From ffc62c792c9a5196cb4ce7a353287dfe20db6524 Mon Sep 17 00:00:00 2001 From: Christoph Berg Date: Fri, 9 Oct 2026 14:12:35 +0200 Subject: New upstream version 3.3.0~beta1+dfsg --- tests/CMakeLists.txt | 50 +- tests/integration/decoder_engine/run_wav_gui.cmake | 70 +++ tests/integration/jt65/check_stream.py | 27 + .../integration/jt9/verify_loaded_libraries.cmake | 39 ++ tests/integration/jtty/run_live_audio.cmake | 36 +- tests/integration/jtty/run_tx_loopback.cmake | 46 +- tests/integration/jtty/tx_loopback.expected.txt | 2 +- tests/release/test_build_type.cmake | 169 ++++++ tests/release/test_expiry_build_step.cmake | 43 ++ tests/release/test_git_archive.cmake | 17 +- tests/release/test_package_version_order.cmake | 59 ++ tests/release/test_release_state.cmake | 107 ++-- tests/release/test_release_state_dependency.cmake | 12 + tests/release/test_release_tarballs.cmake | 44 ++ tests/release/validate_release_state_fixture.cmake | 2 +- .../validate_release_tarballs_fixture.cmake | 4 + tests/unit/audio/CMakeLists.txt | 16 + .../audio/test_audio_input_stream_descriptor.cpp | 12 +- tests/unit/audio/test_echosim_wav_trailer.cpp | 30 +- tests/unit/audio/test_receive_audio_handoff.cpp | 249 +++++++++ tests/unit/audio/test_sound_input.cpp | 85 +++ tests/unit/audio/test_tx_audio_queue.cpp | 9 +- tests/unit/audio/test_wav_input_loading.cpp | 69 +++ tests/unit/common/CMakeLists.txt | 49 ++ tests/unit/common/test_active_stations.cpp | 31 ++ .../common/test_configuration_dialog_layout.cpp | 41 ++ tests/unit/common/test_configuration_radio.cpp | 237 ++++++++ .../unit/common/test_decode_highlighting_model.cpp | 526 ++++++++++++++++++ tests/unit/common/test_frequency_list.cpp | 294 ++++++++++ tests/unit/common/test_frequency_suggestions.cpp | 200 +++++++ tests/unit/common/test_log_window_deletion.cpp | 202 +++++++ tests/unit/common/test_qt_helpers.cpp | 33 ++ tests/unit/common/test_radio_callsign.cpp | 128 +++++ tests/unit/decoder_engine/CMakeLists.txt | 222 ++++++++ .../unit/decoder_engine/decoder_engine_signal.f90 | 190 +++++++ tests/unit/decoder_engine/fst4_engine_signal.f90 | 286 ++++++++++ tests/unit/decoder_engine/jt65_engine_signal.f90 | 52 ++ tests/unit/decoder_engine/jt9_engine_signal.f90 | 88 +++ tests/unit/decoder_engine/q65_engine_signal.f90 | 85 +++ tests/unit/decoder_engine/test_decoder_engine.c | 373 +++++++++++++ .../unit/decoder_engine/test_decoder_engine_fst4.c | 369 +++++++++++++ .../test_decoder_engine_fst4_host.f90 | 211 +++++++ .../unit/decoder_engine/test_decoder_engine_ft4.c | 225 ++++++++ .../unit/decoder_engine/test_decoder_engine_jt65.c | 578 ++++++++++++++++++++ .../test_decoder_engine_jt65_host.f90 | 190 +++++++ .../unit/decoder_engine/test_decoder_engine_jt9.c | 361 ++++++++++++ .../unit/decoder_engine/test_decoder_engine_q65.c | 535 ++++++++++++++++++ .../test_decoder_engine_q65_host.f90 | 236 ++++++++ tests/unit/decoder_ipc/CMakeLists.txt | 43 +- tests/unit/decoder_ipc/check_gui_handshake.py | 70 +++ .../unit/decoder_ipc/decoder_ipc_fortran_probe.f90 | 7 +- .../decoder_ipc/test_decode_operating_context.cpp | 14 + .../decoder_ipc/test_decoder_ipc_handshake.cpp | 603 +++++++++++++++++++++ tests/unit/decoder_ipc/test_decoder_ipc_layout.cpp | 192 +++++++ .../unit/decoder_ipc/test_decoder_ipc_protocol.cpp | 178 +++++- .../decoder_ipc/test_decoder_output_framer.cpp | 106 ++++ tests/unit/decoder_ipc/test_decoder_session.cpp | 561 +++++++++++++++++++ tests/unit/fst4/test_fst4_osd_depth.f90 | 76 ++- tests/unit/ft8/CMakeLists.txt | 3 +- tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp | 46 +- tests/unit/jpl/test_jpl_resilience.f90 | 63 ++- tests/unit/jt65/test_jt65_decode_pipeline.f90 | 52 +- tests/unit/jt65/test_jt65_xcor_silence.f90 | 8 +- tests/unit/jt65/test_map65_jt65_handoff.f90 | 55 +- tests/unit/jt9/test_jt9_cli_validation.cmake | 13 + tests/unit/jt9/test_jt9_input_validation.f90 | 8 +- tests/unit/jtty/CMakeLists.txt | 61 ++- tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp | 22 +- tests/unit/jtty/test_jtty_continuous_decode.f90 | 316 +++++++++++ tests/unit/jtty/test_jtty_draft_acceptance.cpp | 128 ----- tests/unit/jtty/test_jtty_get_updates.f90 | 19 +- tests/unit/jtty/test_jtty_live_entry.cpp | 86 +++ tests/unit/jtty/test_jtty_messages.cpp | 294 +++++++--- tests/unit/jtty/test_jtty_n1mm.cpp | 177 ++++++ tests/unit/jtty/test_jtty_overlap_decode.f90 | 14 +- tests/unit/jtty/test_jtty_pack.f90 | 12 +- tests/unit/jtty/test_jtty_receive_history.cpp | 87 +++ tests/unit/jtty/test_jtty_receive_line.cpp | 209 +++++++ tests/unit/jtty/test_jtty_receive_results.cpp | 396 ++++++++++++++ tests/unit/jtty/test_jtty_recording.cpp | 274 ++++++++++ tests/unit/jtty/test_jtty_source_codec.f90 | 19 + tests/unit/jtty/test_jtty_spectrum.cpp | 192 +++++++ tests/unit/jtty/test_jtty_structured_decode.f90 | 155 ++++-- tests/unit/jtty/test_jtty_tbcc_decoder.f90 | 57 +- tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 | 152 +++++- tests/unit/jtty/test_jtty_transmit_queue.cpp | 107 ++++ tests/unit/jtty/test_jtty_tx_lifecycle.cpp | 186 +++++++ tests/unit/jtty/test_jtty_txstream.cpp | 376 +++++++++++++ tests/unit/jtty/test_jtty_waterfall.cpp | 104 ++++ tests/unit/map65/CMakeLists.txt | 11 + .../map65/decode_history/decode_history_stubs.f90 | 16 +- .../decode_history/test_map65_decode_history.f90 | 108 +++- tests/unit/map65/messages_retention/CMakeLists.txt | 17 + .../messages_retention_stubs.f90 | 35 ++ .../test_map65_messages_retention.f90 | 189 +++++++ tests/unit/map65/test_map65_deep_search_cache.f90 | 5 +- tests/unit/map65/test_map65_filbig_boundary.f90 | 64 +++ tests/unit/map65/test_map65_ptt_unix.c | 489 +++++++++++++++++ tests/unit/map65/test_map65_ptt_windows.c | 323 +++++++++++ tests/unit/map65/test_map65_q65_dphi.f90 | 17 +- tests/unit/map65/test_map65_q65_handoff.f90 | 117 ++++ tests/unit/map65/test_map65_symspec_contract.f90 | 118 ++++ tests/unit/map65/windows_fake/windows.h | 29 + tests/unit/network/CMakeLists.txt | 31 ++ tests/unit/network/test_livecq_upload.cpp | 257 +++++++++ tests/unit/network/test_lotw_users.cpp | 312 +++++++++++ tests/unit/network/test_map65_livecq_decode.cpp | 196 +++++++ tests/unit/network/test_sample_downloader.cpp | 151 ++++++ tests/unit/packjt77/CMakeLists.txt | 7 + .../unit/packjt77/test_packjt77_context_state.f90 | 117 ++++ tests/unit/packjt77/test_packjt77_grammar_gate.f90 | 49 +- tests/unit/packjt77/test_packjt77_hash_state.f90 | 28 +- .../unit/packjt77/test_packjt77_schema_decoder.f90 | 34 ++ .../packjt77/test_packjt77sdvar_invariants.f90 | 11 +- tests/unit/q65/CMakeLists.txt | 16 +- tests/unit/q65/test_map65_wideband_sync_rows.f90 | 132 +++++ tests/unit/q65/test_q65_caller_display.f90 | 123 +++++ tests/unit/q65/test_q65_callers.f90 | 163 ++++++ tests/unit/q65/test_q65_decode_pipeline.f90 | 138 ++++- tests/unit/q65/test_q65_llh_contracts.c | 70 +++ tests/unit/qmap/CMakeLists.txt | 22 + tests/unit/qmap/test_livecq_parser.cpp | 52 ++ tests/unit/qmap/test_qmap_candidates.f90 | 185 +++++++ tests/unit/qmap/test_qmap_q65_connection.f90 | 123 +++++ tests/unit/qmap/test_qmap_q65_handoff.f90 | 116 ++++ tests/unit/qmap/test_qmap_symspec_contract.f90 | 67 +++ tests/unit/streaming/CMakeLists.txt | 21 +- tests/unit/streaming/test_streaming_consumers.cpp | 199 ++++++- tests/unit/streaming/test_streaming_period.f90 | 116 ++++ tests/unit/superfox/test_superfox_unpack.f90 | 69 ++- .../superfox/test_superfox_unpack_unsupported.f90 | 24 +- tests/unit/tci/test_tci_receive_ownership.cpp | 202 ++++++- 132 files changed, 16546 insertions(+), 503 deletions(-) create mode 100644 tests/integration/decoder_engine/run_wav_gui.cmake create mode 100644 tests/integration/jt65/check_stream.py create mode 100644 tests/integration/jt9/verify_loaded_libraries.cmake create mode 100644 tests/release/test_build_type.cmake create mode 100644 tests/release/test_expiry_build_step.cmake create mode 100644 tests/release/test_package_version_order.cmake create mode 100644 tests/release/test_release_state_dependency.cmake create mode 100644 tests/release/test_release_tarballs.cmake create mode 100644 tests/release/validate_release_tarballs_fixture.cmake create mode 100644 tests/unit/audio/test_sound_input.cpp create mode 100644 tests/unit/common/test_configuration_radio.cpp create mode 100644 tests/unit/common/test_decode_highlighting_model.cpp create mode 100644 tests/unit/common/test_frequency_list.cpp create mode 100644 tests/unit/common/test_frequency_suggestions.cpp create mode 100644 tests/unit/common/test_log_window_deletion.cpp create mode 100644 tests/unit/common/test_radio_callsign.cpp create mode 100644 tests/unit/decoder_engine/CMakeLists.txt create mode 100644 tests/unit/decoder_engine/decoder_engine_signal.f90 create mode 100644 tests/unit/decoder_engine/fst4_engine_signal.f90 create mode 100644 tests/unit/decoder_engine/jt65_engine_signal.f90 create mode 100644 tests/unit/decoder_engine/jt9_engine_signal.f90 create mode 100644 tests/unit/decoder_engine/q65_engine_signal.f90 create mode 100644 tests/unit/decoder_engine/test_decoder_engine.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_fst4.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_fst4_host.f90 create mode 100644 tests/unit/decoder_engine/test_decoder_engine_ft4.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt65.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt65_host.f90 create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt9.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_q65.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_q65_host.f90 create mode 100644 tests/unit/decoder_ipc/check_gui_handshake.py create mode 100644 tests/unit/decoder_ipc/test_decoder_ipc_handshake.cpp create mode 100644 tests/unit/decoder_ipc/test_decoder_ipc_layout.cpp create mode 100644 tests/unit/decoder_ipc/test_decoder_session.cpp create mode 100644 tests/unit/jtty/test_jtty_continuous_decode.f90 delete mode 100644 tests/unit/jtty/test_jtty_draft_acceptance.cpp create mode 100644 tests/unit/jtty/test_jtty_live_entry.cpp create mode 100644 tests/unit/jtty/test_jtty_receive_history.cpp create mode 100644 tests/unit/jtty/test_jtty_receive_line.cpp create mode 100644 tests/unit/jtty/test_jtty_receive_results.cpp create mode 100644 tests/unit/jtty/test_jtty_recording.cpp create mode 100644 tests/unit/jtty/test_jtty_spectrum.cpp create mode 100644 tests/unit/jtty/test_jtty_transmit_queue.cpp create mode 100644 tests/unit/jtty/test_jtty_tx_lifecycle.cpp create mode 100644 tests/unit/jtty/test_jtty_waterfall.cpp create mode 100644 tests/unit/map65/messages_retention/CMakeLists.txt create mode 100644 tests/unit/map65/messages_retention/messages_retention_stubs.f90 create mode 100644 tests/unit/map65/messages_retention/test_map65_messages_retention.f90 create mode 100644 tests/unit/map65/test_map65_filbig_boundary.f90 create mode 100644 tests/unit/map65/test_map65_ptt_unix.c create mode 100644 tests/unit/map65/test_map65_ptt_windows.c create mode 100644 tests/unit/map65/test_map65_q65_handoff.f90 create mode 100644 tests/unit/map65/test_map65_symspec_contract.f90 create mode 100644 tests/unit/map65/windows_fake/windows.h create mode 100644 tests/unit/network/test_livecq_upload.cpp create mode 100644 tests/unit/network/test_lotw_users.cpp create mode 100644 tests/unit/network/test_map65_livecq_decode.cpp create mode 100644 tests/unit/network/test_sample_downloader.cpp create mode 100644 tests/unit/packjt77/test_packjt77_context_state.f90 create mode 100644 tests/unit/q65/test_q65_caller_display.f90 create mode 100644 tests/unit/q65/test_q65_callers.f90 create mode 100644 tests/unit/qmap/test_qmap_candidates.f90 create mode 100644 tests/unit/qmap/test_qmap_q65_connection.f90 create mode 100644 tests/unit/qmap/test_qmap_q65_handoff.f90 create mode 100644 tests/unit/qmap/test_qmap_symspec_contract.f90 create mode 100644 tests/unit/streaming/test_streaming_period.f90 (limited to 'tests') diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 02b3a3e1..341a5143 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,8 +7,24 @@ add_test ( -D TEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/release-state -P ${CMAKE_SOURCE_DIR}/tests/release/test_release_state.cmake) +add_test ( + NAME test_release_tarballs + COMMAND ${CMAKE_COMMAND} + -D SOURCE_DIR=${CMAKE_SOURCE_DIR} + -D TEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/release-tarballs + -P ${CMAKE_SOURCE_DIR}/tests/release/test_release_tarballs.cmake) + +get_property (release_configure_depends DIRECTORY ${CMAKE_SOURCE_DIR} PROPERTY CMAKE_CONFIGURE_DEPENDS) +string (REPLACE ";" "|" release_configure_depends "${release_configure_depends}") +add_test ( + NAME test_release_state_dependency + COMMAND ${CMAKE_COMMAND} + -D SOURCE_DIR=${CMAKE_SOURCE_DIR} + -D CONFIGURE_DEPENDS=${release_configure_depends} + -P ${CMAKE_SOURCE_DIR}/tests/release/test_release_state_dependency.cmake) + find_package (Git QUIET) -if (GIT_FOUND) +if (GIT_FOUND AND EXISTS "${CMAKE_SOURCE_DIR}/.git") add_test ( NAME test_release_git_archive COMMAND ${CMAKE_COMMAND} @@ -18,6 +34,37 @@ if (GIT_FOUND) -P ${CMAKE_SOURCE_DIR}/tests/release/test_git_archive.cmake) endif () +add_test ( + NAME test_release_build_type + COMMAND ${CMAKE_COMMAND} + -D SOURCE_DIR=${CMAKE_SOURCE_DIR} + -D TEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/release-build-type + -D GIT_EXECUTABLE=${GIT_EXECUTABLE} + -P ${CMAKE_SOURCE_DIR}/tests/release/test_build_type.cmake) + +# A cross-compiled tree runs its tests in another container than the one that built it. +if (NOT CMAKE_CROSSCOMPILING) + add_test ( + NAME test_release_expiry_build_step + COMMAND ${CMAKE_COMMAND} + -D SOURCE_DIR=${CMAKE_SOURCE_DIR} + -D BINARY_DIR=${CMAKE_BINARY_DIR} + -D TEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/release-expiry-build-step + -P ${CMAKE_SOURCE_DIR}/tests/release/test_expiry_build_step.cmake) + set_tests_properties (test_release_expiry_build_step PROPERTIES RUN_SERIAL TRUE) +endif () + +foreach (package_tool dpkg rpm) + add_test ( + NAME test_release_package_order_${package_tool} + COMMAND ${CMAKE_COMMAND} + -D SOURCE_DIR=${CMAKE_SOURCE_DIR} + -D TOOL=${package_tool} + -P ${CMAKE_SOURCE_DIR}/tests/release/test_package_version_order.cmake) + set_tests_properties (test_release_package_order_${package_tool} PROPERTIES + SKIP_REGULAR_EXPRESSION "Skipped: ${package_tool} is not installed") +endforeach () + add_compile_options ("$<$:-Wall;-Wno-conversion;-fno-second-underscore;-fno-f2c>") add_compile_options ("$<$,$>:-fbounds-check>") add_compile_options ("$<$,$>>:-funroll-all-loops>") @@ -35,6 +82,7 @@ add_subdirectory (unit/audio) add_subdirectory (unit/band_hopping) add_subdirectory (unit/common) add_subdirectory (unit/decoder_ipc) +add_subdirectory (unit/decoder_engine) add_subdirectory (unit/hrd) add_subdirectory (unit/hash) add_subdirectory (unit/message_filter) diff --git a/tests/integration/decoder_engine/run_wav_gui.cmake b/tests/integration/decoder_engine/run_wav_gui.cmake new file mode 100644 index 00000000..88979815 --- /dev/null +++ b/tests/integration/decoder_engine/run_wav_gui.cmake @@ -0,0 +1,70 @@ +if (NOT DEFINED MODE) + set (MODE JT9) +endif () +if (NOT MODE STREQUAL "JT9" AND NOT MODE STREQUAL "JT65" AND NOT MODE STREQUAL "Q65" + AND NOT MODE STREQUAL "FST4" AND NOT MODE STREQUAL "FST4W") + message (FATAL_ERROR "MODE must be JT9, JT65, Q65, FST4, or FST4W") +endif () +string (TOLOWER "${MODE}" mode_option) + +foreach (required_variable WSJTX SAMPLE EXPECTED_MESSAGE WORK_DIR) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +string (RANDOM LENGTH 12 ALPHABET 0123456789abcdef run_id) +set (rig_name "CTEST-${MODE}-WAV-${run_id}") +set (ipc_dir "${WORK_DIR}-ipc") +file (REMOVE_RECURSE "${WORK_DIR}" "${ipc_dir}") +file (MAKE_DIRECTORY + "${WORK_DIR}/config" + "${WORK_DIR}/data" + "${WORK_DIR}/cache" + "${ipc_dir}") + +if (MODE STREQUAL "FST4" OR MODE STREQUAL "FST4W") + set (timestamped_sample "${WORK_DIR}/261003_001500.wav") + configure_file ("${SAMPLE}" "${timestamped_sample}" COPYONLY) + set (SAMPLE "${timestamped_sample}") +endif () + +set (wsjtx_environment + "XDG_CONFIG_HOME=${WORK_DIR}/config" + "XDG_DATA_HOME=${WORK_DIR}/data" + "XDG_CACHE_HOME=${WORK_DIR}/cache" + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_${mode_option}_wav") +if (NOT APPLE) + list (APPEND wsjtx_environment "TMPDIR=${ipc_dir}") +endif () +if (WIN32) + list (APPEND wsjtx_environment + "APPDATA=${WORK_DIR}/config" + "LOCALAPPDATA=${WORK_DIR}/data" + "TEMP=${ipc_dir}" + "TMP=${ipc_dir}") +endif () + +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + ${wsjtx_environment} + "${WSJTX}" + --test-mode + --${mode_option}-wav-test "${SAMPLE}" + --${mode_option}-wav-expected "${EXPECTED_MESSAGE}" + --rig-name "${rig_name}" + WORKING_DIRECTORY "${WORK_DIR}" + TIMEOUT 375 + RESULT_VARIABLE wsjtx_result + OUTPUT_VARIABLE wsjtx_stdout + ERROR_VARIABLE wsjtx_stderr) +file (WRITE "${WORK_DIR}/stdout.log" "${wsjtx_stdout}") +file (WRITE "${WORK_DIR}/stderr.log" "${wsjtx_stderr}") +if (NOT wsjtx_result STREQUAL "0") + message (FATAL_ERROR + "WSJT-X ${MODE} WAV test failed with exit code ${wsjtx_result}\n" + "stdout:\n${wsjtx_stdout}\n" + "stderr:\n${wsjtx_stderr}") +endif () + +message (STATUS "WSJT-X ${MODE} WAV decode and repeat passed") diff --git a/tests/integration/jt65/check_stream.py b/tests/integration/jt65/check_stream.py new file mode 100644 index 00000000..161c9a67 --- /dev/null +++ b/tests/integration/jt65/check_stream.py @@ -0,0 +1,27 @@ +import json +from pathlib import Path +import subprocess +import sys + + +decoder, harness, recording, work_dir = sys.argv[1:] +work = Path(work_dir) +work.mkdir(parents=True, exist_ok=True) +result = subprocess.run( + [sys.executable, harness, decoder, recording, "--mode", "JT65", + "--depth-level", "1", "--nfa", "1300", "--nfb", "1700", "--quiet"], + cwd=work, capture_output=True, text=True, timeout=60, +) +(work / "stdout.log").write_text(result.stdout) +(work / "stderr.log").write_text(result.stderr) +if result.returncode: + raise SystemExit(f"JT65 stream failed: {result.stdout}\n{result.stderr}") +events = [json.loads(line) for line in result.stdout.splitlines() if line.startswith("{")] +if any(event.get("t") == "error" for event in events): + raise SystemExit(f"JT65 stream reported an error: {events}") +if not any(event.get("t") == "decode" and event.get("mode") == "JT65" + and event.get("message", "").strip() == "K1ABC W9XYZ FN42" for event in events): + raise SystemExit(f"JT65 stream did not decode the supplied recording: {events}") +if sum(event.get("t") == "decode_finished" for event in events) != 1: + raise SystemExit(f"JT65 stream must complete the reception exactly once: {events}") +print("JT65 streaming PCM decode and completion passed") diff --git a/tests/integration/jt9/verify_loaded_libraries.cmake b/tests/integration/jt9/verify_loaded_libraries.cmake new file mode 100644 index 00000000..7354fecd --- /dev/null +++ b/tests/integration/jt9/verify_loaded_libraries.cmake @@ -0,0 +1,39 @@ +# Fails if EXECUTABLE loads Boost, Qt or ICU, which the release tarballs' +# decoder programs use no symbol from: they load them only when linked +# without --as-needed (Linux) or -dead_strip_dylibs (macOS). +foreach (required_variable LISTER EXECUTABLE) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +if (LISTER MATCHES "otool$") + set (lister_arguments -L) +else () + set (lister_arguments -dW) +endif () +execute_process ( + COMMAND "${LISTER}" ${lister_arguments} "${EXECUTABLE}" + RESULT_VARIABLE lister_result + OUTPUT_VARIABLE lister_stdout + ERROR_VARIABLE lister_stderr) +if (NOT "${lister_result}" STREQUAL "0") + message (FATAL_ERROR + "${LISTER} exited with ${lister_result}\n" + "stdout:\n${lister_stdout}\n" + "stderr:\n${lister_stderr}") +endif () + +if (LISTER MATCHES "otool$") + # The first line names the file itself. + string (FIND "${lister_stdout}" "\n" first_newline) + string (SUBSTRING "${lister_stdout}" ${first_newline} -1 libraries) +else () + string (REGEX MATCHALL "\\(NEEDED\\)[^\n]*" libraries "${lister_stdout}") + string (REPLACE ";" "\n" libraries "${libraries}") +endif () +string (REGEX MATCHALL "[^\n]*(boost|QtCore|Qt5Core|libicu)[^\n]*" unused "${libraries}") +if (unused) + string (REPLACE ";" "\n" unused "${unused}") + message (FATAL_ERROR "${EXECUTABLE} loads libraries it uses no symbol from:\n${unused}") +endif () diff --git a/tests/integration/jtty/run_live_audio.cmake b/tests/integration/jtty/run_live_audio.cmake index 1dcbd7a2..fe27f1b3 100644 --- a/tests/integration/jtty/run_live_audio.cmake +++ b/tests/integration/jtty/run_live_audio.cmake @@ -4,8 +4,24 @@ foreach (required_variable SJTTY WSJTX WORK_DIR EXPECTED) endif () endforeach () +if (NOT DEFINED AUDIO_SPEED) + set (AUDIO_SPEED 4) +endif () +if (NOT AUDIO_SPEED MATCHES "^[1-4]$") + message (FATAL_ERROR "AUDIO_SPEED must be an integer from 1 through 4") +endif () +if (NOT DEFINED TEST_ID) + set (TEST_ID "test_wsjtx_live_audio_jtty") +endif () +if (NOT TEST_ID MATCHES "^[A-Za-z0-9_-]+$") + message (FATAL_ERROR "TEST_ID must contain only letters, digits, underscores, or hyphens") +endif () + +string (RANDOM LENGTH 12 ALPHABET 0123456789abcdef run_id) +set (rig_name "CTEST-JTTY-${run_id}-LIVE") + set (ipc_dir "${WORK_DIR}-ipc") -file (REMOVE_RECURSE "${WORK_DIR}") +file (REMOVE_RECURSE "${WORK_DIR}" "${ipc_dir}") file (MAKE_DIRECTORY "${WORK_DIR}/config" "${WORK_DIR}/data" @@ -17,9 +33,12 @@ execute_process ( "CQ TEST DE KA1ABC LIVE AUDIO SMOKE TEST" 1500 0.25 AW 0 384 1 99 WORKING_DIRECTORY "${WORK_DIR}" + TIMEOUT 20 RESULT_VARIABLE generator_result OUTPUT_VARIABLE generator_stdout ERROR_VARIABLE generator_stderr) +file (WRITE "${WORK_DIR}/generator.stdout.log" "${generator_stdout}") +file (WRITE "${WORK_DIR}/generator.stderr.log" "${generator_stderr}") if (NOT generator_result STREQUAL "0") message (FATAL_ERROR "sjtty failed with exit code ${generator_result}\n" @@ -40,10 +59,17 @@ set (wsjtx_environment "XDG_CONFIG_HOME=${WORK_DIR}/config" "XDG_DATA_HOME=${WORK_DIR}/data" "XDG_CACHE_HOME=${WORK_DIR}/cache" - "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_live_audio_jtty") + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-${TEST_ID}") if (NOT APPLE) list (APPEND wsjtx_environment "TMPDIR=${ipc_dir}") endif () +if (WIN32) + list (APPEND wsjtx_environment + "APPDATA=${WORK_DIR}/config" + "LOCALAPPDATA=${WORK_DIR}/data" + "TEMP=${ipc_dir}" + "TMP=${ipc_dir}") +endif () execute_process ( COMMAND "${CMAKE_COMMAND}" -E env @@ -51,11 +77,15 @@ execute_process ( "${WSJTX}" --jtty-live-audio-test "${fixture}" --jtty-live-audio-expected "${EXPECTED}" - --rig-name CTEST-LIVE-AUDIO-JTTY + --test-audio-speed "${AUDIO_SPEED}" + --rig-name "${rig_name}" WORKING_DIRECTORY "${WORK_DIR}" + TIMEOUT 110 RESULT_VARIABLE wsjtx_result OUTPUT_VARIABLE wsjtx_stdout ERROR_VARIABLE wsjtx_stderr) +file (WRITE "${WORK_DIR}/receive.stdout.log" "${wsjtx_stdout}") +file (WRITE "${WORK_DIR}/receive.stderr.log" "${wsjtx_stderr}") if (NOT wsjtx_result STREQUAL "0") message (FATAL_ERROR "WSJT-X JTTY live-audio smoke test failed with exit code ${wsjtx_result}\n" diff --git a/tests/integration/jtty/run_tx_loopback.cmake b/tests/integration/jtty/run_tx_loopback.cmake index cb6c0494..8446d282 100644 --- a/tests/integration/jtty/run_tx_loopback.cmake +++ b/tests/integration/jtty/run_tx_loopback.cmake @@ -4,8 +4,24 @@ foreach (required_variable WSJTX WORK_DIR EXPECTED) endif () endforeach () +if (NOT DEFINED AUDIO_SPEED) + set (AUDIO_SPEED 4) +endif () +if (NOT AUDIO_SPEED MATCHES "^[1-4]$") + message (FATAL_ERROR "AUDIO_SPEED must be an integer from 1 through 4") +endif () +if (NOT DEFINED TEST_ID) + set (TEST_ID "test_wsjtx_jtty_tx_loopback") +endif () +if (NOT TEST_ID MATCHES "^[A-Za-z0-9_-]+$") + message (FATAL_ERROR "TEST_ID must contain only letters, digits, underscores, or hyphens") +endif () + +string (RANDOM LENGTH 12 ALPHABET 0123456789abcdef run_id) +set (rig_name "CTEST-JTTY-${run_id}") + set (ipc_dir "${WORK_DIR}-ipc") -file (REMOVE_RECURSE "${WORK_DIR}") +file (REMOVE_RECURSE "${WORK_DIR}" "${ipc_dir}") file (MAKE_DIRECTORY "${WORK_DIR}/capture/config" "${WORK_DIR}/capture/data" @@ -21,27 +37,43 @@ set (capture_environment "XDG_CONFIG_HOME=${WORK_DIR}/capture/config" "XDG_DATA_HOME=${WORK_DIR}/capture/data" "XDG_CACHE_HOME=${WORK_DIR}/capture/cache" - "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_jtty_tx_loopback") + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-${TEST_ID}") set (replay_environment "XDG_CONFIG_HOME=${WORK_DIR}/replay/config" "XDG_DATA_HOME=${WORK_DIR}/replay/data" "XDG_CACHE_HOME=${WORK_DIR}/replay/cache" - "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_jtty_tx_loopback") + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-${TEST_ID}") if (NOT APPLE) list (APPEND capture_environment "TMPDIR=${ipc_dir}/capture") list (APPEND replay_environment "TMPDIR=${ipc_dir}/replay") endif () +if (WIN32) + list (APPEND capture_environment + "APPDATA=${WORK_DIR}/capture/config" + "LOCALAPPDATA=${WORK_DIR}/capture/data" + "TEMP=${ipc_dir}/capture" + "TMP=${ipc_dir}/capture") + list (APPEND replay_environment + "APPDATA=${WORK_DIR}/replay/config" + "LOCALAPPDATA=${WORK_DIR}/replay/data" + "TEMP=${ipc_dir}/replay" + "TMP=${ipc_dir}/replay") +endif () execute_process ( COMMAND "${CMAKE_COMMAND}" -E env ${capture_environment} "${WSJTX}" --jtty-tx-loopback-test "${capture}" - --rig-name CTEST-JTTY-TX-CAPTURE + --test-audio-speed "${AUDIO_SPEED}" + --rig-name "${rig_name}-CAPTURE" WORKING_DIRECTORY "${WORK_DIR}/capture" + TIMEOUT 210 RESULT_VARIABLE capture_result OUTPUT_VARIABLE capture_stdout ERROR_VARIABLE capture_stderr) +file (WRITE "${WORK_DIR}/capture.stdout.log" "${capture_stdout}") +file (WRITE "${WORK_DIR}/capture.stderr.log" "${capture_stderr}") if (NOT capture_result STREQUAL "0") message (FATAL_ERROR "WSJT-X JTTY transmit capture failed with exit code ${capture_result}\n" @@ -69,11 +101,15 @@ execute_process ( "${WSJTX}" --jtty-live-audio-test "${capture}" --jtty-live-audio-expected "${EXPECTED}" - --rig-name CTEST-JTTY-TX-REPLAY + --test-audio-speed "${AUDIO_SPEED}" + --rig-name "${rig_name}-REPLAY" WORKING_DIRECTORY "${WORK_DIR}/replay" + TIMEOUT 400 RESULT_VARIABLE replay_result OUTPUT_VARIABLE replay_stdout ERROR_VARIABLE replay_stderr) +file (WRITE "${WORK_DIR}/replay.stdout.log" "${replay_stdout}") +file (WRITE "${WORK_DIR}/replay.stderr.log" "${replay_stderr}") if (NOT replay_result STREQUAL "0") message (FATAL_ERROR "WSJT-X JTTY transmit replay failed with exit code ${replay_result}\n" diff --git a/tests/integration/jtty/tx_loopback.expected.txt b/tests/integration/jtty/tx_loopback.expected.txt index 3761f4f4..9739495c 100644 --- a/tests/integration/jtty/tx_loopback.expected.txt +++ b/tests/integration/jtty/tx_loopback.expected.txt @@ -1,2 +1,2 @@ WB9XYZ 599 0123 -WB9XYZ TU CQ KA1ABC CQ +SECOND MESSAGE QUEUED DURING FIRST STAYS PENDING UNTIL ITS OWN AIRTIME ARRIVES diff --git a/tests/release/test_build_type.cmake b/tests/release/test_build_type.cmake new file mode 100644 index 00000000..ca40d8cd --- /dev/null +++ b/tests/release/test_build_type.cmake @@ -0,0 +1,169 @@ +cmake_minimum_required (VERSION 3.12) + +if (NOT SOURCE_DIR) + message (FATAL_ERROR "SOURCE_DIR is required") +endif () + +include ("${SOURCE_DIR}/CMake/Modules/set_build_type.cmake") +set (PROJECT_NAME wsjtx) +set (PROJECT_VERSION_MAJOR 3) +set (PROJECT_VERSION_MINOR 3) +set (PROJECT_VERSION_PATCH 0) + +if (DEFINED CHECK_CHANNEL) + set (WSJT_RELEASE_CHANNEL "${CHECK_CHANNEL}" CACHE STRING "" FORCE) + set (WSJT_PRERELEASE_NUMBER "${CHECK_PRERELEASE}" CACHE STRING "" FORCE) + set_build_type () + return () +endif () +if (DEFINED CHECK_SOURCE_DATE_EPOCH) + set (ENV{SOURCE_DATE_EPOCH} "${CHECK_SOURCE_DATE_EPOCH}") + wsjt_prerelease_expiry (DEVEL "${SOURCE_DIR}" expiry) + return () +endif () + +if (NOT TEST_BINARY_DIR) + message (FATAL_ERROR "TEST_BINARY_DIR is required") +endif () + +function (assert_equal actual expected description) + if (NOT "${actual}" STREQUAL "${expected}") + message (FATAL_ERROR "${description}: expected '${expected}', got '${actual}'") + endif () +endfunction () + +function (expect_build_type channel prerelease revision package_revision) + set (WSJT_RELEASE_CHANNEL "${channel}" CACHE STRING "" FORCE) + set (WSJT_PRERELEASE_NUMBER "${prerelease}" CACHE STRING "" FORCE) + set_build_type () + assert_equal ("${BUILD_TYPE_REVISION}" "${revision}" "${channel} ${prerelease} version suffix") + assert_equal ("${BUILD_TYPE_PACKAGE_REVISION}" "${package_revision}" "${channel} ${prerelease} package suffix") +endfunction () + +function (expect_rejected description) + execute_process ( + COMMAND "${CMAKE_COMMAND}" -D SOURCE_DIR=${SOURCE_DIR} ${ARGN} -P "${CMAKE_CURRENT_LIST_FILE}" + RESULT_VARIABLE rejected_result + OUTPUT_QUIET + ERROR_QUIET) + if (rejected_result EQUAL 0) + message (FATAL_ERROR "Invalid input was accepted: ${description}") + endif () +endfunction () + +expect_build_type (DEVEL "" "-devel" "-devel") +expect_build_type (BETA 1 "-beta1" "~beta1") +expect_build_type (beta 10 "-beta10" "~beta10") +expect_build_type (RC 2 "-rc2" "~rc2") +expect_build_type (GA "" "" "") + +expect_rejected ("BETA without a number" -D CHECK_CHANNEL=BETA -D CHECK_PRERELEASE=) +expect_rejected ("BETA 0" -D CHECK_CHANNEL=BETA -D CHECK_PRERELEASE=0) +expect_rejected ("RC without a number" -D CHECK_CHANNEL=RC -D CHECK_PRERELEASE=) +expect_rejected ("DEVEL with a number" -D CHECK_CHANNEL=DEVEL -D CHECK_PRERELEASE=1) +expect_rejected ("GA with a number" -D CHECK_CHANNEL=GA -D CHECK_PRERELEASE=1) +expect_rejected ("unknown channel" -D CHECK_CHANNEL=ALPHA -D CHECK_PRERELEASE=1) + +set (unversioned "${TEST_BINARY_DIR}/expiry-unversioned") +file (MAKE_DIRECTORY "${unversioned}") +set (checkout "${unversioned}") +if (GIT_EXECUTABLE) + set (checkout "${TEST_BINARY_DIR}/expiry-checkout") + file (REMOVE_RECURSE "${checkout}") + file (MAKE_DIRECTORY "${checkout}") + set (git "${GIT_EXECUTABLE}" -C "${checkout}" + -c user.name=Release -c user.email=release@example.invalid -c commit.gpgsign=false) + execute_process (COMMAND ${git} init -q RESULT_VARIABLE init_result) + execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + "GIT_AUTHOR_DATE=1700000000 +0000" "GIT_COMMITTER_DATE=1700000000 +0000" + ${git} commit -q --allow-empty -m expiry + RESULT_VARIABLE commit_result) + if (NOT init_result EQUAL 0 OR NOT commit_result EQUAL 0) + message (FATAL_ERROR "Could not create the expiry test checkout") + endif () +endif () + +# 2025-09-30T14:20:00Z expires at 2025-12-29T23:59:59Z. +set (ENV{SOURCE_DATE_EPOCH} 1759242000) +foreach (channel DEVEL BETA RC) + wsjt_prerelease_expiry (${channel} "${checkout}" expiry) + assert_equal ("${expiry}" "1767052799" "${channel} expiry from SOURCE_DATE_EPOCH") +endforeach () +wsjt_prerelease_expiry (GA "${checkout}" expiry) +assert_equal ("${expiry}" "0" "GA expiry") +expect_rejected ("malformed SOURCE_DATE_EPOCH" -D CHECK_SOURCE_DATE_EPOCH=yesterday) +unset (ENV{SOURCE_DATE_EPOCH}) + +# The build-time step as revisiontag runs it, configured at 2020-09-13T12:26:40Z. +function (write_expiry_header channel source_dir result_out) + execute_process ( + COMMAND "${CMAKE_COMMAND}" + -D CHANNEL=${channel} + -D SOURCE_DIR=${source_dir} + -D OUTPUT_DIR=${TEST_BINARY_DIR} + -D GIT_EXECUTABLE=${GIT_EXECUTABLE} + -D CONFIGURE_EPOCH=1600000000 + -P "${SOURCE_DIR}/CMake/prerelease_expiry.cmake" + RESULT_VARIABLE header_result + OUTPUT_QUIET + ERROR_VARIABLE header_error) + set (${result_out} "${header_result}" PARENT_SCOPE) + set (header_error "${header_error}" PARENT_SCOPE) +endfunction () + +function (expect_expiry_header channel source_dir expected description) + write_expiry_header (${channel} "${source_dir}" header_result) + if (NOT header_result EQUAL 0) + message (FATAL_ERROR "${description}: the build-time expiry step failed: ${header_error}") + endif () + file (READ "${TEST_BINARY_DIR}/prerelease_expiry.h" header) + assert_equal ("${header}" "#define WSJT_PRERELEASE_EXPIRY ${expected}\n" "${description}") +endfunction () + +file (REMOVE "${TEST_BINARY_DIR}/prerelease_expiry.h") +expect_expiry_header (BETA "${unversioned}" 1607817599 "build-time expiry without Git, from the configure time") +set (ENV{SOURCE_DATE_EPOCH} 1700000000) +expect_expiry_header (DEVEL "${unversioned}" 1707782399 "build-time expiry from SOURCE_DATE_EPOCH") +file (TIMESTAMP "${TEST_BINARY_DIR}/prerelease_expiry.h" written "%s" UTC) +execute_process (COMMAND "${CMAKE_COMMAND}" -E sleep 1) +expect_expiry_header (RC "${unversioned}" 1707782399 "build-time expiry, unchanged") +file (TIMESTAMP "${TEST_BINARY_DIR}/prerelease_expiry.h" rewritten "%s" UTC) +assert_equal ("${rewritten}" "${written}" "an unchanged expiry rewrote the header") +expect_expiry_header (GA "${unversioned}" 0 "build-time GA expiry") +unset (ENV{SOURCE_DATE_EPOCH}) +foreach (channel "" ALPHA) + write_expiry_header ("${channel}" "${unversioned}" header_result) + if (header_result EQUAL 0) + message (FATAL_ERROR "The build-time expiry step accepted the channel \"${channel}\"") + endif () +endforeach () + +if (GIT_EXECUTABLE) + # Committed 2023-11-14T22:13:20Z; expires at 2024-02-12T23:59:59Z. + wsjt_prerelease_expiry (RC "${checkout}" expiry) + assert_equal ("${expiry}" "1707782399" "expiry from the commit date") + expect_expiry_header (RC "${checkout}" 1707782399 "build-time expiry from the commit date") + + execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + "GIT_AUTHOR_DATE=1759242000 +0000" "GIT_COMMITTER_DATE=1759242000 +0000" + ${git} commit -q --allow-empty -m "expiry 2" + RESULT_VARIABLE commit_result) + if (NOT commit_result EQUAL 0) + message (FATAL_ERROR "Could not add a commit to the expiry test checkout") + endif () + expect_expiry_header (BETA "${checkout}" 1767052799 "build-time expiry after a new commit") + set (ENV{SOURCE_DATE_EPOCH} 1700000000) + expect_expiry_header (DEVEL "${checkout}" 1707782399 "build-time SOURCE_DATE_EPOCH over the commit date") + unset (ENV{SOURCE_DATE_EPOCH}) +endif () + +string (TIMESTAMP before "%s" UTC) +wsjt_prerelease_expiry (BETA "${unversioned}" expiry) +string (TIMESTAMP after "%s" UTC) +math (EXPR earliest "(${before} / 86400 + 91) * 86400 - 1") +math (EXPR latest "(${after} / 86400 + 91) * 86400 - 1") +if (NOT expiry MATCHES "^[0-9]+$" OR expiry LESS earliest OR expiry GREATER latest) + message (FATAL_ERROR "expiry without Git: expected ${earliest}..${latest}, got '${expiry}'") +endif () diff --git a/tests/release/test_expiry_build_step.cmake b/tests/release/test_expiry_build_step.cmake new file mode 100644 index 00000000..59e2b957 --- /dev/null +++ b/tests/release/test_expiry_build_step.cmake @@ -0,0 +1,43 @@ +cmake_minimum_required (VERSION 3.12) + +if (NOT SOURCE_DIR OR NOT BINARY_DIR OR NOT TEST_BINARY_DIR) + message (FATAL_ERROR "SOURCE_DIR, BINARY_DIR, and TEST_BINARY_DIR are required") +endif () + +# A pending re-run of CMake must see the real environment, not the SOURCE_DATE_EPOCH set below. +execute_process ( + COMMAND "${CMAKE_COMMAND}" --build "${BINARY_DIR}" --target revisiontag + RESULT_VARIABLE build_result + OUTPUT_VARIABLE build_output + ERROR_VARIABLE build_output) +if (NOT build_result EQUAL 0) + message (FATAL_ERROR "Building revisiontag failed:\n${build_output}") +endif () +file (STRINGS "${BINARY_DIR}/CMakeCache.txt" channel REGEX "^WSJT_RELEASE_CHANNEL:[A-Z]+=") +string (REGEX REPLACE "^[^=]*=" "" channel "${channel}") +if (NOT channel MATCHES "^(DEVEL|BETA|RC|GA)$") + message (FATAL_ERROR "No release channel in ${BINARY_DIR}/CMakeCache.txt") +endif () + +include ("${SOURCE_DIR}/CMake/Modules/set_build_type.cmake") +set (ENV{SOURCE_DATE_EPOCH} 1700000000) +wsjt_prerelease_expiry ("${channel}" "${SOURCE_DIR}" expected) + +set (header "${BINARY_DIR}/prerelease_expiry.h") +# file (COPY) keeps the timestamp, so restoring the header does not recompile main.cpp. +file (REMOVE_RECURSE "${TEST_BINARY_DIR}") +file (COPY "${header}" DESTINATION "${TEST_BINARY_DIR}") +execute_process ( + COMMAND "${CMAKE_COMMAND}" --build "${BINARY_DIR}" --target revisiontag + RESULT_VARIABLE build_result + OUTPUT_VARIABLE build_output + ERROR_VARIABLE build_output) +file (READ "${header}" built) +file (COPY "${TEST_BINARY_DIR}/prerelease_expiry.h" DESTINATION "${BINARY_DIR}") + +if (NOT build_result EQUAL 0) + message (FATAL_ERROR "Building revisiontag failed:\n${build_output}") +endif () +if (NOT built STREQUAL "#define WSJT_PRERELEASE_EXPIRY ${expected}\n") + message (FATAL_ERROR "revisiontag wrote '${built}', expected ${expected} from SOURCE_DATE_EPOCH") +endif () diff --git a/tests/release/test_git_archive.cmake b/tests/release/test_git_archive.cmake index 96cf78bc..6fd1c86d 100644 --- a/tests/release/test_git_archive.cmake +++ b/tests/release/test_git_archive.cmake @@ -36,11 +36,20 @@ execute_process ( if (NOT state_result EQUAL 0) message (FATAL_ERROR "Extracted Git archive did not preserve release identity") endif () +execute_process ( + COMMAND "${CMAKE_COMMAND}" + -D SOURCE_DIR=${extract_dir} + -D TEST_BINARY_DIR=${TEST_BINARY_DIR}/archive-ctest-fixtures + -P ${extract_dir}/tests/release/test_release_state.cmake + RESULT_VARIABLE state_result) +if (NOT state_result EQUAL 0) + message (FATAL_ERROR "test_release_state fails when run from the extracted Git archive") +endif () include ("${extract_dir}/CMake/Modules/read_release_state.cmake") wsjt_read_release_state ( "${extract_dir}/release-state.txt" - archive_version archive_channel archive_rc archive_revision) + archive_version archive_channel archive_prerelease archive_revision) include ("${extract_dir}/CMake/Modules/set_build_type.cmake") set (PROJECT_NAME wsjtx) string (REPLACE "." ";" archive_version_parts "${archive_version}") @@ -48,12 +57,14 @@ list (GET archive_version_parts 0 PROJECT_VERSION_MAJOR) list (GET archive_version_parts 1 PROJECT_VERSION_MINOR) list (GET archive_version_parts 2 PROJECT_VERSION_PATCH) set (WSJT_RELEASE_CHANNEL "${archive_channel}" CACHE STRING "" FORCE) -set (WSJT_RC_NUMBER "${archive_rc}" CACHE STRING "" FORCE) +set (WSJT_PRERELEASE_NUMBER "${archive_prerelease}" CACHE STRING "" FORCE) set_build_type () if (archive_channel STREQUAL "DEVEL") set (expected_version "${archive_version}-devel") +elseif (archive_channel STREQUAL "BETA") + set (expected_version "${archive_version}-beta${archive_prerelease}") elseif (archive_channel STREQUAL "RC") - set (expected_version "${archive_version}-rc${archive_rc}") + set (expected_version "${archive_version}-rc${archive_prerelease}") else () set (expected_version "${archive_version}") endif () diff --git a/tests/release/test_package_version_order.cmake b/tests/release/test_package_version_order.cmake new file mode 100644 index 00000000..c383bcd9 --- /dev/null +++ b/tests/release/test_package_version_order.cmake @@ -0,0 +1,59 @@ +cmake_minimum_required (VERSION 3.12) + +if (NOT SOURCE_DIR OR NOT TOOL) + message (FATAL_ERROR "SOURCE_DIR and TOOL are required") +endif () + +find_program (TOOL_EXECUTABLE "${TOOL}") +if (NOT TOOL_EXECUTABLE) + message ("Skipped: ${TOOL} is not installed") + return () +endif () + +include ("${SOURCE_DIR}/CMake/Modules/set_build_type.cmake") +set (PROJECT_NAME wsjtx) + +function (package_version version channel prerelease out) + string (REPLACE "." ";" parts "${version}") + list (GET parts 0 PROJECT_VERSION_MAJOR) + list (GET parts 1 PROJECT_VERSION_MINOR) + list (GET parts 2 PROJECT_VERSION_PATCH) + set (WSJT_RELEASE_CHANNEL "${channel}" CACHE STRING "" FORCE) + set (WSJT_PRERELEASE_NUMBER "${prerelease}" CACHE STRING "" FORCE) + set_build_type () + set (${out} "${version}${BUILD_TYPE_PACKAGE_REVISION}" PARENT_SCOPE) +endfunction () + +function (expect_older older newer) + if (TOOL STREQUAL "dpkg") + execute_process ( + COMMAND "${TOOL_EXECUTABLE}" --compare-versions "${older}" lt "${newer}" + RESULT_VARIABLE comparison) + set (expected 0) + elseif (TOOL STREQUAL "rpm") + execute_process ( + COMMAND "${TOOL_EXECUTABLE}" --eval "%{lua:print(rpm.vercmp('${older}', '${newer}'))}" + OUTPUT_VARIABLE comparison + OUTPUT_STRIP_TRAILING_WHITESPACE) + set (expected -1) + else () + message (FATAL_ERROR "Unsupported package tool: ${TOOL}") + endif () + if (NOT "${comparison}" STREQUAL "${expected}") + message (FATAL_ERROR "${TOOL} does not order ${older} before ${newer} (got '${comparison}')") + endif () +endfunction () + +set (previous "") +foreach (state + "3.3.0;BETA;1" "3.3.0;BETA;2" "3.3.0;BETA;10" "3.3.0;RC;1" "3.3.0;RC;2" "3.3.0;GA;" + "3.3.1;BETA;1") + list (GET state 0 version) + list (GET state 1 channel) + list (GET state 2 prerelease) + package_version ("${version}" "${channel}" "${prerelease}" current) + if (previous) + expect_older ("${previous}" "${current}") + endif () + set (previous "${current}") +endforeach () diff --git a/tests/release/test_release_state.cmake b/tests/release/test_release_state.cmake index 047669fe..beeacf42 100644 --- a/tests/release/test_release_state.cmake +++ b/tests/release/test_release_state.cmake @@ -30,11 +30,12 @@ endfunction () wsjt_read_release_state ( "${SOURCE_DIR}/release-state.txt" - version channel rc revision) + version channel prerelease revision) if (EXPECT_ARCHIVE_REVISION) assert_equal ("${revision}" "${EXPECT_ARCHIVE_REVISION}" "archive revision") -else () +elseif (EXISTS "${SOURCE_DIR}/.git") + # git archive expands the placeholder, so only a checkout must carry it. assert_equal ("${revision}" "" "working-tree archive placeholder") endif () @@ -45,44 +46,60 @@ else () endif () file (MAKE_DIRECTORY "${_fixture_dir}") file (WRITE "${_fixture_dir}/rc.txt" - "version=3.2.0\nchannel=RC\nrc=7\nrevision=0123456789abcdef0123456789abcdef01234567\n") + "version=3.2.0\nchannel=RC\nprerelease=7\nrevision=0123456789abcdef0123456789abcdef01234567\n") wsjt_read_release_state ( "${_fixture_dir}/rc.txt" - version channel rc revision) + version channel prerelease revision) assert_equal ("${channel}" "RC" "RC channel") -assert_equal ("${rc}" "7" "RC number") +assert_equal ("${prerelease}" "7" "RC number") assert_equal ("${revision}" "0123456789abcdef0123456789abcdef01234567" "expanded revision") +file (WRITE "${_fixture_dir}/beta.txt" + "version=3.3.0\nchannel=BETA\nprerelease=12\nrevision=$Format:%H$\nwindows_signing=unsigned\n") +wsjt_read_release_state ( + "${_fixture_dir}/beta.txt" + version channel prerelease revision) +assert_equal ("${channel}" "BETA" "BETA channel") +assert_equal ("${prerelease}" "12" "BETA number") + file (WRITE "${_fixture_dir}/unsigned.txt" - "version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=unsigned\n") + "version=3.2.0\nchannel=RC\nprerelease=1\nrevision=$Format:%H$\nwindows_signing=unsigned\n") wsjt_read_release_state ( "${_fixture_dir}/unsigned.txt" - version channel rc revision) + version channel prerelease revision) assert_equal ("${channel}" "RC" "unsigned release channel") -assert_equal ("${rc}" "1" "unsigned release number") +assert_equal ("${prerelease}" "1" "unsigned release number") file (WRITE "${_fixture_dir}/ga.txt" - "version=3.2.0\nchannel=GA\nrc=\nrevision=$Format:%H$\n") + "version=3.2.0\nchannel=GA\nprerelease=\nrevision=$Format:%H$\n") wsjt_read_release_state ( "${_fixture_dir}/ga.txt" - version channel rc revision) + version channel prerelease revision) assert_equal ("${channel}" "GA" "GA channel") -assert_equal ("${rc}" "" "GA RC number") +assert_equal ("${prerelease}" "" "GA prerelease number") -expect_invalid (ga_with_rc - "version=3.2.0\nchannel=GA\nrc=1\nrevision=$Format:%H$\n") +expect_invalid (ga_with_prerelease + "version=3.2.0\nchannel=GA\nprerelease=1\nrevision=$Format:%H$\n") +expect_invalid (devel_with_prerelease + "version=3.3.0\nchannel=DEVEL\nprerelease=1\nrevision=$Format:%H$\n") expect_invalid (rc_without_number - "version=3.2.0\nchannel=RC\nrc=\nrevision=$Format:%H$\n") + "version=3.2.0\nchannel=RC\nprerelease=\nrevision=$Format:%H$\n") +expect_invalid (beta_without_number + "version=3.3.0\nchannel=BETA\nprerelease=\nrevision=$Format:%H$\nwindows_signing=unsigned\n") +expect_invalid (beta_zero + "version=3.3.0\nchannel=BETA\nprerelease=0\nrevision=$Format:%H$\nwindows_signing=unsigned\n") +expect_invalid (old_rc_key + "version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\n") expect_invalid (invalid_version - "version=3.2\nchannel=DEVEL\nrc=\nrevision=$Format:%H$\n") + "version=3.2\nchannel=DEVEL\nprerelease=\nrevision=$Format:%H$\n") expect_invalid (invalid_revision - "version=3.2.0\nchannel=DEVEL\nrc=\nrevision=not-a-git-object-id\n") + "version=3.2.0\nchannel=DEVEL\nprerelease=\nrevision=not-a-git-object-id\n") expect_invalid (unknown_key - "version=3.2.0\nchannel=DEVEL\nrc=\ncommit=$Format:%H$\n") + "version=3.2.0\nchannel=DEVEL\nprerelease=\ncommit=$Format:%H$\n") expect_invalid (invalid_windows_signing - "version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=ephemeral\n") + "version=3.2.0\nchannel=RC\nprerelease=1\nrevision=$Format:%H$\nwindows_signing=ephemeral\n") expect_invalid (duplicate_windows_signing - "version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=unsigned\nwindows_signing=unsigned\n") + "version=3.2.0\nchannel=RC\nprerelease=1\nrevision=$Format:%H$\nwindows_signing=unsigned\nwindows_signing=unsigned\n") set (_cache_source "${_fixture_dir}/cache-source") set (_cache_build "${_fixture_dir}/cache-build") @@ -91,33 +108,33 @@ file (WRITE "${_cache_source}/CMakeLists.txt" "cmake_minimum_required(VERSION 3.12)\n" "project(release_cache NONE)\n" "include(\"${SOURCE_DIR}/CMake/Modules/read_release_state.cmake\")\n" - "wsjt_read_release_state(\"${_cache_source}/state.txt\" version channel rc revision)\n" - "wsjt_set_source_default_cache(WSJT_RELEASE_CHANNEL \"\${channel}\" \"channel\")\n" - "wsjt_set_source_default_cache(WSJT_RC_NUMBER \"\${rc}\" \"rc\")\n" - "file(WRITE \"\${CMAKE_BINARY_DIR}/result.txt\" \"\${WSJT_RELEASE_CHANNEL}:\${WSJT_RC_NUMBER}\")\n") + "wsjt_read_release_state(\"${_cache_source}/state.txt\" version channel prerelease revision)\n" + "wsjt_set_release_channel_cache(\"\${channel}\" \"\${prerelease}\")\n" + "file(WRITE \"\${CMAKE_BINARY_DIR}/result.txt\" \"\${WSJT_RELEASE_CHANNEL}:\${WSJT_PRERELEASE_NUMBER}\")\n") + +function (configure_cache build expected description) + execute_process ( + COMMAND "${CMAKE_COMMAND}" -S "${_cache_source}" -B "${build}" ${ARGN} + RESULT_VARIABLE cache_result OUTPUT_QUIET ERROR_QUIET) + if (NOT cache_result EQUAL 0) + message (FATAL_ERROR "${description}: configure failed") + endif () + file (READ "${build}/result.txt" cache_result_value) + assert_equal ("${cache_result_value}" "${expected}" "${description}") +endfunction () + file (WRITE "${_cache_source}/state.txt" - "version=3.2.0\nchannel=DEVEL\nrc=\nrevision=$Format:%H$\n") -execute_process ( - COMMAND "${CMAKE_COMMAND}" -S "${_cache_source}" -B "${_cache_build}" - RESULT_VARIABLE cache_result OUTPUT_QUIET ERROR_QUIET) -if (NOT cache_result EQUAL 0) - message (FATAL_ERROR "Initial release cache configure failed") -endif () + "version=3.3.0\nchannel=DEVEL\nprerelease=\nrevision=$Format:%H$\n") +configure_cache ("${_cache_build}" "DEVEL:" "initial release cache") file (WRITE "${_cache_source}/state.txt" - "version=3.2.0\nchannel=RC\nrc=2\nrevision=$Format:%H$\n") -execute_process ( - COMMAND "${CMAKE_COMMAND}" -S "${_cache_source}" -B "${_cache_build}" - RESULT_VARIABLE cache_result OUTPUT_QUIET ERROR_QUIET) -file (READ "${_cache_build}/result.txt" cache_result_value) -assert_equal ("${cache_result_value}" "RC:2" "tracked metadata refresh") + "version=3.3.0\nchannel=BETA\nprerelease=2\nrevision=$Format:%H$\nwindows_signing=unsigned\n") +configure_cache ("${_cache_build}" "BETA:2" "tracked metadata refresh") set (_override_build "${_fixture_dir}/override-build") -execute_process ( - COMMAND "${CMAKE_COMMAND}" -S "${_cache_source}" -B "${_override_build}" - -D WSJT_RELEASE_CHANNEL=GA -D WSJT_RC_NUMBER= - RESULT_VARIABLE override_result OUTPUT_QUIET ERROR_QUIET) -if (NOT override_result EQUAL 0) - message (FATAL_ERROR "Explicit release cache override configure failed") -endif () -file (READ "${_override_build}/result.txt" override_result_value) -assert_equal ("${override_result_value}" "GA:" "explicit cache override") +configure_cache ("${_override_build}" "GA:" "explicit cache override" + -D WSJT_RELEASE_CHANNEL=GA -D WSJT_PRERELEASE_NUMBER=) +configure_cache ("${_override_build}" "BETA:2" "cleared channel override" + -D WSJT_RELEASE_CHANNEL=) + +configure_cache ("${_fixture_dir}/empty-override-build" "BETA:2" "empty channel override" + -D WSJT_RELEASE_CHANNEL= -D WSJT_PRERELEASE_NUMBER=5) diff --git a/tests/release/test_release_state_dependency.cmake b/tests/release/test_release_state_dependency.cmake new file mode 100644 index 00000000..73f60c38 --- /dev/null +++ b/tests/release/test_release_state_dependency.cmake @@ -0,0 +1,12 @@ +cmake_minimum_required (VERSION 3.12) + +if (NOT SOURCE_DIR) + message (FATAL_ERROR "SOURCE_DIR is required") +endif () + +# CONFIGURE_DEPENDS is the top-level CMAKE_CONFIGURE_DEPENDS, "|"-separated. +string (REPLACE "|" ";" depends "${CONFIGURE_DEPENDS}") +list (FIND depends "${SOURCE_DIR}/release-state.txt" index) +if (index EQUAL -1) + message (FATAL_ERROR "release-state.txt is not a configure dependency, so a commit that changes it leaves an incremental build's channel, version and expiry stale") +endif () diff --git a/tests/release/test_release_tarballs.cmake b/tests/release/test_release_tarballs.cmake new file mode 100644 index 00000000..3a13dd2d --- /dev/null +++ b/tests/release/test_release_tarballs.cmake @@ -0,0 +1,44 @@ +cmake_minimum_required (VERSION 3.12) + +if (NOT SOURCE_DIR OR NOT TEST_BINARY_DIR) + message (FATAL_ERROR "SOURCE_DIR and TEST_BINARY_DIR are required") +endif () + +include ("${SOURCE_DIR}/CMake/Modules/read_release_tarballs.cmake") +file (MAKE_DIRECTORY "${TEST_BINARY_DIR}") + +function (assert_programs file expected description) + wsjt_read_release_tarballs ("${file}" programs) + if (NOT "${programs}" STREQUAL "${expected}") + message (FATAL_ERROR "${description}: expected '${expected}', got '${programs}'") + endif () +endfunction () + +function (expect_invalid name contents) + set (fixture "${TEST_BINARY_DIR}/${name}.txt") + file (WRITE "${fixture}" "${contents}") + execute_process ( + COMMAND "${CMAKE_COMMAND}" + -D RELEASE_TARBALLS_READER=${SOURCE_DIR}/CMake/Modules/read_release_tarballs.cmake + -D RELEASE_TARBALLS_FILE=${fixture} + -P ${SOURCE_DIR}/tests/release/validate_release_tarballs_fixture.cmake + RESULT_VARIABLE result + OUTPUT_QUIET + ERROR_VARIABLE error) + if (result EQUAL 0) + message (FATAL_ERROR "Invalid release tarball list was accepted: ${name}") + endif () +endfunction () + +assert_programs ("${SOURCE_DIR}/CMake/release-tarballs.txt" + "jt9;jt9stream;wsprd;wsprcode;encode77;ft4sim;jt4sim;jt65sim;cwsim;sfoxsim" + "committed list") + +file (WRITE "${TEST_BINARY_DIR}/forms.txt" + "# comment\r\n\r\n \r\n # indented comment\r\nengine\tjt9 jt9stream\r\nwsprd wsprd") +assert_programs ("${TEST_BINARY_DIR}/forms.txt" "jt9;jt9stream;wsprd" + "blank, comment, tab and CRLF lines") + +expect_invalid (no_programs "jt9 jt9\ntesting\n") +expect_invalid (named_twice "jt9 jt9\njt9 jt9stream\n") +expect_invalid (only_comments "# comment\n\n") diff --git a/tests/release/validate_release_state_fixture.cmake b/tests/release/validate_release_state_fixture.cmake index 6218e55b..e01d9158 100644 --- a/tests/release/validate_release_state_fixture.cmake +++ b/tests/release/validate_release_state_fixture.cmake @@ -3,4 +3,4 @@ cmake_minimum_required (VERSION 3.12) include ("${RELEASE_STATE_READER}") wsjt_read_release_state ( "${RELEASE_STATE_FILE}" - version channel rc revision) + version channel prerelease revision) diff --git a/tests/release/validate_release_tarballs_fixture.cmake b/tests/release/validate_release_tarballs_fixture.cmake new file mode 100644 index 00000000..9f0be35f --- /dev/null +++ b/tests/release/validate_release_tarballs_fixture.cmake @@ -0,0 +1,4 @@ +cmake_minimum_required (VERSION 3.12) + +include ("${RELEASE_TARBALLS_READER}") +wsjt_read_release_tarballs ("${RELEASE_TARBALLS_FILE}" programs) diff --git a/tests/unit/audio/CMakeLists.txt b/tests/unit/audio/CMakeLists.txt index a279a713..80550b45 100644 --- a/tests/unit/audio/CMakeLists.txt +++ b/tests/unit/audio/CMakeLists.txt @@ -58,6 +58,16 @@ target_link_libraries (test_audio_input_stream_descriptor add_test (NAME test_audio_input_stream_descriptor COMMAND test_audio_input_stream_descriptor) +add_executable (test_sound_input + test_sound_input.cpp + ${CMAKE_SOURCE_DIR}/Audio/AudioDevice.cpp + ${CMAKE_SOURCE_DIR}/Audio/AudioInputSource.hpp + ${CMAKE_SOURCE_DIR}/Audio/soundin.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp) +target_link_libraries (test_sound_input + wsjt_qtmm wsjt_qt Boost::log_setup Qt5::Test Qt5::Multimedia) +add_test (NAME test_sound_input COMMAND test_sound_input) + add_executable (test_receive_audio_handoff test_receive_audio_handoff.cpp receive_reference_probe.f90 @@ -68,6 +78,12 @@ target_link_libraries (test_receive_audio_handoff wsjt_fort_common Qt5::Core Qt5::Test Qt5::Multimedia) target_include_directories (test_receive_audio_handoff PRIVATE ${CMAKE_BINARY_DIR}) set (receive_handoff_scenarios + block_size_changes_preserve_captured_partial_audio + continuous_end_overflow_keeps_original_session + continuous_detached_batch_excludes_later_publications + continuous_receive_preserves_partial_block_across_clock_wrap + continuous_stop_flushes_only_captured_downsampled_audio + continuous_mailbox_overrun_is_explicit_and_rearms_notification downsamplersRetainIndependentHistory producersRemainIsolatedAcrossSourceSwitch queued_prefix_without_reuse diff --git a/tests/unit/audio/test_audio_input_stream_descriptor.cpp b/tests/unit/audio/test_audio_input_stream_descriptor.cpp index 57698073..26083c9c 100644 --- a/tests/unit/audio/test_audio_input_stream_descriptor.cpp +++ b/tests/unit/audio/test_audio_input_stream_descriptor.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -356,13 +357,18 @@ private: QTRY_VERIFY_WITH_TIMEOUT (emissions.count () > 0, 1000); QCOMPARE (emissions.constFirst ().constFirst ().toLongLong (), anchored.capture_anchor_utc_ms); + QElapsedTimer captureElapsed; + captureElapsed.start (); QTest::qWait (200); + auto const elapsedAfterEmission = captureElapsed.elapsed (); source.suspend (); - auto const beforeResume = QDateTime::currentMSecsSinceEpoch (); source.resume (); auto const resumed = source.streamDescriptor (); - QVERIFY (resumed.capture_anchor_utc_ms >= beforeResume - 20); - QVERIFY (resumed.capture_anchor_utc_ms <= beforeResume + 20); + auto const captureAdvance = resumed.capture_anchor_utc_ms + - anchored.capture_anchor_utc_ms; + constexpr qint64 maximumChunkDurationMs = 3456 * 1000 / 12000; + QVERIFY (captureAdvance > 0); + QVERIFY (captureAdvance <= elapsedAfterEmission + maximumChunkDurationMs); QCOMPARE (changes.size (), 3); source.stop (); diff --git a/tests/unit/audio/test_echosim_wav_trailer.cpp b/tests/unit/audio/test_echosim_wav_trailer.cpp index 3348b8d5..cd03de42 100644 --- a/tests/unit/audio/test_echosim_wav_trailer.cpp +++ b/tests/unit/audio/test_echosim_wav_trailer.cpp @@ -10,6 +10,30 @@ namespace { + bool wait_for_echosim (QProcess& process) + { + auto const finished = process.waitForFinished (30000); + if (!finished || process.exitStatus () != QProcess::NormalExit || process.exitCode () != 0) + { + auto const reason = !finished ? process.errorString () + : process.exitStatus () != QProcess::NormalExit ? QString {"abnormal termination"} + : QString {"nonzero exit"}; + if (process.state () != QProcess::NotRunning) + { + process.kill (); + process.waitForFinished (5000); + } + qWarning ().noquote () << QString { + "echosim %1 failed: %2 (exit status %3, exit code %4)\nstdout:\n%5\nstderr:\n%6"} + .arg (process.arguments ().join (' '), reason) + .arg (process.exitStatus () == QProcess::NormalExit ? "normal" : "crashed") + .arg (process.exitCode ()) + .arg (QString::fromLocal8Bit (process.readAllStandardOutput ()), + QString::fromLocal8Bit (process.readAllStandardError ())); + } + return finished; + } + QAudioFormat default_format () { QAudioFormat format; @@ -37,7 +61,8 @@ private: QProcess process; process.setWorkingDirectory (dir.path ()); process.start (ECHOSIM_EXECUTABLE, {"1500", "0.0", "0.0", "1", "100"}); - QVERIFY (process.waitForFinished (30000)); + QVERIFY (wait_for_echosim (process)); + QCOMPARE (process.exitStatus (), QProcess::NormalExit); QCOMPARE (process.exitCode (), 0); QDir out {dir.path ()}; @@ -66,7 +91,8 @@ private: QProcess process; process.setWorkingDirectory (dir.path ()); process.start (ECHOSIM_EXECUTABLE, {"1500", "0.0", "4.0", "1", "-22"}); - QVERIFY (process.waitForFinished (30000)); + QVERIFY (wait_for_echosim (process)); + QCOMPARE (process.exitStatus (), QProcess::NormalExit); QCOMPARE (process.exitCode (), 0); QDir out {dir.path ()}; diff --git a/tests/unit/audio/test_receive_audio_handoff.cpp b/tests/unit/audio/test_receive_audio_handoff.cpp index 07cc9865..da2dfde6 100644 --- a/tests/unit/audio/test_receive_audio_handoff.cpp +++ b/tests/unit/audio/test_receive_audio_handoff.cpp @@ -283,6 +283,255 @@ class TestReceiveAudioHandoff : public QObject } private Q_SLOTS: + void block_size_changes_preserve_captured_partial_audio () + { + Detector detector {12000, 180.0, 1}; + detector.setBlockSize (block); + QVERIFY (detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono)); + detector.setReceivePolicy (ReceivePolicy::ContinuousJtty); + JttyReceiveMailboxPtr mailbox; + connect (&detector, &Detector::continuousAudioAvailable, this, + [&] (JttyReceiveMailboxPtr value) { mailbox = value; }); + QVERIFY (writeSamples (detector, 100, patternA)); + detector.setBlockSize (0); + detector.setBlockSize (block + 1); + detector.setBlockSize (block); + JttyReceiveEvent event; + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + auto const firstSession = event.session; + QVERIFY (!mailbox->take (event)); + + detector.setBlockSize (256); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QCOMPARE (event.session, firstSession); + QCOMPARE (event.samples, std::vector (100, patternA)); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::End); + QCOMPARE (event.firstSample, qint64 {100}); + QVERIFY (!mailbox->take (event)); + QVERIFY (writeSamples (detector, 256, patternB)); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QVERIFY (event.session != firstSession); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QCOMPARE (event.firstSample, qint64 {0}); + QCOMPARE (event.samples, std::vector (256, patternB)); + QVERIFY (!mailbox->take (event)); + } + + void continuous_receive_preserves_partial_block_across_clock_wrap () + { + Detector detector {12000, 1.0, 1}; + detector.setBlockSize (block); + QVERIFY (detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono)); + detector.setStreamDescriptor (descriptor (true)); + detector.setReceiveContext (91); + detector.setReceivePolicy (ReceivePolicy::ContinuousJtty); + JttyReceiveMailboxPtr mailbox; + int notifications = 0; + connect (&detector, &Detector::continuousAudioAvailable, this, + [&] (JttyReceiveMailboxPtr value) { mailbox = value; ++notifications; }); + + QVERIFY (writeSamples (detector, committed + 100, patternA)); + QVERIFY (writeSamples (detector, block, patternB)); + detector.finishInput (); + QVERIFY (mailbox); + QCOMPARE (notifications, 1); + JttyReceiveEvent event; + std::vector observed; + quint64 session = 0; + bool ended = false; + while (mailbox->take (event)) + { + if (event.kind == JttyReceiveEvent::Kind::Begin) + { + QCOMPARE (session, quint64 {0}); + session = event.session; + } + QCOMPARE (event.session, session); + QCOMPARE (event.context, quint64 {91}); + if (event.kind == JttyReceiveEvent::Kind::Samples) + { + QCOMPARE (event.firstSample, qint64 (observed.size ())); + observed.insert (observed.end (), event.samples.begin (), event.samples.end ()); + } + if (event.kind == JttyReceiveEvent::Kind::End) + { + QCOMPARE (event.firstSample, qint64 (observed.size ())); + ended = true; + } + } + QVERIFY (ended); + QCOMPARE (observed.size (), std::size_t (committed + 100 + block)); + QVERIFY (std::all_of (observed.begin (), observed.begin () + committed + 100, + [] (short sample) { return sample == patternA; })); + QVERIFY (std::all_of (observed.begin () + committed + 100, observed.end (), + [] (short sample) { return sample == patternB; })); + detector.setReceiveContext (92); + QVERIFY (writeSamples (detector, block, patternB)); + detector.finishInput (); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QCOMPARE (event.context, quint64 {92}); + QVERIFY (event.session != session); + } + + void continuous_stop_flushes_only_captured_downsampled_audio () + { + Detector detector {48000, 180.0, 4}; + detector.setBlockSize (block); + QVERIFY (detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono)); + detector.setReceivePolicy (ReceivePolicy::ContinuousJtty); + JttyReceiveMailboxPtr mailbox; + connect (&detector, &Detector::continuousAudioAvailable, this, + [&] (JttyReceiveMailboxPtr value) { mailbox = value; }); + std::vector input (4 * block + 103, patternA); + QCOMPARE (detector.write (reinterpret_cast (input.data ()), + qint64 (input.size () * sizeof (short))), + qint64 (input.size () * sizeof (short))); + detector.setInputStopReason (JttyReceiveReason::Transmission); + detector.finishInput (); + std::vector actual; + JttyReceiveEvent event; + bool ended = false; + while (mailbox->take (event)) + { + if (event.kind == JttyReceiveEvent::Kind::Samples) + actual.insert (actual.end (), event.samples.begin (), event.samples.end ()); + if (event.kind == JttyReceiveEvent::Kind::End) + { + QCOMPARE (event.reason, JttyReceiveReason::Transmission); + ended = true; + } + } + QVERIFY (ended); + std::vector expected (input.size () / 4); + std::array filter {}; + qint32 inputFrames = int (expected.size () * 4), outputFrames = 0; + fil4_state_ (input.data (), &inputFrames, expected.data (), &outputFrames, filter.data ()); + QVERIFY (actual == expected); + detector.finishInput (); + QVERIFY (!mailbox->take (event)); + QVERIFY (writeSamples (detector, 103, patternA)); + detector.inputInterrupted (); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + auto const interruptedSession = event.session; + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QCOMPARE (event.samples.size (), std::size_t {25}); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::End); + QCOMPARE (event.reason, JttyReceiveReason::InputError); + QVERIFY (!mailbox->take (event)); + QVERIFY (writeSamples (detector, 4 * block, patternB)); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QVERIFY (event.session != interruptedSession); + QCOMPARE (event.firstSample, qint64 {0}); + detector.setReceivePolicy (ReceivePolicy::Timed); + quint64 drainedRequest = 0; + JttyReceiveMailboxPtr drainedMailbox; + connect (&detector, &Detector::continuousReceiveDrained, this, + [&] (quint64 request, JttyReceiveMailboxPtr value) { + drainedRequest = request; + drainedMailbox = std::move (value); + }); + detector.requestContinuousReceiveDrain (55); + QCOMPARE (drainedRequest, quint64 {55}); + QVERIFY (drainedMailbox == mailbox); + } + + void continuous_mailbox_overrun_is_explicit_and_rearms_notification () + { + JttyReceivePublisher publisher; + QVERIFY (publisher.begin (100000)); + std::vector samples (3456, patternA); + for (int i = 0; i < 630; ++i) + QVERIFY (!publisher.append (samples.data (), int (samples.size ()))); + auto mailbox = publisher.mailbox (); + JttyReceiveEvent event; + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Gap); + QCOMPARE (event.reason, JttyReceiveReason::Overrun); + auto const oldSession = event.session; + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QVERIFY (event.session > oldSession); + qint64 total = 0; + while (mailbox->take (event)) + { + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QCOMPARE (event.firstSample, total); + total += qint64 (event.samples.size ()); + } + QVERIFY (total <= JttyReceiveMailbox::capacitySamples); + QVERIFY (publisher.append (samples.data (), int (samples.size ()))); + } + + void continuous_detached_batch_excludes_later_publications () + { + JttyReceivePublisher publisher; + publisher.setContext (42); + QVERIFY (publisher.begin (100000)); + short const first[] {patternA, patternB}; + QVERIFY (!publisher.append (first, 2)); + auto pending = publisher.mailbox ()->detachPending (); + short const later = patternB; + QVERIFY (publisher.append (&later, 1)); + publisher.end (JttyReceiveReason::MonitorStopped); + JttyReceiveEvent event; + QVERIFY (pending->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QCOMPARE (event.context, quint64 {42}); + auto const session = event.session; + QVERIFY (pending->take (event)); + QCOMPARE (event.session, session); + QCOMPARE (event.firstSample, qint64 {0}); + QVERIFY (event.samples == std::vector (first, first + 2)); + QVERIFY (!pending->take (event)); + QVERIFY (publisher.mailbox ()->take (event)); + QCOMPARE (event.session, session); + QCOMPARE (event.firstSample, qint64 {2}); + QVERIFY (event.samples == std::vector {later}); + QVERIFY (publisher.mailbox ()->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::End); + QCOMPARE (event.endSample (), qint64 {3}); + QVERIFY (!publisher.mailbox ()->take (event)); + } + + void continuous_end_overflow_keeps_original_session () + { + JttyReceivePublisher publisher; + QVERIFY (publisher.begin (100000)); + JttyReceiveEvent event; + auto mailbox = publisher.mailbox (); + QVERIFY (mailbox->take (event)); + auto const session = event.session; + short const sample = patternA; + for (int i = 0; i < 1024; ++i) QVERIFY (!publisher.append (&sample, 1)); + QVERIFY (!publisher.end (JttyReceiveReason::MonitorStopped)); + QVERIFY (!publisher.active ()); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Gap); + QCOMPARE (event.session, session); + QCOMPARE (event.firstSample, qint64 {1024}); + QCOMPARE (event.reason, JttyReceiveReason::Overrun); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::End); + QCOMPARE (event.session, session); + QCOMPARE (event.firstSample, qint64 {1024}); + QCOMPARE (event.reason, JttyReceiveReason::MonitorStopped); + QVERIFY (!mailbox->take (event)); + QVERIFY (publisher.begin (101000)); + QVERIFY (mailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QVERIFY (event.session != session); + } + void downsamplersRetainIndependentHistory () { std::array firstState {}, secondState {}, referenceState {}; diff --git a/tests/unit/audio/test_sound_input.cpp b/tests/unit/audio/test_sound_input.cpp new file mode 100644 index 00000000..8002c03a --- /dev/null +++ b/tests/unit/audio/test_sound_input.cpp @@ -0,0 +1,85 @@ +#include + +#include "Audio/soundin.h" + +namespace +{ + class TestAudioSink final : public AudioDevice + { + public: + void inputInterrupted () override {++interruptions;} + int interruptions {0}; + + protected: + qint64 readData (char *, qint64) override {return -1;} + qint64 writeData (char const *, qint64 size) override {return size;} + }; +} + +class TestSoundInput : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void sticky_underrun_does_not_interrupt_recovered_input () + { + TestAudioSink sink; + SoundInput input; + input.m_sink = &sink; + input.updateStreamInterruption (QAudio::ActiveState, QAudio::NoError); + input.updateStreamInterruption (QAudio::IdleState, QAudio::UnderrunError); + input.updateStreamInterruption (QAudio::IdleState, QAudio::UnderrunError); + QCOMPARE (sink.interruptions, 1); + + input.updateStreamInterruption (QAudio::ActiveState, QAudio::UnderrunError); + for (int notification = 0; notification < 5; ++notification) + input.updateStreamInterruption (QAudio::ActiveState, QAudio::UnderrunError); + QCOMPARE (sink.interruptions, 1); + + input.updateStreamInterruption (QAudio::IdleState, QAudio::UnderrunError); + QCOMPARE (sink.interruptions, 2); + input.updateStreamInterruption (QAudio::ActiveState, QAudio::UnderrunError); + input.updateStreamInterruption (QAudio::ActiveState, QAudio::NoError); + input.updateStreamInterruption (QAudio::ActiveState, QAudio::UnderrunError); + QCOMPARE (sink.interruptions, 3); + } + + void interruption_states_rearm_after_recovery () + { + TestAudioSink sink; + SoundInput input; + input.m_sink = &sink; + QList states {QAudio::IdleState, QAudio::SuspendedState}; +#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0) + states.append (QAudio::InterruptedState); +#endif + int expected = 0; + for (auto state : states) + { + input.updateStreamInterruption (QAudio::ActiveState, QAudio::NoError); + input.updateStreamInterruption (state, QAudio::NoError); + input.updateStreamInterruption (state, QAudio::NoError); + QCOMPARE (sink.interruptions, ++expected); + } + } + + void hard_errors_and_stream_replacement_remain_observable () + { + TestAudioSink sink; + SoundInput input; + input.m_sink = &sink; + int expected = 0; + for (auto error : {QAudio::OpenError, QAudio::IOError, QAudio::FatalError}) + { + input.updateStreamInterruption (QAudio::StoppedState, error); + input.updateStreamInterruption (QAudio::StoppedState, error); + QCOMPARE (sink.interruptions, ++expected); + input.stop (); + } + input.updateStreamInterruption (QAudio::StoppedState, QAudio::FatalError); + QCOMPARE (sink.interruptions, ++expected); + } +}; + +QTEST_GUILESS_MAIN (TestSoundInput) +#include "test_sound_input.moc" diff --git a/tests/unit/audio/test_tx_audio_queue.cpp b/tests/unit/audio/test_tx_audio_queue.cpp index e73eb79e..0d3c60f6 100644 --- a/tests/unit/audio/test_tx_audio_queue.cpp +++ b/tests/unit/audio/test_tx_audio_queue.cpp @@ -42,6 +42,7 @@ private: QVERIFY (qMetaTypeId () != QMetaType::UnknownType); QVERIFY (qMetaTypeId () != QMetaType::UnknownType); QVERIFY (qMetaTypeId () != QMetaType::UnknownType); + QVERIFY (qMetaTypeId () != QMetaType::UnknownType); QVERIFY (qMetaTypeId () != QMetaType::UnknownType); QVERIFY (epoch (1) == epoch (1)); QVERIFY (epoch (1) != epoch (2)); @@ -57,6 +58,7 @@ private: QVector const first {1, 2, 3}; auto result = queue.enqueue (first, current); QVERIFY (result.accepted); + QCOMPARE (result.failure, TxAudioQueueEnqueueFailure::None); QCOMPARE (result.progress.epoch, current); QCOMPARE (result.progress.queued_samples, qint64 (3)); QCOMPARE (result.progress.served_samples, qint64 (0)); @@ -95,6 +97,7 @@ private: qint16 const stale_sample {9}; auto const rejected = queue.enqueue (&stale_sample, 1, epoch (22)); QVERIFY (!rejected.accepted); + QCOMPARE (rejected.failure, TxAudioQueueEnqueueFailure::StaleEpoch); QCOMPARE (rejected.progress.epoch, current); QCOMPARE (rejected.progress.queued_samples, qint64 (2)); QCOMPARE (rejected.progress.served_samples, qint64 (0)); @@ -102,8 +105,11 @@ private: auto const empty = queue.enqueue (nullptr, 0, current); QVERIFY (empty.accepted); + QCOMPARE (empty.failure, TxAudioQueueEnqueueFailure::None); QCOMPARE (empty.progress.total_samples, qint64 (2)); - QVERIFY (!queue.enqueue (nullptr, 0, epoch (99)).accepted); + auto const stale_empty = queue.enqueue (nullptr, 0, epoch (99)); + QVERIFY (!stale_empty.accepted); + QCOMPARE (stale_empty.failure, TxAudioQueueEnqueueFailure::StaleEpoch); } Q_SLOT void pending_reset_excludes_aborted_samples () @@ -147,6 +153,7 @@ private: auto const rejected = queue.enqueue (QVector {12, 13}, current); QVERIFY (!rejected.accepted); + QCOMPARE (rejected.failure, TxAudioQueueEnqueueFailure::Capacity); QCOMPARE (rejected.progress.queued_samples, qint64 (2)); QCOMPARE (rejected.progress.total_samples, qint64 (2)); diff --git a/tests/unit/audio/test_wav_input_loading.cpp b/tests/unit/audio/test_wav_input_loading.cpp index d66e3f23..6a0190cd 100644 --- a/tests/unit/audio/test_wav_input_loading.cpp +++ b/tests/unit/audio/test_wav_input_loading.cpp @@ -4,10 +4,13 @@ #include #include +#include #include +#include #include #include "Audio/WavInputLoader.hpp" +#include "Audio/BWFFile.hpp" namespace { @@ -105,11 +108,77 @@ private: QCOMPARE (result.samples[0], short {1234}); QCOMPARE (result.samples[1], short {-2345}); QCOMPARE (result.samples[2], short {32767}); + QVERIFY (!result.firstSampleUtc.isValid ()); + QCOMPARE (result.timeReferenceRate, 0); QVERIFY (std::all_of (result.samples.cbegin () + result.frames, result.samples.cend (), [] (short sample) {return !sample;})); QFile::remove (name); } + Q_SLOT void preserves_bwf_capture_time_data () + { + QTest::addColumn ("sampleRate"); + QTest::newRow ("native") << 12000; + QTest::newRow ("resampled") << 11025; + } + + Q_SLOT void preserves_bwf_capture_time () + { + QFETCH (int, sampleRate); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const name = directory.filePath (QStringLiteral ("260101_000000.wav")); + QAudioFormat format; + format.setCodec (QStringLiteral ("audio/pcm")); + format.setSampleRate (sampleRate); + format.setChannelCount (1); + format.setSampleSize (16); + format.setSampleType (QAudioFormat::SignedInt); + BWFFile file {format, name}; + QVERIFY (file.open (QIODevice::WriteOnly)); + QDateTime const date {QDate {2026, 9, 12}, QTime {0, 0}, Qt::UTC}; + auto const reference = quint64 (sampleRate / 2 + 7); + file.bext_origination_date_time (date); + file.bext_time_reference (reference); + auto const samples = signed_samples (sampleRate); + QCOMPARE (file.write (samples), qint64 (samples.size ())); + QVERIFY (file.finalize ()); + + auto const result = Radio::load_wav_input (name, 13000); + QVERIFY (result.valid); + QCOMPARE (result.frames, 12000); + QCOMPARE (result.firstSampleUtc, date.addMSecs (500)); + QCOMPARE (result.samplesSinceMidnight, reference); + QCOMPARE (result.timeReferenceRate, sampleRate); + QCOMPARE (result.fileDateTime, QStringLiteral ("260101_000000")); + QCOMPARE (result.yymmdd, 260101); + } + + Q_SLOT void invalid_bwf_reference_does_not_replace_filename_time () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const name = directory.filePath (QStringLiteral ("260911_235958.wav")); + QAudioFormat format; + format.setCodec (QStringLiteral ("audio/pcm")); + format.setSampleRate (12000); + format.setChannelCount (1); + format.setSampleSize (16); + format.setSampleType (QAudioFormat::SignedInt); + BWFFile file {format, name}; + QVERIFY (file.open (QIODevice::WriteOnly)); + file.bext_origination_date_time (QDateTime {QDate {2026, 9, 11}, QTime {23, 59, 58}, Qt::UTC}); + file.bext_time_reference (quint64 {86400} * 12000); + QCOMPARE (file.write (signed_samples (100)), qint64 {200}); + QVERIFY (file.finalize ()); + + auto const result = Radio::load_wav_input (name, 1000); + QVERIFY (result.valid); + QVERIFY (!result.firstSampleUtc.isValid ()); + QCOMPARE (result.timeReferenceRate, 0); + QCOMPARE (result.nutc, 235958); + } + Q_SLOT void truncates_oversized_input_to_capacity () { int constexpr sample_limit = 13000; diff --git a/tests/unit/common/CMakeLists.txt b/tests/unit/common/CMakeLists.txt index 770aa0ec..9c6f0a2d 100644 --- a/tests/unit/common/CMakeLists.txt +++ b/tests/unit/common/CMakeLists.txt @@ -1,3 +1,14 @@ +add_executable (test_radio_callsign test_radio_callsign.cpp) +target_link_libraries (test_radio_callsign wsjt_qt Qt5::Test) +add_test (NAME test_radio_callsign COMMAND test_radio_callsign) + +add_executable (test_frequency_list + test_frequency_list.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp +) +target_link_libraries (test_frequency_list wsjt_qt Boost::log_setup Qt5::Test) +add_test (NAME test_frequency_list COMMAND test_frequency_list) + add_executable (test_qt_helpers test_qt_helpers.cpp ${CMAKE_SOURCE_DIR}/qt_helpers.cpp @@ -6,6 +17,19 @@ target_include_directories (test_qt_helpers PRIVATE ${CMAKE_BINARY_DIR}) target_link_libraries (test_qt_helpers Qt5::Test Qt5::Network Qt5::Widgets) add_test (NAME test_qt_helpers COMMAND test_qt_helpers) +add_executable (test_configuration_radio test_configuration_radio.cpp) +add_dependencies (test_configuration_radio wsjt_qt_autogen) +target_include_directories (test_configuration_radio PRIVATE + ${CMAKE_BINARY_DIR} + ${CMAKE_BINARY_DIR}/wsjt_qt_autogen/include + ${CMAKE_BINARY_DIR}/wsjt_qt_autogen/include_$) +target_link_libraries (test_configuration_radio wsjt_qt wsjt_cxx wsjt_fort_common + Boost::log_setup Qt5::Test) +add_test (NAME test_configuration_radio COMMAND test_configuration_radio) +set_tests_properties (test_configuration_radio PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + TIMEOUT 60) + add_executable (test_callsign_validator test_callsign_validator.cpp ${CMAKE_SOURCE_DIR}/validators/CallsignValidator.cpp @@ -49,6 +73,12 @@ add_executable (test_wf_palette target_link_libraries (test_wf_palette wsjt_qt Qt5::Test) add_test (NAME test_wf_palette COMMAND test_wf_palette) +add_executable (test_decode_highlighting_model + test_decode_highlighting_model.cpp +) +target_link_libraries (test_decode_highlighting_model wsjt_qt Qt5::Test) +add_test (NAME test_decode_highlighting_model COMMAND test_decode_highlighting_model) + add_executable (test_waterfall_scale test_waterfall_scale.cpp ) @@ -97,6 +127,17 @@ target_link_libraries (test_round_robin_selection Qt5::Test Qt5::Widgets) add_test (NAME test_round_robin_selection COMMAND test_round_robin_selection) set_tests_properties (test_round_robin_selection PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") +add_executable (test_log_window_deletion + test_log_window_deletion.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp +) +target_link_libraries (test_log_window_deletion wsjt_qt wsjt_cxx wsjt_fort_common + Boost::log_setup Qt5::Test Qt5::Widgets Qt5::Sql) +add_test (NAME test_log_window_deletion COMMAND test_log_window_deletion) +set_tests_properties (test_log_window_deletion PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + TIMEOUT 60) + add_executable (test_rig_frequency_change_policy test_rig_frequency_change_policy.cpp ) @@ -183,6 +224,14 @@ add_executable (test_frequency_editors target_link_libraries (test_frequency_editors wsjt_qt Boost::log_setup Qt5::Test Qt5::Widgets) add_test (NAME test_frequency_editors COMMAND test_frequency_editors) +add_executable (test_frequency_suggestions + test_frequency_suggestions.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp +) +target_link_libraries (test_frequency_suggestions wsjt_qt Boost::log_setup Qt5::Test Qt5::Widgets) +add_test (NAME test_frequency_suggestions COMMAND test_frequency_suggestions) +set_tests_properties (test_frequency_suggestions PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + add_executable (test_decoded_message_reaction test_decoded_message_reaction.cpp ) diff --git a/tests/unit/common/test_active_stations.cpp b/tests/unit/common/test_active_stations.cpp index d53f58e0..10b262d2 100644 --- a/tests/unit/common/test_active_stations.cpp +++ b/tests/unit/common/test_active_stations.cpp @@ -6,6 +6,7 @@ #include #include "widgets/activeStations.h" +#include "lib/qra/q65/q65_limits.h" class TestActiveStations : public QObject { @@ -14,6 +15,7 @@ class TestActiveStations : public QObject private slots: void transitions(); void clickRouting(); + void fullPileupSelection(); }; void TestActiveStations::transitions() @@ -82,5 +84,34 @@ void TestActiveStations::clickRouting() } } +void TestActiveStations::fullPileupSelection() +{ + QTemporaryDir directory; + QVERIFY(directory.isValid()); + QSettings settings(directory.filePath("settings.ini"), QSettings::IniFormat); + ActiveStations widget(&settings, QFont{}); + QSignalSpy station(&widget, SIGNAL(callSandP(int))); + QVERIFY(station.isValid()); + auto editor = widget.findChild("RecentStationsPlainTextEdit"); + QVERIFY(editor); + QString rows; + for (int row = 1; row <= Q65_CALLER_CAPACITY; ++row) { + rows += QString("%1. 1500 K1ABC FN42 10 0.0\n").arg(row, 2); + } + widget.setClickOK(false); + widget.displayRecentStations(ActiveStations::DisplayMode::Q65Pileup, rows); + auto cursor = editor->textCursor(); + cursor.movePosition(QTextCursor::Start); + for (int row = 1; row < Q65_CALLER_CAPACITY; ++row) { + QVERIFY(cursor.movePosition(QTextCursor::NextBlock)); + } + editor->setTextCursor(cursor); + station.clear(); + widget.setClickOK(true); + QVERIFY(QMetaObject::invokeMethod(&widget, "on_textEdit_clicked", Qt::DirectConnection)); + QCOMPARE(station.count(), 1); + QCOMPARE(station.at(0).at(0).toInt(), Q65_CALLER_CAPACITY); +} + QTEST_MAIN(TestActiveStations) #include "test_active_stations.moc" diff --git a/tests/unit/common/test_configuration_dialog_layout.cpp b/tests/unit/common/test_configuration_dialog_layout.cpp index 019147af..b66d5724 100644 --- a/tests/unit/common/test_configuration_dialog_layout.cpp +++ b/tests/unit/common/test_configuration_dialog_layout.cpp @@ -241,9 +241,12 @@ void TestConfigurationDialogLayout::compactControlsKeepNaturalGeometry () { QFETCH (int, font_delta); + QWidget host; DialogFixture fixture {font_delta}; auto& dialog = fixture.dialog; auto& ui = fixture.ui; + dialog.setParent (&host, Qt::Widget); + host.show (); showDialog (dialog, {640, 480}); ui.configuration_tabs->setCurrentWidget (ui.general_tab); @@ -268,6 +271,30 @@ void TestConfigurationDialogLayout::compactControlsKeepNaturalGeometry () QVERIFY (isFullyInside (control, group)); } } + + ui.configuration_tabs->setCurrentWidget (ui.colors_tab); + for (int width : {420, 640, 1100}) + { + dialog.resize (width, 480); + settleLayouts (); + QCOMPARE (dialog.width (), width); + auto * up = ui.move_highlighting_up_push_button; + auto * down = ui.move_highlighting_down_push_button; + for (auto * button : {up, down}) + { + QVERIFY (button->width () >= button->minimumSizeHint ().width ()); + QVERIFY2 (button->width () <= button->sizeHint ().width () + 2, + qPrintable (QString {"%1 dialogWidth=%2 actual=%3 hint=%4"} + .arg (button->objectName ()).arg (width) + .arg (sizeText (button->size ()), sizeText (button->sizeHint ())))); + QVERIFY (isFullyInside (button, ui.groupBox_12)); + } + QVERIFY (qAbs (up->geometry ().center ().y () + - down->geometry ().center ().y ()) <= 2); + QVERIFY (ui.highlighting_actions_tool_button->geometry ().right () + < up->geometry ().left ()); + QVERIFY (up->geometry ().right () < down->geometry ().left ()); + } } void TestConfigurationDialogLayout::constrainedDialogKeepsNavigationAndActionsReachable_data () @@ -473,6 +500,20 @@ void TestConfigurationDialogLayout::keyboardFocusRevealsOffscreenControls () QTRY_VERIFY (isFullyVisible (left_side_control, filters_scroll_area)); QCOMPARE (geometryIn (ui.configuration_dialog_button_box, &dialog), filters_button_box_geometry); + + ui.configuration_tabs->setCurrentWidget (ui.colors_tab); + settleLayouts (); + auto * colors_scroll_area = SettingsDialogLayout::pageScrollArea (ui.colors_tab); + ui.move_highlighting_up_push_button->setFocus (Qt::TabFocusReason); + QTRY_COMPARE (QApplication::focusWidget (), ui.move_highlighting_up_push_button); + QTRY_VERIFY (isFullyVisible (ui.move_highlighting_up_push_button, colors_scroll_area)); + QCOMPARE (ui.move_highlighting_up_push_button->nextInFocusChain (), + ui.move_highlighting_down_push_button); + QCOMPARE (ui.move_highlighting_down_push_button->previousInFocusChain (), + ui.move_highlighting_up_push_button); + ui.move_highlighting_down_push_button->setFocus (Qt::TabFocusReason); + QTRY_COMPARE (QApplication::focusWidget (), ui.move_highlighting_down_push_button); + QTRY_VERIFY (isFullyVisible (ui.move_highlighting_down_push_button, colors_scroll_area)); } void TestConfigurationDialogLayout::wheelEventsScrollThePage () diff --git a/tests/unit/common/test_configuration_radio.cpp b/tests/unit/common/test_configuration_radio.cpp new file mode 100644 index 00000000..9df6b2bd --- /dev/null +++ b/tests/unit/common/test_configuration_radio.cpp @@ -0,0 +1,237 @@ +#include "wsjtx_config.h" +#include +#include + +// Exercise the private dialog and its auto-connected slots without exposing a test API. +#include "Configuration.cpp" +#include "widgets/itoneAndicw.h" + +int volatile itone[MAX_NUM_SYMBOLS] {}; +float gran () { return 0; } + +class TestConfigurationRadio final : public QObject +{ + Q_OBJECT + + using RadioValidationError = Configuration::impl::RadioValidationError; + + QTemporaryDir directory_; + QNetworkAccessManager network_; + std::unique_ptr settings_; + std::unique_ptr configuration_; + QString serial_rig_; + QString network_rig_; + + Configuration::impl& dialog () { return *configuration_->m_; } + Ui::configuration_dialog& ui () { return *dialog ().ui_; } + +private slots: + void initTestCase () + { + register_types (); + QStandardPaths::setTestModeEnabled (true); + QCoreApplication::setApplicationName ("test_configuration_radio"); + QVERIFY (directory_.isValid ()); + } + + void init () + { + settings_.reset (new QSettings {directory_.filePath ("settings.ini"), QSettings::IniFormat}); + settings_->clear (); + configuration_.reset (new Configuration {&network_, QDir {directory_.path ()}, settings_.get (), nullptr}); + auto& d = dialog (); + auto& rigs = const_cast (d.transceiver_factory_.supported_transceivers ()); + using Caps = TransceiverFactory::Capabilities; + for (auto it = rigs.cbegin (); it != rigs.cend (); ++it) + { + if (it->port_type_ == Caps::serial) serial_rig_ = it.key (); + if (it->port_type_ == Caps::network) network_rig_ = it.key (); + } + QVERIFY (!serial_rig_.isEmpty ()); + QVERIFY (!network_rig_.isEmpty ()); + // OmniRig's Windows COM transport is unavailable here; use its registered capabilities. + if (!rigs.contains ("OmniRig Rig 1")) + rigs.insert ("OmniRig Rig 1", Caps {99904, Caps::none, true, false, true, true}); + d.enumerate_rigs (); + d.rig_params_.rig_name = serial_rig_; + d.rig_params_.serial_port = "/dev/test-cat"; + d.rig_params_.network_port = "localhost:4532"; + d.rig_params_.ptt_port = "/dev/test-cat"; + d.rig_params_.ptt_type = TransceiverFactory::PTT_method_DTR; + d.rig_params_.handshake = TransceiverFactory::handshake_none; + d.initialize_models (); + // Audio availability is independent of these radio validation cases. + if (ui ().sound_input_combo_box->currentIndex () < 0) + ui ().sound_input_combo_box->addItem ("Test input"); + if (ui ().sound_input_channel_combo_box->currentIndex () < 0) + ui ().sound_input_channel_combo_box->addItem ("Mono"); + if (ui ().sound_output_combo_box->currentIndex () < 0) + ui ().sound_output_combo_box->addItem ("Test output"); + if (d.dns_lookup_id_ > -1) QHostInfo::abortHostLookup (d.dns_lookup_id_); + d.dns_lookup_id_ = -1; + } + + void cleanup () + { + configuration_.reset (); + settings_.reset (); + } + + void proxyCatBecomesExplicitSerialSelection_data () + { + QTest::addColumn ("rts"); + QTest::newRow ("DTR") << false; + QTest::newRow ("RTS") << true; + } + + void proxyCatBecomesExplicitSerialSelection () + { + QFETCH (bool, rts); + auto& u = ui (); + u.rig_combo_box->setCurrentText ("OmniRig Rig 1"); + (rts ? u.PTT_RTS_radio_button : u.PTT_DTR_radio_button)->setChecked (true); + u.PTT_port_combo_box->setCurrentIndex (u.PTT_port_combo_box->findText ("CAT")); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {"CAT"}); + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::none); + QSignalSpy changes {u.PTT_port_combo_box, &QComboBox::currentTextChanged}; + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + QCOMPARE (u.PTT_port_combo_box->currentIndex (), -1); + QCOMPARE (changes.count (), 0); + QCOMPARE (u.PTT_port_combo_box->findText ("USB"), -1); + QVERIFY (u.CAT_port_combo_box->findText ("USB") >= 0); + for (int i = 0; i != 3; ++i) dialog ().set_rig_invariants (); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + u.rig_combo_box->setCurrentText ("OmniRig Rig 1"); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::invalid_ptt_port); + u.PTT_port_combo_box->setEditText ("/dev/manually-entered-ptt"); + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::none); + QCOMPARE (dialog ().gather_rig_data ().ptt_port, QString {"/dev/manually-entered-ptt"}); + } + + void networkToSerialUsesFinalPorts_data () + { + QTest::addColumn ("same_port"); + QTest::addColumn ("hardware"); + QTest::addColumn ("rts"); + for (bool same : {false, true}) + for (bool hw : {false, true}) + for (bool rts : {false, true}) + QTest::newRow (qPrintable (QString {"same=%1,hardware=%2,rts=%3"}.arg (same).arg (hw).arg (rts))) + << same << hw << rts; + } + + void networkToSerialUsesFinalPorts () + { + QFETCH (bool, same_port); + QFETCH (bool, hardware); + QFETCH (bool, rts); + auto& u = ui (); + (hardware ? u.CAT_handshake_hardware_radio_button : u.CAT_handshake_none_radio_button)->setChecked (true); + (rts ? u.PTT_RTS_radio_button : u.PTT_DTR_radio_button)->setChecked (true); + u.PTT_port_combo_box->setEditText (same_port ? "/dev/test-cat" : "/dev/test-ptt"); + for (int i = 0; i != 3; ++i) + { + u.rig_combo_box->setCurrentText (network_rig_); + QVERIFY (u.PTT_RTS_radio_button->isEnabled ()); + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.CAT_port_combo_box->currentText (), QString {"/dev/test-cat"}); + QCOMPARE (u.PTT_RTS_radio_button->isEnabled (), !(same_port && hardware)); + QCOMPARE (u.force_DTR_combo_box->isEnabled (), !(same_port && !rts)); + QCOMPARE (u.force_RTS_combo_box->isEnabled (), !hardware && !(same_port && rts)); + dialog ().set_rig_invariants (); + QCOMPARE (u.PTT_RTS_radio_button->isEnabled (), !(same_port && hardware)); + QCOMPARE (u.force_DTR_combo_box->isEnabled (), !(same_port && !rts)); + QCOMPARE (u.force_RTS_combo_box->isEnabled (), !hardware && !(same_port && rts)); + } + } + + void editablePortsUpdateWithoutActivation () + { + auto& u = ui (); + QSignalSpy activated {u.PTT_port_combo_box, QOverload::of (&QComboBox::activated)}; + QVERIFY (!u.force_DTR_combo_box->isEnabled ()); + u.PTT_port_combo_box->lineEdit ()->selectAll (); + QTest::keyClicks (u.PTT_port_combo_box->lineEdit (), "/dev/typed-port"); + QCOMPARE (activated.count (), 0); + QVERIFY (u.force_DTR_combo_box->isEnabled ()); + u.CAT_port_combo_box->setEditText ("/dev/typed-port"); + QVERIFY (!u.force_DTR_combo_box->isEnabled ()); + u.CAT_handshake_hardware_radio_button->setChecked (true); + QVERIFY (!u.PTT_RTS_radio_button->isEnabled ()); + u.PTT_port_combo_box->setCurrentText ("/dev/separate-port"); + QVERIFY (u.PTT_RTS_radio_button->isEnabled ()); + QVERIFY (!u.force_RTS_combo_box->isEnabled ()); + } + + void validationRefreshesBlockedProgrammaticChanges_data () + { + QTest::addColumn ("port"); + QTest::newRow ("unsupported proxy") << QString {"CAT"}; + QTest::newRow ("USB is not serial PTT") << QString {"USB"}; + QTest::newRow ("empty") << QString {}; + QTest::newRow ("whitespace") << QString {" "}; + } + + void validationRefreshesBlockedProgrammaticChanges () + { + QFETCH (QString, port); + auto& u = ui (); + { + QSignalBlocker blocked {u.PTT_port_combo_box}; + u.PTT_port_combo_box->setEditText (port); + } + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::invalid_ptt_port); + QVERIFY (!dialog ().rig_active_); + QCOMPARE (dialog ().rig_params_.ptt_port, QString {"/dev/test-cat"}); + } + + void cancelRestoresSavedPorts () + { + auto& u = ui (); + u.CAT_port_combo_box->setEditText ("/dev/edited-cat"); + u.PTT_port_combo_box->setEditText ("/dev/edited-ptt"); + u.configuration_dialog_button_box->button (QDialogButtonBox::Cancel)->click (); + QCOMPARE (u.CAT_port_combo_box->currentText (), QString {"/dev/test-cat"}); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {"/dev/test-cat"}); + QVERIFY (!u.force_DTR_combo_box->isEnabled ()); + } + + void validationRefreshesHandshakeAfterBlockedRigChange () + { + auto& u = ui (); + u.rig_combo_box->setCurrentText (network_rig_); + u.CAT_handshake_hardware_radio_button->setChecked (true); + u.PTT_RTS_radio_button->setChecked (true); + QVERIFY (u.PTT_RTS_radio_button->isEnabled ()); + { + QSignalBlocker blocked {u.rig_combo_box}; + u.rig_combo_box->setCurrentText (serial_rig_); + } + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::invalid_ptt_method); + QCOMPARE (u.CAT_port_combo_box->currentText (), u.PTT_port_combo_box->currentText ()); + QVERIFY (!u.PTT_RTS_radio_button->isEnabled ()); + QVERIFY (!u.force_RTS_combo_box->isEnabled ()); + } + + void noneRetainsSerialPortSelection () + { + auto& u = ui (); + u.CAT_port_combo_box->setEditText ("/dev/edited-cat"); + u.rig_combo_box->setCurrentText ("None"); + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.CAT_port_combo_box->currentText (), QString {"/dev/edited-cat"}); + } + + void destructionCancelsDeferredFileInformation () + { + configuration_.reset (); + QTest::qWait (3000); + } +}; + +QTEST_MAIN (TestConfigurationRadio) +#include "test_configuration_radio.moc" diff --git a/tests/unit/common/test_decode_highlighting_model.cpp b/tests/unit/common/test_decode_highlighting_model.cpp new file mode 100644 index 00000000..c34223c2 --- /dev/null +++ b/tests/unit/common/test_decode_highlighting_model.cpp @@ -0,0 +1,526 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include "models/DecodeHighlightingModel.hpp" + +class TestDecodeHighlightingModel + : public QObject +{ + Q_OBJECT + + using Highlight = DecodeHighlightingModel::Highlight; + using HighlightItems = DecodeHighlightingModel::HighlightItems; + using HighlightColors = DecodeHighlightingModel::HighlightColors; + using ColorPreset = DecodeHighlightingModel::ColorPreset; + + static HighlightColors const * colors_for (ColorPreset const& preset, Highlight type) + { + for (auto const& colors : preset) + { + if (colors.type_ == type) + { + return &colors; + } + } + return nullptr; + } + + static qreal relative_luminance (QColor const& color) + { + auto linear = [] (int component) { + auto const value = component / 255.; + return value <= .04045 ? value / 12.92 : std::pow ((value + .055) / 1.055, 2.4); + }; + return .2126 * linear (color.red ()) + + .7152 * linear (color.green ()) + + .0722 * linear (color.blue ()); + } + + static qreal contrast_ratio (QColor const& first, QColor const& second) + { + auto const first_luminance = relative_luminance (first); + auto const second_luminance = relative_luminance (second); + auto const lighter = std::max (first_luminance, second_luminance); + auto const darker = std::min (first_luminance, second_luminance); + return (lighter + .05) / (darker + .05); + } + + template + static void verify_complete_type_coverage (Items const& items, char const * name) + { + auto const meta = QMetaEnum::fromType (); + QSet types; + for (auto const& item : items) + { + auto const type = static_cast (item.type_); + auto const message = QString {"%1 contains unknown or duplicate type %2"}.arg (name).arg (type); + QVERIFY2 (meta.valueToKey (type), qPrintable (message)); + QVERIFY2 (!types.contains (type), qPrintable (message)); + types.insert (type); + } + QCOMPARE (types.size (), meta.keyCount ()); + for (int key {0}; key < meta.keyCount (); ++key) + { + auto const message = QString {"%1 omits %2"}.arg (name).arg (meta.key (key)); + QVERIFY2 (types.contains (meta.value (key)), qPrintable (message)); + } + } + +private Q_SLOTS: + void refactored_defaults_preserve_existing_values () + { + HighlightItems const expected_default = { + {Highlight::MyCall, true, {}, {{0xff, 0x66, 0x66}}} + , {Highlight::Continent, true, {}, {{0xff, 0x00, 0x63}}} + , {Highlight::ContinentBand, true, {}, {{0xff, 0x99, 0xc2}}} + , {Highlight::CQZone, true, {}, {{0xff, 0xbf, 0x00}}} + , {Highlight::CQZoneBand, true, {}, {{0xff, 0xe4, 0x99}}} + , {Highlight::ITUZone, false, {}, {{0xa6, 0xff, 0x00}}} + , {Highlight::ITUZoneBand, false, {}, {{0xdd, 0xff, 0x99}}} + , {Highlight::DXCC, true, {}, {{0xff, 0x00, 0xff}}} + , {Highlight::DXCCBand, true, {}, {{0xff, 0xaa, 0xff}}} + , {Highlight::Grid, false, {}, {{0xff, 0x80, 0x00}}} + , {Highlight::GridBand, false, {}, {{0xff, 0xcc, 0x99}}} + , {Highlight::Call, false, {}, {{0x00, 0xff, 0xff}}} + , {Highlight::CallBand, false, {}, {{0x99, 0xff, 0xff}}} + , {Highlight::LotW, false, {{0x99, 0x00, 0x00}}, {}} + , {Highlight::CQ, true, {}, {{0x66, 0xff, 0x66}}} + , {Highlight::Tx, true, {}, {Qt::yellow}} + }; + HighlightItems const expected_default2 = { + {Highlight::LotW, true, {Qt::black}, {}} + , {Highlight::MyCall, true, {{0xaa, 0x00, 0x00}}, {{0x00, 0xff, 0xff}}} + , {Highlight::Continent, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0x50, 0xff}}} + , {Highlight::ContinentBand, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0x82, 0xff}}} + , {Highlight::DXCC, true, {{0xaa, 0x00, 0x00}}, {Qt::yellow}} + , {Highlight::DXCCBand, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0xff, 0x9b}}} + , {Highlight::CQZone, true, {{0xaa, 0x00, 0x00}}, {{0xaa, 0xaa, 0x00}}} + , {Highlight::CQZoneBand, true, {{0xaa, 0x00, 0x00}}, {{0xaa, 0xaa, 0x7f}}} + , {Highlight::ITUZone, true, {{0xaa, 0x00, 0x00}}, {{0x37, 0xbd, 0xff}}} + , {Highlight::ITUZoneBand, true, {{0xaa, 0x00, 0x00}}, {{0x91, 0xde, 0xff}}} + , {Highlight::Grid, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0xa8, 0x80}}} + , {Highlight::GridBand, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0xcd, 0x9b}}} + , {Highlight::Call, true, {{0xaa, 0x00, 0x00}}, {{0x64, 0xff, 0x64}}} + , {Highlight::CallBand, true, {{0xaa, 0x00, 0x00}}, {{0xb4, 0xff, 0xb4}}} + , {Highlight::CQ, true, {{0xaa, 0x00, 0x00}}, {{0xc3, 0xc3, 0xc3}}} + , {Highlight::Tx, true, {Qt::black}, {{0xff, 0xa5, 0xc6}}} + }; + + QVERIFY (DecodeHighlightingModel::default_items () == expected_default); + QVERIFY (DecodeHighlightingModel::default_items2 () == expected_default2); + } + + void built_in_presets_are_complete () + { + DecodeHighlightingModel model; + + verify_complete_type_coverage (DecodeHighlightingModel::default_items (), "Default 1 items"); + verify_complete_type_coverage (DecodeHighlightingModel::default_items2 (), "Default 2 items"); + verify_complete_type_coverage (DecodeHighlightingModel::default_color_preset (), "Default 1 preset"); + verify_complete_type_coverage (DecodeHighlightingModel::default2_color_preset (), "Default 2 preset"); + verify_complete_type_coverage (DecodeHighlightingModel::red_green_color_vision_preset (), "Red/green preset"); + verify_complete_type_coverage (DecodeHighlightingModel::blue_yellow_color_vision_preset (), "Blue/yellow preset"); + verify_complete_type_coverage (DecodeHighlightingModel::high_contrast_color_preset (), "High contrast preset"); + verify_complete_type_coverage (DecodeHighlightingModel::dark_shack_color_preset (), "Dark shack preset"); + verify_complete_type_coverage (DecodeHighlightingModel::solarized_color_preset (), "Solarized preset"); + verify_complete_type_coverage (DecodeHighlightingModel::monochrome_color_preset (), "Monochrome preset"); + + QCOMPARE (DecodeHighlightingModel::default_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::default2_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::red_green_color_vision_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::blue_yellow_color_vision_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::high_contrast_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::dark_shack_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::solarized_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::monochrome_color_preset ().size (), model.items ().size ()); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default2_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::red_green_color_vision_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::blue_yellow_color_vision_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::high_contrast_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::dark_shack_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::solarized_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::monochrome_color_preset ())); + } + + void default_presets_match_reset_colors () + { + struct DefaultPair final + { + HighlightItems const& items_; + ColorPreset const& preset_; + }; + DefaultPair const defaults[] = { + {DecodeHighlightingModel::default_items (), DecodeHighlightingModel::default_color_preset ()} + , {DecodeHighlightingModel::default_items2 (), DecodeHighlightingModel::default2_color_preset ()} + }; + + for (auto const& default_pair : defaults) + { + for (auto const& item : default_pair.items_) + { + auto const colors = colors_for (default_pair.preset_, item.type_); + QVERIFY (colors); + QCOMPARE (colors->foreground_, item.foreground_); + QCOMPARE (colors->background_, item.background_); + } + } + } + + void color_resolution_honors_priority_and_reordering () + { + HighlightItems items { + {Highlight::MyCall, true, QBrush {Qt::white}, QBrush {Qt::red}} + , {Highlight::CQ, true, QBrush {Qt::black}, QBrush {Qt::yellow}} + }; + DecodeHighlightingModel::HighlightTypes matches {Highlight::CQ, Highlight::MyCall}; + + auto resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::MyCall); + QCOMPARE (resolved.background_, QColor {Qt::red}); + QCOMPARE (resolved.foreground_, QColor {Qt::white}); + + items.prepend (items.takeLast ()); + resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::CQ); + QCOMPARE (resolved.background_, QColor {Qt::yellow}); + QCOMPARE (resolved.foreground_, QColor {Qt::black}); + } + + void color_resolution_composes_independent_channels () + { + HighlightItems const items { + {Highlight::MyCall, true, {}, QBrush {Qt::red}} + , {Highlight::DXCC, true, QBrush {Qt::white}, {}} + , {Highlight::CQ, true, QBrush {Qt::black}, QBrush {Qt::yellow}} + }; + DecodeHighlightingModel::HighlightTypes const matches { + Highlight::CQ, Highlight::DXCC, Highlight::MyCall + }; + + auto const resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::MyCall); + QCOMPARE (resolved.background_, QColor {Qt::red}); + QCOMPARE (resolved.foreground_, QColor {Qt::white}); + } + + void color_resolution_ignores_disabled_rules () + { + HighlightItems const items { + {Highlight::MyCall, false, QBrush {Qt::white}, QBrush {Qt::red}} + , {Highlight::CQ, true, QBrush {Qt::black}, QBrush {Qt::yellow}} + }; + DecodeHighlightingModel::HighlightTypes const matches {Highlight::CQ, Highlight::MyCall}; + + auto const resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::CQ); + QCOMPARE (resolved.background_, QColor {Qt::yellow}); + QCOMPARE (resolved.foreground_, QColor {Qt::black}); + } + + void complete_pair_presets_meet_text_contrast () + { + struct NamedPreset final + { + char const * name_; + ColorPreset const& preset_; + }; + NamedPreset const presets[] = { + {"red/green", DecodeHighlightingModel::red_green_color_vision_preset ()} + , {"blue/yellow", DecodeHighlightingModel::blue_yellow_color_vision_preset ()} + , {"high contrast", DecodeHighlightingModel::high_contrast_color_preset ()} + , {"dark shack", DecodeHighlightingModel::dark_shack_color_preset ()} + , {"solarized", DecodeHighlightingModel::solarized_color_preset ()} + , {"monochrome", DecodeHighlightingModel::monochrome_color_preset ()} + }; + + for (auto const& named_preset : presets) + { + for (auto const& colors : named_preset.preset_) + { + auto const rule_name = DecodeHighlightingModel::highlight_name (colors.type_); + auto const unset_message = QString {"%1: %2 must set both foreground and background colors"} + .arg (named_preset.name_) + .arg (rule_name); + QVERIFY2 (Qt::NoBrush != colors.foreground_.style (), qPrintable (unset_message)); + QVERIFY2 (Qt::NoBrush != colors.background_.style (), qPrintable (unset_message)); + auto const ratio = contrast_ratio (colors.foreground_.color (), colors.background_.color ()); + auto const message = QString {"%1: %2 has contrast ratio %3"} + .arg (named_preset.name_) + .arg (rule_name) + .arg (ratio, 0, 'f', 2); + QVERIFY2 (ratio >= 4.5, qPrintable (message)); + } + } + } + + void monochrome_preset_is_achromatic () + { + for (auto const& colors : DecodeHighlightingModel::monochrome_color_preset ()) + { + QColor const pair[] = {colors.foreground_.color (), colors.background_.color ()}; + for (auto const& color : pair) + { + QCOMPARE (color.red (), color.green ()); + QCOMPARE (color.green (), color.blue ()); + } + } + } + + void dark_shack_preset_uses_dark_backgrounds () + { + qreal constexpr maximum_background_luminance {.15}; + for (auto const& colors : DecodeHighlightingModel::dark_shack_color_preset ()) + { + auto const luminance = relative_luminance (colors.background_.color ()); + auto const message = QString {"%1 background luminance %2 exceeds %3"} + .arg (DecodeHighlightingModel::highlight_name (colors.type_)) + .arg (luminance, 0, 'f', 3) + .arg (maximum_background_luminance, 0, 'f', 3); + QVERIFY2 (luminance <= maximum_background_luminance, qPrintable (message)); + } + } + + void operating_presets_separate_all_band_backgrounds_from_cq () + { + struct AlertPair final + { + Highlight all_band_; + Highlight on_band_; + }; + AlertPair const alert_pairs[] = { + {Highlight::Continent, Highlight::ContinentBand} + , {Highlight::CQZone, Highlight::CQZoneBand} + , {Highlight::ITUZone, Highlight::ITUZoneBand} + , {Highlight::DXCC, Highlight::DXCCBand} + , {Highlight::Grid, Highlight::GridBand} + , {Highlight::Call, Highlight::CallBand} + }; + ColorPreset const * presets[] = { + &DecodeHighlightingModel::dark_shack_color_preset () + , &DecodeHighlightingModel::solarized_color_preset () + , &DecodeHighlightingModel::monochrome_color_preset () + }; + + for (auto const preset : presets) + { + auto const cq = colors_for (*preset, Highlight::CQ); + QVERIFY (cq); + for (auto const& pair : alert_pairs) + { + auto const all_band = colors_for (*preset, pair.all_band_); + auto const on_band = colors_for (*preset, pair.on_band_); + QVERIFY (all_band); + QVERIFY (on_band); + auto const all_band_contrast = contrast_ratio ( + all_band->background_.color (), cq->background_.color ()); + auto const on_band_contrast = contrast_ratio ( + on_band->background_.color (), cq->background_.color ()); + auto const minimum_contrast = on_band_contrast * 1.1; + auto const message = QString {"%1 background contrast %2 must be at least 10% greater " + "than %3's %4"} + .arg (DecodeHighlightingModel::highlight_name (pair.all_band_)) + .arg (all_band_contrast, 0, 'f', 2) + .arg (DecodeHighlightingModel::highlight_name (pair.on_band_)) + .arg (on_band_contrast, 0, 'f', 2); + QVERIFY2 (all_band_contrast >= minimum_contrast, qPrintable (message)); + } + } + } + + void preset_changes_only_colors () + { + DecodeHighlightingModel model; + auto custom = DecodeHighlightingModel::default_items (); + custom.append (custom.takeFirst ()); + for (int row {0}; row < custom.size (); ++row) + { + custom[row].enabled_ = 0 == row % 2; + custom[row].foreground_ = QBrush {QColor {row, row + 1, row + 2}}; + custom[row].background_ = QBrush {QColor {row + 3, row + 4, row + 5}}; + } + model.items (custom); + auto const before = model.items (); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + QSignalSpy resets {&model, &QAbstractItemModel::modelReset}; + + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default2_color_preset ())); + + auto const after = model.items (); + QCOMPARE (after.size (), before.size ()); + for (int row {0}; row < after.size (); ++row) + { + QCOMPARE (after[row].type_, before[row].type_); + QCOMPARE (after[row].enabled_, before[row].enabled_); + auto const colors = colors_for (DecodeHighlightingModel::default2_color_preset (), after[row].type_); + QVERIFY (colors); + QCOMPARE (after[row].foreground_, colors->foreground_); + QCOMPARE (after[row].background_, colors->background_); + } + QCOMPARE (changes.size (), 1); + auto const change = changes.takeFirst (); + QCOMPARE (change.at (0).value (), model.index (0, 0)); + QCOMPARE (change.at (1).value (), model.index (after.size () - 1, 0)); + auto const roles = change.at (2).value> (); + QCOMPARE (roles, QVector ({Qt::DisplayRole, Qt::ForegroundRole, Qt::BackgroundRole})); + QCOMPARE (resets.size (), 0); + auto const lotw = std::find_if (after.cbegin (), after.cend (), [] (auto const& item) { + return item.type_ == Highlight::LotW; + }); + QVERIFY (lotw != after.cend ()); + auto const lotw_row = static_cast (std::distance (after.cbegin (), lotw)); + auto const& abstract_model = static_cast (model); + QVERIFY (abstract_model.data (model.index (lotw_row, 0), Qt::DisplayRole).toString ().contains ("b/g unset")); + + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default2_color_preset ())); + QCOMPARE (changes.size (), 0); + } + + void color_changes_notify_display_role () + { + DecodeHighlightingModel model; + auto items = model.items (); + items[0].foreground_ = QBrush {Qt::black}; + items[0].background_ = QBrush {Qt::white}; + model.items (items); + auto const index = model.index (0, 0); + auto& abstract_model = static_cast (model); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + + QVERIFY (abstract_model.setData (index, QBrush {}, Qt::ForegroundRole)); + QCOMPARE (changes.size (), 1); + QCOMPARE (changes.takeFirst ().at (2).value> (), + QVector ({Qt::ForegroundRole, Qt::DisplayRole})); + QVERIFY (abstract_model.data (index, Qt::DisplayRole).toString ().contains ("f/g unset")); + + QVERIFY (abstract_model.setData (index, QBrush {}, Qt::BackgroundRole)); + QCOMPARE (changes.size (), 1); + QCOMPARE (changes.takeFirst ().at (2).value> (), + QVector ({Qt::BackgroundRole, Qt::DisplayRole})); + QVERIFY (abstract_model.data (index, Qt::DisplayRole).toString ().contains ("b/g unset")); + } + + void complete_presets_apply_to_legacy_models () + { + DecodeHighlightingModel model; + auto legacy = DecodeHighlightingModel::default_items (); + legacy.erase (std::remove_if (legacy.begin (), legacy.end (), [] (auto const& item) { + return item.type_ == Highlight::Continent + || item.type_ == Highlight::ContinentBand + || item.type_ == Highlight::CQZone + || item.type_ == Highlight::CQZoneBand + || item.type_ == Highlight::ITUZone + || item.type_ == Highlight::ITUZoneBand; + }), legacy.end ()); + model.items (legacy); + + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::high_contrast_color_preset ())); + QCOMPARE (model.items ().size (), legacy.size ()); + for (auto const& item : model.items ()) + { + auto const colors = colors_for (DecodeHighlightingModel::high_contrast_color_preset (), item.type_); + QVERIFY (colors); + QCOMPARE (item.foreground_, colors->foreground_); + QCOMPARE (item.background_, colors->background_); + } + } + + void presets_apply_to_duplicate_model_rules () + { + DecodeHighlightingModel model; + auto malformed = DecodeHighlightingModel::default_items (); + malformed.last ().type_ = malformed.first ().type_; + malformed.first ().foreground_ = QBrush {Qt::magenta}; + malformed.last ().foreground_ = QBrush {Qt::cyan}; + model.items (malformed); + + auto const& preset = DecodeHighlightingModel::high_contrast_color_preset (); + QVERIFY (model.apply_color_preset (preset)); + + auto const colors = colors_for (preset, malformed.first ().type_); + QVERIFY (colors); + auto const after = model.items (); + QCOMPARE (after.first ().foreground_, colors->foreground_); + QCOMPARE (after.first ().background_, colors->background_); + QCOMPARE (after.last ().foreground_, colors->foreground_); + QCOMPARE (after.last ().background_, colors->background_); + } + + void invalid_presets_do_not_modify_model () + { + DecodeHighlightingModel model; + auto custom = model.items (); + for (int row {0}; row < custom.size (); ++row) + { + custom[row].foreground_ = QBrush {QColor {row + 1, row + 2, row + 3}}; + custom[row].background_ = QBrush {QColor {row + 4, row + 5, row + 6}}; + } + model.items (custom); + auto const before = model.items (); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + + auto incomplete = DecodeHighlightingModel::high_contrast_color_preset (); + incomplete.removeLast (); + QVERIFY (!model.apply_color_preset (incomplete)); + QVERIFY (model.items () == before); + + auto duplicate = DecodeHighlightingModel::default_color_preset (); + duplicate.last ().type_ = duplicate.first ().type_; + QVERIFY (!model.apply_color_preset (duplicate)); + QVERIFY (model.items () == before); + QCOMPARE (changes.size (), 0); + } + + void empty_models_reject_presets () + { + DecodeHighlightingModel model; + model.items ({}); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + + QVERIFY (!model.apply_color_preset (DecodeHighlightingModel::default_color_preset ())); + QVERIFY (model.items ().isEmpty ()); + QCOMPARE (changes.size (), 0); + } + + void preset_colors_round_trip_through_settings () + { + qRegisterMetaTypeStreamOperators ("HighlightInfo"); + qRegisterMetaTypeStreamOperators ("HighlightItems"); + + DecodeHighlightingModel model; + auto customized = model.items (); + customized.append (customized.takeFirst ()); + for (int row {0}; row < customized.size (); ++row) + { + customized[row].enabled_ = 0 == row % 2; + } + model.items (customized); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::solarized_color_preset ())); + + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const filename = directory.filePath ("wsjtx.ini"); + { + QSettings settings {filename, QSettings::IniFormat}; + settings.setValue ("DecodeHighlighting", QVariant::fromValue (model.items ())); + settings.sync (); + QCOMPARE (settings.status (), QSettings::NoError); + } + + QSettings settings {filename, QSettings::IniFormat}; + auto const restored = settings.value ("DecodeHighlighting").value (); + QVERIFY (restored == model.items ()); + } +}; + +QTEST_APPLESS_MAIN (TestDecodeHighlightingModel); + +#include "test_decode_highlighting_model.moc" diff --git a/tests/unit/common/test_frequency_list.cpp b/tests/unit/common/test_frequency_list.cpp new file mode 100644 index 00000000..92933cfc --- /dev/null +++ b/tests/unit/common/test_frequency_list.cpp @@ -0,0 +1,294 @@ +#include + +#include + +#include +#include +#include + +#include "models/Bands.hpp" +#include "models/FrequencyList.hpp" + +namespace +{ + using WorkingFrequencies = FrequencyList_v2_101; + + class LocaleGuard + { + public: + ~LocaleGuard () { QLocale::setDefault (original_); } + private: + QLocale original_; + }; + + class RegionTranslator : public QTranslator + { + public: + bool isEmpty () const override { return false; } + QString translate (char const * context, char const * source, + char const * = nullptr, int = -1) const override + { + if (QString::fromLatin1 (context) == "IARURegions") + return "Translated " + QString::fromLatin1 (source); + return {}; + } + }; + + QList visible_frequencies (WorkingFrequencies const& model) + { + QList result; + for (auto const& item : model) result.append (item.frequency_); + std::sort (result.begin (), result.end ()); + return result; + } + + Radio::Frequency selected_frequency (WorkingFrequencies const& model, int row) + { + if (row < 0 || row >= model.rowCount ()) return 0; + return model.frequency_list ({model.index (row, 0)}).value (0).frequency_; + } +} + +class TestFrequencyList : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void json_round_trip_data (); + void json_round_trip (); + void legacy_locale_frequencies_data (); + void legacy_locale_frequencies (); + void invalid_documents_data (); + void invalid_documents (); + void invalid_entries_are_isolated (); + void mode_names_are_normalized (); + void eligibility_filters (); + void selection_uses_eligible_frequencies (); +}; + +void TestFrequencyList::json_round_trip_data () +{ + QTest::addColumn ("locale_name"); + QTest::addColumn ("translated"); + QTest::newRow ("C") << QStringLiteral ("C") << false; + QTest::newRow ("decimal-comma") << QStringLiteral ("de_DE") << false; + QTest::newRow ("translated-regions") << QStringLiteral ("C") << true; +} + +void TestFrequencyList::json_round_trip () +{ + QFETCH (QString, locale_name); + QFETCH (bool, translated); + LocaleGuard restore_locale; + QLocale::setDefault (QLocale {locale_name}); + RegionTranslator translator; + if (translated) QVERIFY (QCoreApplication::installTranslator (&translator)); + + Bands bands; + WorkingFrequencies model {&bands}; + WorkingFrequencies::FrequencyItems const expected { + {1000001, Modes::FreqCal, IARURegions::R1, "Reference", "Test source", + QDateTime::fromString ("2026-01-01T12:34:56Z", Qt::ISODate), + QDateTime::fromString ("2026-12-31T12:34:56Z", Qt::ISODate), true}, + {14074000, Modes::FT8, IARURegions::ALL, {}, {}, {}, {}, false}, + {7078000, Modes::ALL, IARURegions::R2, {}, {}, {}, {}, false} + }; + QTemporaryFile file; + QVERIFY (file.open ()); + model.to_json_file (&file, "test", "101", expected); + QVERIFY (file.seek (0)); + auto const document = QJsonDocument::fromJson (file.readAll ()); + QCOMPARE (document.object ()["frequencies"].toArray ()[0].toObject ()["frequency"].toString (), + QStringLiteral ("1.000001")); + QVERIFY (file.seek (0)); + auto const actual = WorkingFrequencies::from_json_file (&file); + QCOMPARE (actual.size (), expected.size ()); + for (int i = 0; i < expected.size (); ++i) QCOMPARE (actual[i], expected[i]); +} + +void TestFrequencyList::legacy_locale_frequencies_data () +{ + QTest::addColumn ("frequency_text"); + QTest::addColumn ("frequency_hz"); + QTest::newRow ("German decimal comma") << QStringLiteral ("14,074000") << Radio::Frequency {14074000}; + QTest::newRow ("German grouping") << QStringLiteral ("1.296,000000") << Radio::Frequency {1296000000}; + QTest::newRow ("French narrow-space grouping") << QStringLiteral ("1\u202f296,000000") + << Radio::Frequency {1296000000}; + QTest::newRow ("French older grouping") << QStringLiteral ("1\u00a0296,000000") + << Radio::Frequency {1296000000}; + QTest::newRow ("Russian grouping") << QLocale {"ru_RU"}.toString (1296., 'f', 6) + << Radio::Frequency {1296000000}; + QTest::newRow ("Swiss apostrophe grouping") << QStringLiteral ("1\u2019296.000000") + << Radio::Frequency {1296000000}; + QTest::newRow ("Swiss older grouping") << QStringLiteral ("1'296.000000") + << Radio::Frequency {1296000000}; +} + +void TestFrequencyList::legacy_locale_frequencies () +{ + QFETCH (QString, frequency_text); + QFETCH (Radio::Frequency, frequency_hz); + LocaleGuard restore_locale; + QLocale::setDefault (QLocale::c ()); + QVERIFY (frequency_text != QLocale::c ().toString (frequency_hz / 1e6, 'f', 6)); + QJsonArray entries {QJsonObject {{"frequency", frequency_text}, {"mode", "FT8"}, + {"region", "Region 1"}}}; + QTemporaryFile file; + QVERIFY (file.open ()); + auto const contents = QJsonDocument {QJsonObject {{"frequencies", entries}}}.toJson (); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + WorkingFrequencies::ImportReport report; + auto const actual = WorkingFrequencies::from_json_file (&file, &report); + QCOMPARE (report.entries, 1); + QCOMPARE (report.imported, 1); + QCOMPARE (report.skipped (), 0); + QCOMPARE (actual.size (), 1); + QCOMPARE (actual.front ().frequency_, frequency_hz); +} + +void TestFrequencyList::invalid_documents_data () +{ + QTest::addColumn ("contents"); + QTest::newRow ("malformed") << QByteArray {"{"}; + QTest::newRow ("missing-frequencies") << QByteArray {"{\"wsjtx_file\":\"qrg\"}"}; + QTest::newRow ("empty-frequencies") << QByteArray {"{\"frequencies\":[]}"}; +} + +void TestFrequencyList::invalid_documents () +{ + QFETCH (QByteArray, contents); + QTemporaryFile file; + QVERIFY (file.open ()); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + QVERIFY_EXCEPTION_THROWN (WorkingFrequencies::from_json_file (&file), ReadFileException); +} + +void TestFrequencyList::invalid_entries_are_isolated () +{ + QJsonObject const valid {{"frequency", "14.074000"}, {"mode", "FT8"}, + {"region", "Region 1"}}; + QJsonArray entries; + for (auto const& frequency : {"invalid", "-1", "18446744073709.551616", "0", "14,074"}) + { + auto invalid = valid; + invalid["frequency"] = frequency; + entries.append (invalid); + } + for (auto const& field : {"mode", "region"}) + { + auto invalid = valid; + invalid[field] = "Unknown"; + entries.append (invalid); + } + entries.insert (2, valid); + auto unknown_mode = valid; + unknown_mode["mode"] = "FT2"; + entries.append (unknown_mode); + auto invalid_dates = valid; + invalid_dates["start_time"] = "2026-12-31T00:00:00Z"; + invalid_dates["end_time"] = "2026-01-01T00:00:00Z"; + entries.append (invalid_dates); + auto malformed_date = valid; + malformed_date["start_time"] = "not a date"; + entries.append (malformed_date); + QTemporaryFile file; + QVERIFY (file.open ()); + auto const contents = QJsonDocument {QJsonObject {{"frequencies", entries}}}.toJson (); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + WorkingFrequencies::ImportReport report; + auto const actual = WorkingFrequencies::from_json_file (&file, &report); + QCOMPARE (actual.size (), 1); + QCOMPARE (actual.front ().frequency_, Radio::Frequency {14074000}); + QCOMPARE (actual.front ().mode_, Modes::FT8); + QCOMPARE (actual.front ().region_, IARURegions::R1); + QCOMPARE (report.entries, entries.size ()); + QCOMPARE (report.imported, 1); + QCOMPARE (report.invalid_frequency, 5); + QCOMPARE (report.invalid_region, 1); + QCOMPARE (report.unknown_modes.value ("Unknown"), 1); + QCOMPARE (report.unknown_modes.value ("FT2"), 1); + QCOMPARE (report.invalid_item, 2); + QCOMPARE (report.skipped (), 10); +} + +void TestFrequencyList::mode_names_are_normalized () +{ + QJsonArray entries; + for (auto const& mode : {"ft8", " FT8 ", "", "All"}) + { + QJsonObject entry {{"frequency", "14.074000"}, {"region", "Region 1"}}; + entry["mode"] = mode; + entries.append (entry); + } + entries.append (QJsonObject {{"frequency", "7.074000"}, {"region", "Region 1"}}); + QTemporaryFile file; + QVERIFY (file.open ()); + auto const contents = QJsonDocument {QJsonObject {{"frequencies", entries}}}.toJson (); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + WorkingFrequencies::ImportReport report; + auto const actual = WorkingFrequencies::from_json_file (&file, &report); + QCOMPARE (report.imported, entries.size ()); + QCOMPARE (report.skipped (), 0); + QCOMPARE (actual[0].mode_, Modes::FT8); + QCOMPARE (actual[1].mode_, Modes::FT8); + QCOMPARE (actual[2].mode_, Modes::ALL); + QCOMPARE (actual[3].mode_, Modes::ALL); + QCOMPARE (actual[4].mode_, Modes::ALL); +} + +void TestFrequencyList::eligibility_filters () +{ + Bands bands; + WorkingFrequencies model {&bands}; + auto const now = QDateTime::currentDateTimeUtc (); + model.frequency_list ({ + {14074000, Modes::FT8, IARURegions::R1, {}, {}, now.addDays (-1), now.addDays (1), false}, + {7074000, Modes::FT8, IARURegions::ALL, {}, {}, {}, {}, false}, + {10136000, Modes::ALL, IARURegions::R1, {}, {}, {}, {}, false}, + {50313000, Modes::FT8, IARURegions::R2, {}, {}, {}, {}, false}, + {14080000, Modes::FT4, IARURegions::R1, {}, {}, {}, {}, false}, + {10000000, Modes::FreqCal, IARURegions::ALL, {}, {}, {}, {}, false}, + {3573000, Modes::FT8, IARURegions::R1, {}, {}, {}, now.addDays (-1), false}, + {1840000, Modes::FT8, IARURegions::R1, {}, {}, now.addDays (1), {}, false} + }); + model.filter (IARURegions::R1, Modes::FT8, true); + QCOMPARE (visible_frequencies (model), (QList {7074000, 10136000, 14074000})); + model.filter (IARURegions::R1, Modes::FT8, false); + QCOMPARE (visible_frequencies (model), (QList {1840000, 3573000, 7074000, 10136000, 14074000})); + model.filter (IARURegions::R1, Modes::FreqCal, true); + QCOMPARE (visible_frequencies (model), (QList {10000000})); + model.filter (IARURegions::ALL, Modes::ALL, false); + QCOMPARE (model.rowCount (), 8); +} + +void TestFrequencyList::selection_uses_eligible_frequencies () +{ + Bands bands; + WorkingFrequencies model {&bands}; + WorkingFrequencies::Item const preferred {14074000, Modes::FT8, IARURegions::ALL, + {}, {}, {}, {}, true}; + model.frequency_list ({ + preferred, + {14080000, Modes::FT8, IARURegions::R1, {}, {}, {}, {}, false}, + {14090000, Modes::FT8, IARURegions::R1, {}, {}, {}, {}, false}, + {14081000, Modes::FT8, IARURegions::R2, {}, {}, {}, {}, true}, + {7074000, Modes::FT8, IARURegions::R2, {}, {}, {}, {}, true} + }); + model.filter (IARURegions::R1, Modes::FT8, false); + QCOMPARE (selected_frequency (model, model.best_working_frequency (Radio::Frequency {14081000})), + preferred.frequency_); + QCOMPARE (selected_frequency (model, model.best_working_frequency (QString {"20m"})), + preferred.frequency_); + QVERIFY (model.remove (preferred)); + QCOMPARE (selected_frequency (model, model.best_working_frequency (Radio::Frequency {14081000})), + Radio::Frequency {14080000}); + QCOMPARE (model.best_working_frequency (Radio::Frequency {7074000}), -1); + QCOMPARE (model.best_working_frequency (QString {"40m"}), -1); +} + +QTEST_GUILESS_MAIN (TestFrequencyList) +#include "test_frequency_list.moc" diff --git a/tests/unit/common/test_frequency_suggestions.cpp b/tests/unit/common/test_frequency_suggestions.cpp new file mode 100644 index 00000000..fdd8f0ed --- /dev/null +++ b/tests/unit/common/test_frequency_suggestions.cpp @@ -0,0 +1,200 @@ +#include +#include +#include +#include +#include +#include + +#include "models/Bands.hpp" +#include "models/FrequencySuggestions.hpp" +#include "widgets/SuggestedFrequenciesDialog.hpp" + +namespace +{ + using Item = FrequencyList_v2_101::Item; + using Items = FrequencyList_v2_101::FrequencyItems; + + Item frequency (Radio::Frequency dial, Modes::Mode mode = Modes::FT8, + IARURegions::Region region = IARURegions::ALL, + QString description = {}, bool preferred = false) + { + return {dial, mode, region, description, {}, {}, {}, preferred}; + } +} + +class TestFrequencySuggestions final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void matchesOperatingIdentity () + { + auto const proposed = frequency (14090000, Modes::FT8, IARURegions::R2); + auto const customized = frequency (14090000, Modes::FT8, IARURegions::ALL, + "My DX frequency", true); + QVERIFY (FrequencySuggestions::is_present (proposed, Items {customized})); + QVERIFY (!FrequencySuggestions::is_present ( + frequency (14091000, Modes::FT8, IARURegions::R2), Items {customized})); + QVERIFY (!FrequencySuggestions::is_present ( + frequency (14090000, Modes::JTTY, IARURegions::R2), Items {customized})); + QVERIFY (!FrequencySuggestions::is_present ( + frequency (14090000, Modes::FT8, IARURegions::ALL), + Items {frequency (14090000, Modes::FT8, IARURegions::R2)})); + QVERIFY (FrequencySuggestions::is_present ( + proposed, Items {frequency (14090000, Modes::ALL)})); + } + + void preservesCustomRowsAndPreferences () + { + Bands bands; + auto const custom = frequency (14074000, Modes::FT8, IARURegions::ALL, + "Personal calling spot", true); + Items working {custom}; + Items selected {frequency (14074000, Modes::FT8, IARURegions::ALL), + frequency (14090000, Modes::FT8, IARURegions::ALL, {}, true), + frequency (14090000, Modes::FT8, IARURegions::ALL, {}, true)}; + + auto additions = FrequencySuggestions::prepare_additions (selected, working, bands); + QCOMPARE (additions.size (), 1); + QCOMPARE (additions.first ().frequency_, Radio::Frequency {14090000}); + QVERIFY (!additions.first ().preferred_); + QCOMPARE (working.first ().description_, QStringLiteral ("Personal calling spot")); + QVERIFY (working.first ().preferred_); + } + + void noticeDoesNotAcknowledgeTemporaryReset () + { + Items previous_catalog {frequency (14074000)}; + Items catalog {frequency (14074000), frequency (14090000)}; + Items saved {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + QVERIFY (notice.acknowledge_present_catalog (previous_catalog, saved)); + QCOMPARE (notice.visibility (catalog, saved), + FrequencySuggestions::NoticeState::Visibility::New); + + auto temporary = catalog; + QCOMPARE (notice.visibility (catalog, temporary), + FrequencySuggestions::NoticeState::Visibility::Hidden); + notice.cancel (); + QCOMPARE (notice.visibility (catalog, saved), + FrequencySuggestions::NoticeState::Visibility::New); + QCOMPARE (notice.seen_keys ().size (), 1); + } + + void noticeAcknowledgesOnlyCommittedSelections () + { + Items catalog {frequency (14074000), frequency (14090000), frequency (14091000)}; + Items working {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::Available); + QVERIFY (!notice.commit (catalog, working)); + notice.selected_additions (Items {frequency (14090000)}); + notice.cancel (); + QVERIFY (!notice.commit (catalog, working)); + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::Available); + + notice.selected_additions (Items {frequency (14090000)}); + Items partial {frequency (14074000), frequency (14090000)}; + QVERIFY (notice.commit (catalog, partial)); + QCOMPARE (notice.visibility (catalog, partial), + FrequencySuggestions::NoticeState::Visibility::Hidden); + QCOMPARE (notice.seen_keys ().size (), 3); + } + + void noticeDoesNotAcknowledgeRemovedSelection () + { + Items catalog {frequency (14074000), frequency (14090000)}; + Items saved {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + notice.selected_additions (Items {frequency (14090000)}); + QVERIFY (!notice.commit (catalog, saved)); + QCOMPARE (notice.visibility (catalog, saved), + FrequencySuggestions::NoticeState::Visibility::Available); + } + + void dismissPersistsIndependentlyOfSettingsCancel () + { + Items catalog {frequency (14074000), frequency (14090000)}; + Items working {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + notice.dismiss (catalog); + notice.cancel (); + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::Hidden); + catalog.append (frequency (14091000)); + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::New); + } + + void chooserAddsOnlyCheckedRows () + { + Bands bands; + Items catalog {frequency (14074000), frequency (14090000)}; + Items working {frequency (14074000, Modes::FT8, IARURegions::ALL, + "My row")}; + SuggestedFrequenciesDialog dialog {catalog, working, bands, {}}; + auto * list = dialog.findChild (QStringLiteral ("suggested_frequencies_list")); + QVERIFY (list); + auto checkboxes = list->findChildren (); + QCOMPARE (checkboxes.size (), 1); + auto * checkbox = checkboxes.first (); + QVERIFY (dialog.selected_items ().isEmpty ()); + + dialog.show (); + checkbox->setFocus (); + QTest::keyClick (checkbox, Qt::Key_Space); + QCOMPARE (dialog.selected_items ().size (), 1); + QCOMPARE (dialog.selected_items ().first ().frequency_, Radio::Frequency {14090000}); + QCOMPARE (working.size (), 1); + + auto * accessible = QAccessible::queryAccessibleInterface (checkbox); + QVERIFY (accessible); + QCOMPARE (accessible->role (), QAccessible::CheckBox); + auto * action = accessible->actionInterface (); + QVERIFY (action); + QVERIFY (action->actionNames ().contains (QAccessibleActionInterface::toggleAction ())); + action->doAction (QAccessibleActionInterface::toggleAction ()); + QVERIFY (dialog.selected_items ().isEmpty ()); + action->doAction (QAccessibleActionInterface::toggleAction ()); + QCOMPARE (dialog.selected_items ().size (), 1); + QStyleOptionButton option; + option.initFrom (checkbox); + auto const indicator = checkbox->style ()->subElementRect ( + QStyle::SE_CheckBoxIndicator, &option, checkbox); + QVERIFY (indicator.isValid ()); + QTest::mouseClick (checkbox, Qt::LeftButton, Qt::NoModifier, indicator.center ()); + QVERIFY (dialog.selected_items ().isEmpty ()); + QTest::mouseClick (checkbox, Qt::LeftButton, Qt::NoModifier, indicator.center ()); + QCOMPARE (dialog.selected_items ().size (), 1); + + QTest::keyClick (checkbox, Qt::Key_Tab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), QStringLiteral ("Cancel")); + QTest::keyClick (dialog.focusWidget (), Qt::Key_Tab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), QStringLiteral ("Add selected (1)")); + QTest::keyClick (dialog.focusWidget (), Qt::Key_Backtab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), QStringLiteral ("Cancel")); + checkbox->setFocus (); + QTest::keyClick (checkbox, Qt::Key_Backtab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), + QStringLiteral ("Show selected only")); + + auto * selected_only = dialog.focusWidget (); + QTest::mouseClick (selected_only, Qt::LeftButton); + checkboxes = list->findChildren (); + QCOMPARE (checkboxes.size (), 1); + checkboxes.first ()->setChecked (false); + QCoreApplication::processEvents (); + QVERIFY (!selected_only->property ("checked").toBool ()); + QVERIFY (dialog.selected_items ().isEmpty ()); + QCOMPARE (list->findChildren ().size (), 1); + } +}; + +QTEST_MAIN (TestFrequencySuggestions) +#include "test_frequency_suggestions.moc" diff --git a/tests/unit/common/test_log_window_deletion.cpp b/tests/unit/common/test_log_window_deletion.cpp new file mode 100644 index 00000000..27854a27 --- /dev/null +++ b/tests/unit/common/test_log_window_deletion.cpp @@ -0,0 +1,202 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Configuration.hpp" +#include "MetaDataRegistry.hpp" +#include "widgets/AbstractLogWindow.hpp" +#include "widgets/itoneAndicw.h" + +int volatile itone[MAX_NUM_SYMBOLS] {}; +float gran () { return 0; } + +namespace +{ + class LogWindow final : public AbstractLogWindow + { + public: + LogWindow (QSettings * settings, Configuration const * configuration) + : AbstractLogWindow {"log", settings, configuration} {} + + int changes {}; + + private: + void log_model_changed (int) override { ++changes; } + }; +} + +class TestLogWindowDeletion final : public QObject +{ + Q_OBJECT + + QTemporaryDir directory_; + QNetworkAccessManager network_; + std::unique_ptr settings_; + std::unique_ptr configuration_; + QSqlDatabase database_; + std::unique_ptr model_; + std::unique_ptr window_; + QTableView * view_ {}; + + void select_ids (std::initializer_list ids) + { + while (model_->canFetchMore (QModelIndex {})) model_->fetchMore (QModelIndex {}); + auto selection = view_->selectionModel (); + selection->clearSelection (); + for (int id : ids) + { + for (int row = 0; row < view_->model ()->rowCount (); ++row) + { + auto index = view_->model ()->index (row, 0); + if (index.data (Qt::EditRole).toInt () == id) + selection->select (index, QItemSelectionModel::Select | QItemSelectionModel::Rows); + } + } + QCOMPARE (selection->selectedRows ().size (), static_cast (ids.size ())); + } + + bool append_contact () + { + model_->setEditStrategy (QSqlTableModel::OnManualSubmit); + auto record = model_->record (); + record.setValue ("id", 601); + record.setValue ("call", "NEW"); + record.setValue ("band", "20m"); + record.setValue ("datetime", "000601"); + bool const result = model_->insertRecord (-1, record) && model_->submitAll (); + model_->setEditStrategy (QSqlTableModel::OnFieldChange); + return result; + } + + bool contains_id (int id) + { + QSqlQuery query {database_}; + query.prepare ("SELECT id FROM contacts WHERE id = ?"); + query.addBindValue (id); + return query.exec () && query.next (); + } + + template + void delete_selected (QMessageBox::StandardButton answer, DuringConfirmation during_confirmation) + { + QTimer::singleShot (0, this, [=] { + auto box = qobject_cast (QApplication::activeModalWidget ()); + Q_ASSERT (box); + during_confirmation (); + box->button (answer)->click (); + }); + view_->actions ().first ()->trigger (); + } + +private slots: + void initTestCase () + { + register_types (); + QStandardPaths::setTestModeEnabled (true); + QCoreApplication::setApplicationName ("test_log_window_deletion"); + QVERIFY (directory_.isValid ()); + settings_.reset (new QSettings {directory_.filePath ("settings.ini"), QSettings::IniFormat}); + configuration_.reset (new Configuration {&network_, QDir {directory_.path ()}, settings_.get (), nullptr}); + } + + void init () + { + database_ = QSqlDatabase::addDatabase ("QSQLITE", "log-window-deletion"); + database_.setDatabaseName (":memory:"); + QVERIFY (database_.open ()); + QSqlQuery query {database_}; + QVERIFY (query.exec ("CREATE TABLE contacts (id INTEGER PRIMARY KEY, call TEXT, band TEXT, datetime TEXT)")); + QVERIFY (database_.transaction ()); + query.prepare ("INSERT INTO contacts VALUES (?, ?, '20m', ?)"); + for (int id = 1; id <= 600; ++id) + { + query.bindValue (0, id); + query.bindValue (1, QString {"CALL%1"}.arg (id)); + query.bindValue (2, QString {"%1"}.arg (id, 6, 10, QChar {'0'})); + QVERIFY (query.exec ()); + } + QVERIFY (database_.commit ()); + model_.reset (new QSqlTableModel {nullptr, database_}); + model_->setTable ("contacts"); + model_->setEditStrategy (QSqlTableModel::OnFieldChange); + QVERIFY (model_->select ()); + QVERIFY (model_->rowCount () < 600); + window_.reset (new LogWindow {settings_.get (), configuration_.get ()}); + view_ = new QTableView {window_.get ()}; + view_->setModel (model_.get ()); + window_->set_log_view (view_); + } + + void cleanup () + { + // Finish fetching before draining auto-scroll callbacks, which can otherwise fetch more rows. + while (model_->canFetchMore (QModelIndex {})) model_->fetchMore (QModelIndex {}); + QCoreApplication::processEvents (); + window_.reset (); + model_.reset (); + database_.close (); + database_ = QSqlDatabase {}; + QSqlDatabase::removeDatabase ("log-window-deletion"); + } + + void confirmed_ids_survive_refresh () + { + select_ids ({550, 600}); + bool inserted = false; + int fetched_after_refresh = 600; + delete_selected (QMessageBox::Yes, [&] { + inserted = append_contact (); + fetched_after_refresh = model_->rowCount (); + }); + QVERIFY (inserted); + QVERIFY (fetched_after_refresh < 550); + QVERIFY (!contains_id (550)); + QVERIFY (!contains_id (600)); + QVERIFY (contains_id (601)); + QVERIFY (contains_id (42)); + QCOMPARE (window_->changes, 1); + } + + void cancel_after_refresh_preserves_contacts () + { + select_ids ({550, 600}); + bool inserted = false; + delete_selected (QMessageBox::No, [&] { inserted = append_contact (); }); + QVERIFY (inserted); + QVERIFY (contains_id (550)); + QVERIFY (contains_id (600)); + QVERIFY (contains_id (601)); + QCOMPARE (window_->changes, 0); + } + + void nonadjacent_ids_survive_sort_change () + { + select_ids ({12, 80, 599}); + delete_selected (QMessageBox::Yes, [&] { model_->sort (3, Qt::DescendingOrder); }); + QVERIFY (!contains_id (12)); + QVERIFY (!contains_id (80)); + QVERIFY (!contains_id (599)); + QVERIFY (contains_id (13)); + QVERIFY (contains_id (79)); + QVERIFY (contains_id (600)); + QCOMPARE (window_->changes, 1); + } +}; + +QTEST_MAIN (TestLogWindowDeletion) +#include "test_log_window_deletion.moc" diff --git a/tests/unit/common/test_qt_helpers.cpp b/tests/unit/common/test_qt_helpers.cpp index b56627c0..a0d4ce5b 100644 --- a/tests/unit/common/test_qt_helpers.cpp +++ b/tests/unit/common/test_qt_helpers.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include "qt_helpers.hpp" @@ -18,6 +19,38 @@ class TestQtHelpers public: private: + Q_SLOT void serial_port_order_data () + { + QTest::addColumn ("expected"); + QTest::newRow ("COM-zero") << QStringList {"COM0", "COM1", "COM2", "COM10"}; + QTest::newRow ("Unix-prefixes") << QStringList { + "ttyACM0", "ttyACM2", "ttyACM10", "ttyUSB0", "ttyUSB2", "ttyUSB10"}; + QTest::newRow ("macOS-names") << QStringList { + "cu.Bluetooth-Incoming-Port", "cu.usbserial-2", "cu.usbserial-10"}; + QTest::newRow ("leading-zeroes") << QStringList { + "COM0", "COM00", "COM0002", "COM02", "COM2", "COM10"}; + QTest::newRow ("large-suffixes") << QStringList { + "ttyUSB2", "ttyUSB10", "ttyUSB2147483648", "ttyUSB99999999999999999999", + "ttyUSB100000000000000000000"}; + QTest::newRow ("mixed-names") << QStringList { + "", "COM", "COM0", "COM2", "COM10", "COM2A", "COM2A2", "COM2A10", + "COMA", "com0", "ttyUSB", "ttyUSB0"}; + } + + Q_SLOT void serial_port_order () + { + QFETCH (QStringList, expected); + auto actual = expected; + std::reverse (actual.begin (), actual.end ()); + std::sort (actual.begin (), actual.end (), serial_port_name_less); + QCOMPARE (actual, expected); + + // Check every pair so mixed prefixes and numeric ties have a consistent order. + for (int i = 0; i < expected.size (); ++i) + for (int j = 0; j < expected.size (); ++j) + QCOMPARE (serial_port_name_less (expected.at (i), expected.at (j)), i < j); + } + Q_SLOT void round_15s_date_time_up () { QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 500}}; diff --git a/tests/unit/common/test_radio_callsign.cpp b/tests/unit/common/test_radio_callsign.cpp new file mode 100644 index 00000000..c19cfc1e --- /dev/null +++ b/tests/unit/common/test_radio_callsign.cpp @@ -0,0 +1,128 @@ +#include + +#include "Radio.hpp" + +class TestRadioCallsign final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void identity_data (); + void identity (); + void classification_data (); + void classification (); + void standard_data (); + void standard (); + void decodedGrid_data (); + void decodedGrid (); +}; + +void TestRadioCallsign::identity_data () +{ + QTest::addColumn ("callsign"); + QTest::addColumn ("base"); + QTest::addColumn ("prefix"); + + QTest::newRow ("ordinary") << QString {"K1ABC"} << QString {"K1ABC"} << QString {"K1ABC"}; + QTest::newRow ("portable prefix") << QString {"EA8/K1ABC"} << QString {"K1ABC"} << QString {"EA8"}; + QTest::newRow ("portable suffix") << QString {"K1ABC/EA8"} << QString {"K1ABC"} << QString {"EA8"}; + QTest::newRow ("equal length") << QString {"EA8/K1A"} << QString {"K1A"} << QString {"EA8"}; +} + +void TestRadioCallsign::identity () +{ + QFETCH (QString, callsign); + QFETCH (QString, base); + QFETCH (QString, prefix); + + for (auto const& suffix : {QString {}, QString {"/P"}, QString {"/QRP"}, QString {"/P/QRP"}}) + { + auto const input = callsign + suffix; + QCOMPARE (Radio::base_callsign (input), base); + QCOMPARE (Radio::effective_prefix (input), prefix); + QCOMPARE (Radio::base_callsign (input.toLower ()), base); + QCOMPARE (Radio::effective_prefix (input.toLower ()), prefix); + } +} + +void TestRadioCallsign::classification_data () +{ + QTest::addColumn ("callsign"); + QTest::addColumn ("valid"); + QTest::addColumn ("compound"); + QTest::addColumn ("nonstandard"); + + QTest::newRow ("standard") << QString {"K1ABC"} << true << false << false; + QTest::newRow ("compound") << QString {"K1ABC/P"} << true << true << true; + QTest::newRow ("long prefix") << QString {"3DA0XYZ"} << true << false << true; + QTest::newRow ("invalid alphabet") << QString {"---"} << false << false << false; + QTest::newRow ("empty") << QString {} << false << false << false; +} + +void TestRadioCallsign::classification () +{ + QFETCH (QString, callsign); + QFETCH (bool, valid); + QFETCH (bool, compound); + QFETCH (bool, nonstandard); + + QCOMPARE (Radio::is_callsign (callsign), valid); + QCOMPARE (Radio::is_compound_callsign (callsign), compound); + QCOMPARE (Radio::is_77bit_nonstandard_callsign (callsign), nonstandard); +} + +void TestRadioCallsign::standard_data () +{ + QTest::addColumn ("callsign"); + QTest::addColumn ("standard"); + QTest::newRow ("ordinary") << QString {"K1ABC"} << true; + QTest::newRow ("case and whitespace") << QString {" k1abc "} << true; + QTest::newRow ("portable") << QString {"K1ABC/P"} << true; + QTest::newRow ("rover") << QString {"K1ABC/r"} << true; + QTest::newRow ("digit prefix") << QString {"3D2ABC"} << true; + QTest::newRow ("letter digit prefix") << QString {"A12ABC"} << true; + QTest::newRow ("no suffix letters") << QString {"K1"} << true; + QTest::newRow ("no prefix") << QString {"1ABC"} << true; + QTest::newRow ("single digit") << QString {"1"} << true; + QTest::newRow ("compound prefix") << QString {"EA8/K1ABC"} << false; + QTest::newRow ("unsupported suffix") << QString {"K1ABC/QRP"} << false; + QTest::newRow ("long prefix") << QString {"3DA0XYZ"} << false; + QTest::newRow ("long suffix") << QString {"K1ABCD"} << false; + QTest::newRow ("internal whitespace") << QString {"K1 ABC"} << false; + QTest::newRow ("empty") << QString {} << false; +} + +void TestRadioCallsign::standard () +{ + QFETCH (QString, callsign); + QFETCH (bool, standard); + QCOMPARE (Radio::is_standard_callsign (callsign), standard); +} + +void TestRadioCallsign::decodedGrid_data () +{ + QTest::addColumn ("grid"); + QTest::addColumn ("valid"); + QTest::newRow ("four characters") << QString {"FN42"} << true; + QTest::newRow ("six characters mixed case") << QString {"fn42aB"} << true; + QTest::newRow ("range limits") << QString {"RR99XX"} << true; + QTest::newRow ("acknowledgement") << QString {"RR73"} << false; + QTest::newRow ("acknowledgement case") << QString {"rR73"} << false; + QTest::newRow ("acknowledgement prefix") << QString {"RR73AA"} << false; + QTest::newRow ("field range") << QString {"SS42"} << false; + QTest::newRow ("subsquare range") << QString {"FN42YY"} << false; + QTest::newRow ("leading space") << QString {" FN42"} << false; + QTest::newRow ("trailing space") << QString {"FN42 "} << false; + QTest::newRow ("empty") << QString {} << false; +} + +void TestRadioCallsign::decodedGrid () +{ + QFETCH (QString, grid); + QFETCH (bool, valid); + QCOMPARE (grid.contains (QRegularExpression {Radio::decoded_grid_pattern ()}), valid); +} + +QTEST_GUILESS_MAIN (TestRadioCallsign) + +#include "test_radio_callsign.moc" diff --git a/tests/unit/decoder_engine/CMakeLists.txt b/tests/unit/decoder_engine/CMakeLists.txt new file mode 100644 index 00000000..c2546109 --- /dev/null +++ b/tests/unit/decoder_engine/CMakeLists.txt @@ -0,0 +1,222 @@ +add_library (test_decoder_engine_signal STATIC decoder_engine_signal.f90 jt9_engine_signal.f90) +set_target_properties (test_decoder_engine_signal PROPERTIES + Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/signal-modules) +target_include_directories (test_decoder_engine_signal PRIVATE ${CMAKE_SOURCE_DIR}/lib) +wsjt_link_common_fortran (test_decoder_engine_signal) + +add_executable (test_decoder_engine test_decoder_engine.c) +set_target_properties (test_decoder_engine PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decoder_engine PRIVATE test_decoder_engine_signal) +add_test (NAME test_decoder_engine COMMAND test_decoder_engine) +set_tests_properties (test_decoder_engine PROPERTIES TIMEOUT 90) + +add_executable (test_decoder_engine_ft4 test_decoder_engine_ft4.c) +set_target_properties (test_decoder_engine_ft4 PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine_ft4 PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decoder_engine_ft4 PRIVATE test_decoder_engine_signal) +add_test (NAME test_decoder_engine_ft4 COMMAND test_decoder_engine_ft4) +set_tests_properties (test_decoder_engine_ft4 PROPERTIES TIMEOUT 90) + +find_package (Threads REQUIRED) +add_executable (test_decoder_engine_jt9 test_decoder_engine_jt9.c) +set_target_properties (test_decoder_engine_jt9 PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine_jt9 PRIVATE ${CMAKE_SOURCE_DIR} ${FFTW3_INCLUDE_DIRS}) +target_link_libraries (test_decoder_engine_jt9 PRIVATE test_decoder_engine_signal Threads::Threads) +add_test (NAME test_decoder_engine_jt9 COMMAND test_decoder_engine_jt9 --smoke) +set_tests_properties (test_decoder_engine_jt9 PROPERTIES TIMEOUT 90) +if (TARGET wsjt_fort) + add_test (NAME test_decoder_engine_jt9_small_stack COMMAND test_decoder_engine_jt9 --small-stack) + set_tests_properties (test_decoder_engine_jt9_small_stack PROPERTIES TIMEOUT 90) +else () + # The common target also uses wsjt_fort_omp; retain a one-thread smoke. + set_tests_properties (test_decoder_engine_jt9 PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +endif () + +add_library (test_decoder_engine_jt65_signal STATIC + ../jt65/jt65_test_fixture.f90 jt65_engine_signal.f90) +set_target_properties (test_decoder_engine_jt65_signal PROPERTIES + Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt65-signal-modules) +target_link_libraries (test_decoder_engine_jt65_signal PUBLIC jt65_test_vectors) +wsjt_link_common_fortran (test_decoder_engine_jt65_signal) + +add_executable (test_decoder_engine_jt65 test_decoder_engine_jt65.c) +set_target_properties (test_decoder_engine_jt65 PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine_jt65 PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decoder_engine_jt65 PRIVATE test_decoder_engine_jt65_signal Threads::Threads) +# Full behavioral coverage belongs to one constrained-stack test per archive. +add_test (NAME test_decoder_engine_jt65 COMMAND test_decoder_engine_jt65 --smoke) +set_tests_properties (test_decoder_engine_jt65 PROPERTIES TIMEOUT 360) +if (TARGET wsjt_fort) + add_test (NAME test_decoder_engine_jt65_small_stack COMMAND test_decoder_engine_jt65 --small-stack) + set_tests_properties (test_decoder_engine_jt65_small_stack PROPERTIES TIMEOUT 360) +else () + # The common target also uses wsjt_fort_omp; retain a one-thread smoke. + set_tests_properties (test_decoder_engine_jt65 PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +endif () +add_test (NAME prepare_jt65_engine_wav COMMAND test_decoder_engine_jt65 + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/jt65-engine.wav) +set_tests_properties (prepare_jt65_engine_wav PROPERTIES FIXTURES_SETUP jt65_engine_wav TIMEOUT 15) + +add_executable (test_decoder_engine_jt65_host test_decoder_engine_jt65_host.f90) +target_link_libraries (test_decoder_engine_jt65_host PRIVATE test_decoder_engine_jt65_signal) +wsjt_link_common_fortran (test_decoder_engine_jt65_host) +file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt65-host) +add_test (NAME test_decoder_engine_jt65_host COMMAND test_decoder_engine_jt65_host) +set_tests_properties (test_decoder_engine_jt65_host PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt65-host TIMEOUT 60) + +add_library (test_decoder_engine_q65_signal STATIC q65_engine_signal.f90) +wsjt_link_common_fortran (test_decoder_engine_q65_signal) +add_executable (test_decoder_engine_q65 test_decoder_engine_q65.c) +set_target_properties (test_decoder_engine_q65 PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine_q65 PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decoder_engine_q65 PRIVATE test_decoder_engine_q65_signal Threads::Threads) +add_test (NAME test_decoder_engine_q65 COMMAND test_decoder_engine_q65 --smoke) +set_tests_properties (test_decoder_engine_q65 PROPERTIES TIMEOUT 180) +if (TARGET wsjt_fort) + add_test (NAME test_decoder_engine_q65_small_stack COMMAND test_decoder_engine_q65 --small-stack) + set_tests_properties (test_decoder_engine_q65_small_stack PROPERTIES TIMEOUT 180) +else () + set_tests_properties (test_decoder_engine_q65 PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +endif () +add_test (NAME prepare_q65_engine_wav COMMAND test_decoder_engine_q65 + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/q65-engine.wav) +set_tests_properties (prepare_q65_engine_wav PROPERTIES FIXTURES_SETUP q65_engine_wav TIMEOUT 15) +add_test (NAME prepare_q65_engine_60s_wav COMMAND test_decoder_engine_q65 + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/261003_001500.wav 60) +set_tests_properties (prepare_q65_engine_60s_wav PROPERTIES FIXTURES_SETUP q65_engine_60s_wav TIMEOUT 15) + +add_executable (test_decoder_engine_q65_host test_decoder_engine_q65_host.f90) +set_target_properties (test_decoder_engine_q65_host PROPERTIES LINKER_LANGUAGE CXX) +target_link_libraries (test_decoder_engine_q65_host PRIVATE test_decoder_engine_q65_signal) +wsjt_link_common_fortran (test_decoder_engine_q65_host) +file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/q65-host) +add_test (NAME test_decoder_engine_q65_host COMMAND test_decoder_engine_q65_host) +set_tests_properties (test_decoder_engine_q65_host PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/q65-host TIMEOUT 360) +file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/q65-host-contest) +add_test (NAME test_decoder_engine_q65_host_contest COMMAND test_decoder_engine_q65_host --contest) +set_tests_properties (test_decoder_engine_q65_host_contest PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/q65-host-contest TIMEOUT 90) + +if (TARGET wsjt_fort_omp) + add_library (test_decoder_engine_signal_omp STATIC decoder_engine_signal.f90 jt9_engine_signal.f90) + set_target_properties (test_decoder_engine_signal_omp PROPERTIES + Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/signal-omp-modules) + target_include_directories (test_decoder_engine_signal_omp PRIVATE + ${WSJT_FORTRAN_OPENMP_MODULE_DIR} ${CMAKE_SOURCE_DIR}/lib) + target_link_libraries (test_decoder_engine_signal_omp PUBLIC + wsjt_fort_omp wsjt_fortran_openmp) + + add_executable (test_decoder_engine_omp test_decoder_engine.c) + set_target_properties (test_decoder_engine_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_omp PRIVATE ${CMAKE_SOURCE_DIR}) + target_link_libraries (test_decoder_engine_omp PRIVATE test_decoder_engine_signal_omp) + add_test (NAME test_decoder_engine_omp COMMAND test_decoder_engine_omp) + set_tests_properties (test_decoder_engine_omp PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2" + PROCESSORS 2 + TIMEOUT 90) + + add_executable (test_decoder_engine_ft4_omp test_decoder_engine_ft4.c) + set_target_properties (test_decoder_engine_ft4_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_ft4_omp PRIVATE ${CMAKE_SOURCE_DIR}) + target_link_libraries (test_decoder_engine_ft4_omp PRIVATE test_decoder_engine_signal_omp) + add_test (NAME test_decoder_engine_ft4_omp COMMAND test_decoder_engine_ft4_omp) + set_tests_properties (test_decoder_engine_ft4_omp PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2" + PROCESSORS 2 + TIMEOUT 90) + + add_executable (test_decoder_engine_jt9_omp test_decoder_engine_jt9.c) + set_target_properties (test_decoder_engine_jt9_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_jt9_omp PRIVATE ${CMAKE_SOURCE_DIR} ${FFTW3_INCLUDE_DIRS}) + target_link_libraries (test_decoder_engine_jt9_omp PRIVATE test_decoder_engine_signal_omp Threads::Threads) + add_test (NAME test_decoder_engine_jt9_omp COMMAND test_decoder_engine_jt9_omp --smoke) + add_test (NAME test_decoder_engine_jt9_omp_small_stack COMMAND test_decoder_engine_jt9_omp --small-stack) + set_tests_properties (test_decoder_engine_jt9_omp test_decoder_engine_jt9_omp_small_stack PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2;OMP_STACKSIZE=1M" + PROCESSORS 2 + TIMEOUT 90) + + add_library (test_decoder_engine_jt65_signal_omp STATIC + ../jt65/jt65_test_fixture.f90 jt65_engine_signal.f90) + set_target_properties (test_decoder_engine_jt65_signal_omp PROPERTIES + Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt65-signal-omp-modules) + target_link_libraries (test_decoder_engine_jt65_signal_omp PUBLIC + jt65_test_vectors wsjt_fort_omp wsjt_fortran_openmp) + + add_executable (test_decoder_engine_jt65_omp test_decoder_engine_jt65.c) + set_target_properties (test_decoder_engine_jt65_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_jt65_omp PRIVATE ${CMAKE_SOURCE_DIR}) + target_link_libraries (test_decoder_engine_jt65_omp PRIVATE test_decoder_engine_jt65_signal_omp Threads::Threads) + add_test (NAME test_decoder_engine_jt65_omp COMMAND test_decoder_engine_jt65_omp --smoke) + add_test (NAME test_decoder_engine_jt65_omp_small_stack COMMAND test_decoder_engine_jt65_omp --small-stack) + set_tests_properties (test_decoder_engine_jt65_omp test_decoder_engine_jt65_omp_small_stack PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2;OMP_STACKSIZE=1M" + PROCESSORS 2 + TIMEOUT 360) + + add_library (test_decoder_engine_q65_signal_omp STATIC q65_engine_signal.f90) + target_link_libraries (test_decoder_engine_q65_signal_omp PUBLIC wsjt_fort_omp wsjt_fortran_openmp) + add_executable (test_decoder_engine_q65_omp test_decoder_engine_q65.c) + set_target_properties (test_decoder_engine_q65_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_q65_omp PRIVATE ${CMAKE_SOURCE_DIR}) + target_link_libraries (test_decoder_engine_q65_omp PRIVATE test_decoder_engine_q65_signal_omp Threads::Threads) + add_test (NAME test_decoder_engine_q65_omp COMMAND test_decoder_engine_q65_omp --smoke) + add_test (NAME test_decoder_engine_q65_omp_small_stack COMMAND test_decoder_engine_q65_omp --small-stack) + set_tests_properties (test_decoder_engine_q65_omp test_decoder_engine_q65_omp_small_stack PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2;OMP_STACKSIZE=1M" + PROCESSORS 2 + TIMEOUT 180) +endif () + +add_library (test_decoder_engine_fst4_signal STATIC fst4_engine_signal.f90) +set_target_properties (test_decoder_engine_fst4_signal PROPERTIES + Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/fst4-signal-modules) +wsjt_link_common_fortran (test_decoder_engine_fst4_signal) +add_executable (test_decoder_engine_fst4 test_decoder_engine_fst4.c) +set_target_properties (test_decoder_engine_fst4 PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine_fst4 PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decoder_engine_fst4 PRIVATE test_decoder_engine_fst4_signal Threads::Threads) +add_test (NAME test_decoder_engine_fst4 COMMAND test_decoder_engine_fst4 --small-stack) +set_tests_properties (test_decoder_engine_fst4 PROPERTIES TIMEOUT 360 + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +option (WSJT_ENABLE_FST4_LONG_TESTS "Run FST4 engine long-period regressions." OFF) +if (WSJT_ENABLE_FST4_LONG_TESTS) + add_test (NAME test_decoder_engine_fst4_long_periods COMMAND test_decoder_engine_fst4 --long-periods) + set_tests_properties (test_decoder_engine_fst4_long_periods PROPERTIES + LABELS "decoder;fst4;long-period" TIMEOUT 360 + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +endif () +add_test (NAME prepare_fst4_engine_wav COMMAND test_decoder_engine_fst4 + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/fst4-engine.wav 240 15) +set_tests_properties (prepare_fst4_engine_wav PROPERTIES FIXTURES_SETUP fst4_engine_wav TIMEOUT 30) +add_test (NAME prepare_fst4w_engine_wav COMMAND test_decoder_engine_fst4 + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/fst4w-engine.wav 241 120) +set_tests_properties (prepare_fst4w_engine_wav PROPERTIES FIXTURES_SETUP fst4w_engine_wav TIMEOUT 30) +add_executable (test_decoder_engine_fst4_host test_decoder_engine_fst4_host.f90) +set_target_properties (test_decoder_engine_fst4_host PROPERTIES LINKER_LANGUAGE CXX) +target_link_libraries (test_decoder_engine_fst4_host PRIVATE test_decoder_engine_fst4_signal) +wsjt_link_common_fortran (test_decoder_engine_fst4_host) +file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/fst4-host) +add_test (NAME test_decoder_engine_fst4_host COMMAND test_decoder_engine_fst4_host) +set_tests_properties (test_decoder_engine_fst4_host PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/fst4-host TIMEOUT 360) +if (TARGET wsjt_fort_omp) + add_library (test_decoder_engine_fst4_signal_omp STATIC fst4_engine_signal.f90) + set_target_properties (test_decoder_engine_fst4_signal_omp PROPERTIES + Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/fst4-signal-omp-modules) + target_link_libraries (test_decoder_engine_fst4_signal_omp PUBLIC wsjt_fort_omp wsjt_fortran_openmp) + add_executable (test_decoder_engine_fst4_omp test_decoder_engine_fst4.c) + set_target_properties (test_decoder_engine_fst4_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_fst4_omp PRIVATE ${CMAKE_SOURCE_DIR}) + target_link_libraries (test_decoder_engine_fst4_omp PRIVATE test_decoder_engine_fst4_signal_omp Threads::Threads) + add_test (NAME test_decoder_engine_fst4_omp COMMAND test_decoder_engine_fst4_omp --small-stack) + set_tests_properties (test_decoder_engine_fst4_omp PROPERTIES TIMEOUT 360 PROCESSORS 2 + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2;OMP_STACKSIZE=1M") +endif () diff --git a/tests/unit/decoder_engine/decoder_engine_signal.f90 b/tests/unit/decoder_engine/decoder_engine_signal.f90 new file mode 100644 index 00000000..ffaba33d --- /dev/null +++ b/tests/unit/decoder_engine/decoder_engine_signal.f90 @@ -0,0 +1,190 @@ +subroutine decoder_engine_test_signal(samples,payload,expected_tones,start_sample) bind(C) + use iso_c_binding, only: c_int,c_int8_t,c_int16_t,c_int64_t + use packjt77, only: pack77_state + use ft8_codec_context, only: genft8_for_state + implicit none + integer, parameter :: symbol_samples=1920,wave_samples=79*symbol_samples + integer(c_int16_t), intent(out) :: samples(180000) + integer(c_int8_t), intent(out) :: payload(77) + integer(c_int8_t), intent(out) :: expected_tones(79) + integer(c_int), value :: start_sample + type(pack77_state) :: knowledge + real :: wave(wave_samples) + complex :: complex_wave(1) + integer :: tones(79),i3,n3,i,j + integer(c_int64_t) :: random_state + character(len=37) :: message,sent + + message='CQ K1JT FN20' + i3=-1 + n3=-1 + call genft8_for_state(knowledge,message,i3,n3,sent,payload,tones) + expected_tones=int(tones,c_int8_t) + if(sent.ne.message) error stop 'engine test waveform message did not encode' + call gen_ft8wave(tones,79,symbol_samples,2.0,12000.0,1500.0, & + complex_wave,wave,0,wave_samples) + random_state=1234567_c_int64_t + do i=1,size(samples) + random_state=mod(16807_c_int64_t*random_state,2147483647_c_int64_t) + samples(i)=int(mod(random_state,21_c_int64_t)-10_c_int64_t,c_int16_t) + enddo + do i=1,wave_samples + j=start_sample+i + if(j>=1.and.j<=size(samples)) samples(j)=samples(j)+int(1500.0*wave(i),c_int16_t) + enddo +end subroutine decoder_engine_test_signal + +subroutine decoder_engine_test_records(records,record_size) bind(C) + use iso_c_binding, only: c_size_t,c_sizeof + use decoder_engine_types + implicit none + type(engine_observation), intent(out) :: records(2) + integer(c_size_t), intent(out) :: record_size + + record_size=c_sizeof(records(1)) + records=engine_observation() + records(1)%mode=engine_mode_ft4 + records(1)%dt_seconds=0.25 + records(1)%ft4%payload77(77)=1 + records(1)%ft4%tones(103)=3 + records(1)%ft4%payload_origin=engine_payload_decoded + records(1)%ft4%has_tones=1 + records(1)%ft4%has_waveform_start=1 + records(1)%ft4%waveform_start_seconds=-0.125 + records(2)%variant=2 + records(2)%superfox%symbols(50)=127 + records(2)%superfox%kind=sf_kind_verification + records(2)%superfox%child_index=4 +end subroutine decoder_engine_test_records + +subroutine decoder_engine_test_message(mode,text,samples,payload,expected_tones,start_sample) bind(C) + use iso_c_binding, only: c_int,c_char,c_int8_t,c_int16_t,c_int64_t + use packjt77, only: pack77_state + use ft4_codec, only: genft4_for_state + use ft8_codec_context, only: genft8_for_state + implicit none + integer(c_int), value :: mode,start_sample + character(c_char), intent(in) :: text(37) + integer(c_int16_t), intent(out) :: samples(180000) + integer(c_int8_t), intent(out) :: payload(77),expected_tones(103) + type(pack77_state) :: knowledge + real :: wave(151680) + complex :: complex_wave(1) + integer :: tones(103),i3,n3,i,j,nwave + integer(c_int64_t) :: random_state + character(len=37) :: message,sent + + message=transfer(text,message) + if(mode==5) then + call genft4_for_state(knowledge,message,0,sent,payload,tones) + nwave=60480 + call gen_ft4wave(tones,103,576,12000.0,1500.0,complex_wave,wave,0,nwave) + else + tones=0 + i3=-1 + n3=-1 + call genft8_for_state(knowledge,message,i3,n3,sent,payload,tones(:79)) + nwave=151680 + call gen_ft8wave(tones,79,1920,2.0,12000.0,1500.0,complex_wave,wave,0,nwave) + endif + if(sent/=message) error stop 'mixed-mode waveform message did not encode' + expected_tones=int(tones,c_int8_t) + random_state=1234567_c_int64_t + do i=1,size(samples) + random_state=mod(16807_c_int64_t*random_state,2147483647_c_int64_t) + samples(i)=int(mod(random_state,21_c_int64_t)-10_c_int64_t,c_int16_t) + enddo + do i=1,nwave + j=start_sample+i + if(j>=1.and.j<=size(samples)) samples(j)=samples(j)+int(1500.0*wave(i),c_int16_t) + enddo +end subroutine + +subroutine decoder_engine_test_residual(samples) bind(C) + use iso_c_binding, only: c_float + use ft8_mod1, only: dd8 + implicit none + real(c_float), intent(out) :: samples(180000) + samples=dd8 +end subroutine + +subroutine decoder_engine_test_host_windows() bind(C) + use iso_c_binding, only: c_short,c_int8_t,c_int64_t,c_sizeof + use decoder_engine, only: engine_host_decode + use ft8_engine_kernel, only: params_block + use ft8_mod1, only: dd8 + use decode_completion_module, only: decode_completion_result + implicit none + type(params_block) :: params + type(decode_completion_result) :: completion + integer(c_int8_t) :: zeros(c_sizeof(params)) + integer(c_short), target :: samples(180000) + integer :: extent,case_no + + zeros=0 + params=transfer(zeros,params) + params%nmode=8 + params%ntr=15 + params%nutc=120000 + params%nzhsym=49 + params%newdat=.true. + params%lmultift8=.true. + params%nmt=1 + params%nfqso=3000 + params%nfa=1000 + params%nfb=2000 + params%nagainfil=.true. + params%mycall=' ' + params%mybcall=' ' + params%hiscall=' ' + params%hisbcall=' ' + params%mygrid=' ' + params%hisgrid=' ' + samples=2 + do case_no=1,2 + extent=180000 + if(case_no==2) extent=100000 + call engine_host_decode(samples,params,12000,completion,0, & + int(900+case_no,c_int64_t),int(900+case_no,c_int64_t),1,extent) + extent=min(extent,49*3456) + if(any(dd8(:extent)/=2.0)) error stop 'host discarded available MTD audio' + if(any(dd8(extent+1:)/=0.0)) error stop 'host retained audio outside the MTD window' + if(.not.completion%available) error stop 'host window probe did not complete' + enddo +end subroutine + +subroutine decoder_engine_test_legacy_isolation() bind(C) + use packjt77, only: nzhash,recent_calls + implicit none + if(nzhash/=0.or.any(recent_calls/='')) error stop 'engine mutated legacy codec knowledge' +end subroutine + +subroutine decoder_engine_test_gui_codec() bind(C) + use packjt77, only: pack77_state,pack77_for_state,unpack77_for_state,unpack77 + use decoder_codec_context, only: get_decoder_codec_state + use ft4_codec, only: ft4_tones_from_77bits,ft4_scramble + implicit none + type(pack77_state), pointer :: state + type(pack77_state) :: encoder + character(len=37) :: message,sent,resolved + character(len=77) :: bits + integer(kind=1) :: payload(77),canonical(77) + integer :: tones(103),expected(103),i3,n3 + logical :: ok + + message='CQ K1JT FN20' + call genft4(message,0,sent,payload,tones) + canonical=payload + call ft4_scramble(canonical) + call ft4_tones_from_77bits(canonical,expected) + if(any(expected/=tones)) error stop 'legacy FT4 encoder bit convention changed' + state=>get_decoder_codec_state() + message='PJ2/W1AW RR73' + i3=-1 + n3=-1 + call pack77_for_state(encoder,message,i3,n3,bits) + call unpack77_for_state(state,bits,1,resolved,ok) + if(.not.ok.or.resolved/=message) error stop 'GUI codec did not retain FT4 knowledge' + call unpack77(bits,1,resolved,ok) + if(.not.ok.or.resolved/='PJ2/W1AW <...> RR73') error stop 'GUI codec leaked into legacy store' +end subroutine diff --git a/tests/unit/decoder_engine/fst4_engine_signal.f90 b/tests/unit/decoder_engine/fst4_engine_signal.f90 new file mode 100644 index 00000000..bc5d3b73 --- /dev/null +++ b/tests/unit/decoder_engine/fst4_engine_signal.f90 @@ -0,0 +1,286 @@ +module fst4_engine_workspace_test + use iso_fortran_env, only: error_unit + use fst4_decode, only: fst4_decoder + use decoder_engine_types, only: fst4_result + implicit none + private + public :: workspace_test_decoder,require,observe + + type, extends(fst4_decoder) :: workspace_test_decoder + integer :: observations=0 + logical :: expected_doppler=.false. + end type + +contains + subroutine require(condition,description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if(condition) return + write(error_unit,'(a)') 'FST4 workspace: '//description + error stop 1 + end subroutine + + subroutine observe(this,nutc,sync,nsnr,dt,freq,decoded,nap,qual,ntrperiod,fmid,w50,result) + class(fst4_decoder), intent(inout) :: this + integer, intent(in) :: nutc,nsnr,nap,ntrperiod + real, intent(in) :: sync,dt,freq,qual,fmid,w50 + character(len=37), intent(in) :: decoded + type(fst4_result), optional, intent(in) :: result + select type(this) + type is(workspace_test_decoder) + call require(decoded=='K1ABC W9XYZ FN42','correct message after workspace reacquisition') + call require(present(result),'typed result after workspace reacquisition') + call require(result%has_doppler==merge(1,0,this%expected_doppler),'requested Doppler analysis') + this%observations=this%observations+1 + class default + error stop 'invalid FST4 workspace test decoder' + end select + end subroutine +end module fst4_engine_workspace_test + +subroutine decoder_engine_test_fst4_signal(mode,period,frequency,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t,c_float + implicit none + integer(c_int), value :: mode,period + real(c_float), value :: frequency + integer(c_int16_t), intent(out) :: samples(period*12000) + call fst4_engine_make_signal(mode,period,frequency,300.0,0,-1,samples) +end subroutine + +subroutine decoder_engine_test_fst4_weak_signal(period,amplitude,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t,c_float + implicit none + integer(c_int), value :: period + real(c_float), value :: amplitude + integer(c_int16_t), intent(out) :: samples(period*12000) + call fst4_engine_make_signal(241,period,1500.0,amplitude,0,-1,samples) +end subroutine + +subroutine decoder_engine_test_fst4_ap_signal(samples) bind(C) + use iso_c_binding, only: c_int16_t,c_float + implicit none + integer(c_int16_t), intent(out) :: samples(15*12000) + call fst4_engine_make_signal(240,15,1500.0,300.0,1,-1,samples) +end subroutine + +subroutine decoder_engine_test_fst4_rr73_signal(samples) bind(C) + use iso_c_binding, only: c_int16_t + implicit none + integer(c_int16_t), intent(out) :: samples(15*12000) + call fst4_engine_make_signal(240,15,1500.0,300.0,2,-1,samples) +end subroutine + +subroutine decoder_engine_test_fst4_hash_signals(count,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t + implicit none + integer(c_int), value :: count + integer(c_int16_t), intent(out) :: samples(15*12000) + integer(c_int16_t), allocatable :: second(:) + if(count<1.or.count>2) error stop 'invalid FST4 hash fixture count' + call fst4_engine_make_signal(241,15,merge(1500.0,1450.0,count==1),300.0,0,1234567,samples) + if(count==2) then + allocate(second(size(samples))) + call fst4_engine_make_signal(241,15,1550.0,300.0,0,2345678,second) + samples=int(max(-32768,min(32767,int(samples)+int(second))),c_int16_t) + endif +end subroutine + +subroutine fst4_engine_make_signal(mode,period,frequency,amplitude,payload_damage,hash22,samples) + use iso_c_binding, only: c_int,c_int16_t,c_float + use iso_fortran_env, only: int64,real64 + use packjt77, only: pack77_state,pack77_for_state,pack77_options,PACK77_STATUS_ENCODED + use packjt77_schema, only: encode_pack77_wspr_type3 + use packjt77_grammar, only: pack77_grid6_wspr_index + implicit none + integer(c_int), intent(in) :: mode,period,hash22,payload_damage + real(c_float), intent(in) :: frequency,amplitude + integer(c_int16_t), intent(out) :: samples(period*12000) + logical :: encoded + type(pack77_state), target :: knowledge + real, allocatable :: wave(:) + complex :: unused_complex(1) + integer :: tones(160),nsps,start,i,j,i3,n3,status,iwspr,ncrc,length + integer(c_int16_t) :: sample + integer(kind=1) :: bits(101) + integer, parameter :: scramble(77)=[0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, & + 1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,1, & + 0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1] + integer(int64) :: rng + real(real64) :: noise,u1,u2,value + real(real64), parameter :: twopi=6.283185307179586476925286766559_real64 + character(len=37) :: message + character(len=77) :: packed + character(len=24) :: crc + + select case(period) + case(15) + nsps=720 + case(30) + nsps=1680 + case(60) + nsps=3888 + case(120) + nsps=8200 + case(300) + nsps=21504 + case(900) + nsps=66560 + case(1800) + nsps=134400 + case default + error stop 'invalid FST4 fixture period' + end select + iwspr=merge(1,0,mode==241) + message='K1ABC W9XYZ FN42' + if(payload_damage==2) message='K1ABC W9XYZ RR73' + if(iwspr==1) message='K1ABC FN42 37' + if(hash22>=0) then + call encode_pack77_wspr_type3(hash22,pack77_grid6_wspr_index('FN42AB'),packed,encoded) + if(.not.encoded) error stop 'FST4 hash fixture pack failed' + else + call pack77_for_state(knowledge,message,i3,n3,packed, & + pack77_options(prefer_wspr_50bit=iwspr==1),status) + if(status/=PACK77_STATUS_ENCODED) error stop 'FST4 fixture pack failed' + endif + bits=0 + length=77 + if(iwspr==1) length=50 + read(packed,'(77i1)') bits(1:77) + if(iwspr==0) bits(1:77)=mod(bits(1:77)+scramble,2) + bits(length+1:)=0 + call get_crc24(bits,length+24,ncrc) + write(crc,'(b24.24)') ncrc + read(crc,'(24i1)') bits(length+1:length+24) + call get_fst4_tones_from_bits(bits,tones,iwspr) + if(payload_damage==1) tones(9:37)=mod(tones(9:37)+2,4) + if(payload_damage==2) then + ! Damage beyond the callsign bits makes recovery depend on the full RR73 AP hypothesis. + tones(9:38)=mod(tones(9:38)+2,4) + tones(47:70)=mod(tones(47:70)+2,4) + endif + allocate(wave(period*12000)) + call gen_fst4wave(tones,160,nsps,size(wave),12000.0,1, & + frequency+1.5*12000.0/nsps,0,unused_complex,wave) + start=12000 + if(period==15) start=6000 + rng=104729_int64 + do i=1,size(samples) + rng=modulo(16807_int64*rng,2147483647_int64) + u1=max(real(rng,real64)/2147483647.0_real64,tiny(1.0_real64)) + rng=modulo(16807_int64*rng,2147483647_int64) + u2=real(rng,real64)/2147483647.0_real64 + noise=100*sqrt(-2*log(u1))*cos(twopi*u2) + value=noise + j=i-start + if(j>0.and.j<=160*nsps) value=value+amplitude*wave(j) + sample=int(nint(max(-32768.0_real64,min(32767.0_real64,value))),c_int16_t) + samples(i)=sample + enddo + samples(1)=-32767_c_int16_t-1_c_int16_t +end subroutine fst4_engine_make_signal + +subroutine decoder_engine_test_fst4_workspace() bind(C) + use iso_c_binding, only: c_int16_t,c_ptr,c_null_ptr,c_associated,c_loc + use fst4_decode, only: fst4_options + use fst4_engine_workspace_test, only: workspace_test_decoder,require,observe + use fftw3, only: fftwf_destroy_plan,FFTW_MEASURE + implicit none + type(workspace_test_decoder) :: decoder + type(fst4_options) :: options + type(c_ptr) :: big_plan,baseband_plan,dop_plan,baseband,frame + integer(c_int16_t), allocatable :: samples(:),saved_pcm(:) + integer :: attempt,status + + options%period=300 + options%low_frequency=1400 + options%high_frequency=1600 + options%receive_frequency=1500 + options%tolerance=50 + options%single_decode=.true. + options%measure_doppler=.true. + allocate(samples(options%period*12000)) + call fst4_engine_make_signal(240,options%period,1500.0,300.0,0,-1,samples) + do attempt=1,4 + if(attempt==3) then + call decoder%reset() + call require(c_associated(decoder%big_plan,big_plan).and. & + c_associated(decoder%baseband_plan,baseband_plan).and.c_associated(decoder%dop_plan,dop_plan), & + 'reset retains FFT plans before the next decode') + endif + if(attempt==4) then + call fftwf_destroy_plan(decoder%big_plan) + call fftwf_destroy_plan(decoder%baseband_plan) + call fftwf_destroy_plan(decoder%dop_plan) + decoder%big_plan=c_null_ptr + decoder%baseband_plan=c_null_ptr + decoder%dop_plan=c_null_ptr + endif + decoder%observations=0 + decoder%expected_doppler=options%measure_doppler + call decoder%decode_pcm(observe,samples,size(samples),options,status) + call require(status==0.and.decoder%observations==1,'one result after workspace reacquisition') + call require(.not.associated(decoder%big),'release long-period FFT scratch') + call require(.not.associated(decoder%dopgain).and..not.associated(decoder%dopwave), & + 'release long-period Doppler scratch') + call require(.not.allocated(decoder%candidate_s).and..not.allocated(decoder%candidate_s2).and. & + .not.allocated(decoder%candidate_base).and..not.allocated(decoder%baseline_scratch), & + 'release long-period candidate scratch') + call require(c_associated(decoder%big_plan).and.c_associated(decoder%baseband_plan).and. & + c_associated(decoder%dop_plan),'retain valid FFT plans') + call require(associated(decoder%baseband).and.associated(decoder%frame),'retain smaller work buffers') + if(attempt==1) then + big_plan=decoder%big_plan + baseband_plan=decoder%baseband_plan + dop_plan=decoder%dop_plan + baseband=c_loc(decoder%baseband(1)) + frame=c_loc(decoder%frame(1)) + else + if(attempt<4) call require(c_associated(decoder%big_plan,big_plan).and. & + c_associated(decoder%baseband_plan,baseband_plan).and.c_associated(decoder%dop_plan,dop_plan), & + 'repeat and reset retain the same FFT plans') + call require(c_associated(c_loc(decoder%baseband(1)),baseband).and. & + c_associated(c_loc(decoder%frame(1)),frame),'repeat and reset retain smaller allocations') + endif + enddo + options%period=15 + call fst4_engine_make_signal(240,options%period,1500.0,300.0,0,-1,samples(1:15*12000)) + decoder%observations=0 + decoder%expected_doppler=options%measure_doppler + call decoder%decode_pcm(observe,samples,15*12000,options,status) + call require(status==0.and.decoder%observations==1,'short-period decode after long-period scratch release') + call require(associated(decoder%big).and.associated(decoder%dopgain).and.associated(decoder%dopwave), & + 'retain short-period FFT and Doppler scratch') + call require(allocated(decoder%candidate_s).and.allocated(decoder%candidate_s2).and. & + allocated(decoder%candidate_base).and.allocated(decoder%baseline_scratch),'retain short-period candidate scratch') + allocate(saved_pcm(15*12000)) + saved_pcm=samples(1:15*12000) + options%fft_flags=FFTW_MEASURE + options%measure_doppler=.false. + decoder%observations=0 + decoder%expected_doppler=options%measure_doppler + call decoder%decode_pcm(observe,samples,15*12000,options,status) + call require(status==0.and.decoder%observations==1,'decode after changing FFT planning effort') + call require(all(samples(1:15*12000)==saved_pcm),'MEASURE planning preserves caller PCM') + call require(c_associated(decoder%big_plan).and.c_associated(decoder%baseband_plan), & + 'MEASURE creates the required FFT plans') + call require(.not.c_associated(decoder%dop_plan),'planning effort invalidates the unused Doppler plan') + options%measure_doppler=.true. + do attempt=1,2 + decoder%observations=0 + decoder%expected_doppler=options%measure_doppler + call decoder%decode_pcm(observe,samples,15*12000,options,status) + call require(status==0.and.decoder%observations==1,'decode with MEASURE Doppler planning') + call require(all(samples(1:15*12000)==saved_pcm),'Doppler MEASURE planning preserves caller PCM') + call require(c_associated(decoder%dop_plan),'recreate the Doppler plan at the selected planning effort') + if(attempt==1) then + big_plan=decoder%big_plan + baseband_plan=decoder%baseband_plan + dop_plan=decoder%dop_plan + else + call require(c_associated(decoder%big_plan,big_plan).and. & + c_associated(decoder%baseband_plan,baseband_plan).and.c_associated(decoder%dop_plan,dop_plan), & + 'unchanged planning effort reuses every FFT plan') + endif + enddo + call decoder%destroy() +end subroutine decoder_engine_test_fst4_workspace diff --git a/tests/unit/decoder_engine/jt65_engine_signal.f90 b/tests/unit/decoder_engine/jt65_engine_signal.f90 new file mode 100644 index 00000000..e31a1ccf --- /dev/null +++ b/tests/unit/decoder_engine/jt65_engine_signal.f90 @@ -0,0 +1,52 @@ +subroutine decoder_engine_test_jt65_signal(submode,kind,seed,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t + use iso_fortran_env, only: real32,real64 + use jt65_test_fixture, only: make_jt65_wave,jt65_sample_count + use jt65_test_vectors, only: standard_tones,ooo_tones + implicit none + integer(c_int), value :: submode,kind,seed + integer(c_int16_t), intent(out) :: samples(jt65_sample_count) + real(real32), allocatable :: wave(:), second(:) + integer :: tones(126),i,j,itype + character :: message(23),sent(23) + character(len=22) :: text + + interface + subroutine gen65(message,check,sent,tones,message_type) bind(C) + import c_int + character :: message(23),sent(23) + integer(c_int) :: check,tones(126),message_type + end subroutine + end interface + + allocate(wave(jt65_sample_count)) + tones=standard_tones + if(kind==1) tones=ooo_tones + if(kind>=3.and.kind<=5) then + tones=0 + do j=1,126 + if(mod((j-1)/4,2)==1) tones(j)=10*(kind-1) + enddo + endif + if(kind==6) then + call make_jt65_wave(wave,tones,1,1500.0_real64,600.0_real64,2500.0_real64,seed) + elseif(kind==2) then + call make_jt65_wave(wave,tones,2**submode,1500.0_real64,110.0_real64,2500.0_real64,seed) + else + call make_jt65_wave(wave,tones,2**submode,1500.0_real64,300.0_real64,100.0_real64,seed) + endif + if(kind==6) then + allocate(second(jt65_sample_count)) + text="K2DEF N0XYZ EM00" + message=" " + do i=1,22 + message(i)=text(i:i) + enddo + call gen65(message,0,sent,tones,itype) + call make_jt65_wave(second,tones,1,2100.0_real64,500.0_real64) + wave=wave+second + endif + do i=1,size(samples) + samples(i)=int(nint(max(-32768.0_real32,min(32767.0_real32,wave(i)))),c_int16_t) + enddo +end subroutine decoder_engine_test_jt65_signal diff --git a/tests/unit/decoder_engine/jt9_engine_signal.f90 b/tests/unit/decoder_engine/jt9_engine_signal.f90 new file mode 100644 index 00000000..b25eda39 --- /dev/null +++ b/tests/unit/decoder_engine/jt9_engine_signal.f90 @@ -0,0 +1,88 @@ +module jt9_engine_test_reference + use jt9_decode, only: jt9_decoder + implicit none + type, extends(jt9_decoder) :: reference_decoder + logical :: found=.false. + real :: result(4)=0. + end type +contains + subroutine observe_reference(this,sync,snr,dt,freq,drift,decoded) + class(jt9_decoder), intent(inout) :: this + real, intent(in) :: sync,dt,freq + integer, intent(in) :: snr,drift + character(len=22), intent(in) :: decoded + if(decoded/='CQ K1JT FN20') return + select type(this) + type is(reference_decoder) + this%found=.true. + this%result=[freq,dt,sync,real(snr)] + end select + end subroutine +end module + +subroutine decoder_engine_test_jt9_signal(submode,start_sample,spread_hz,frequency_hz,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t,c_int64_t,c_float + implicit none + integer(c_int), value :: submode,start_sample + real(c_float), value :: spread_hz,frequency_hz + integer(c_int16_t), intent(out) :: samples(720000) + integer :: tones(85),itype,i,symbol,j + integer(c_int64_t) :: random_state + real(kind=8) :: phase,step,twopi + character(len=22) :: message,sent + + message='CQ K1JT FN20' + call gen9(message,0,sent,tones,itype) + if(sent/=message) error stop 'JT9 engine test message did not encode' + random_state=1234567_c_int64_t + do i=1,size(samples) + random_state=mod(16807_c_int64_t*random_state,2147483647_c_int64_t) + samples(i)=int(mod(random_state,201_c_int64_t)-100_c_int64_t,c_int16_t) + enddo + phase=0.0d0 + twopi=8.0d0*atan(1.0d0) + do symbol=1,85 + step=twopi*(real(frequency_hz,kind=8)+tones(symbol)*(12000.0d0/6912.0d0)*2**submode)/12000.0d0 + do i=1,6912 + j=start_sample+(symbol-1)*6912+i + phase=modulo(phase+step+twopi*spread_hz*sin(twopi*0.4d0*j/12000.0d0)/12000.0d0,twopi) + samples(j)=samples(j)+int(45.0d0*sin(phase),c_int16_t) + enddo + enddo +end subroutine + +subroutine decoder_engine_test_jt9_reference(submode,windowed,samples,result) bind(C) + use jt9_decode, only: jt9_spectrum_workspace + use jt9_engine_test_reference, only: reference_decoder,observe_reference + include 'jt9com.f90' + integer(c_int), value :: submode,windowed + integer(c_short), intent(in) :: samples(720000) + real(c_float), intent(out) :: result(4) + type(dec_data), allocatable :: shared + type(reference_decoder) :: decoder + type(jt9_spectrum_workspace) :: workspace + real, allocatable :: spectra(:,:),waterfall(:) + real :: power,peak,df + integer :: row,half_symbols,npts8 + logical(c_bool) :: low_sidelobes + + allocate(shared,spectra(184,NSMAX),waterfall(NSMAX)) + shared%ss=0. + shared%id2(:720000)=samples + low_sidelobes=windowed/=0 + do row=1,181 + call symspec(shared,row*3456,6912,0,low_sidelobes,0,power,waterfall, & + df,half_symbols,npts8,peak,0.0) + enddo + if(windowed==0) then + call workspace%prepare_spectra(samples,181,spectra) + if(maxval(abs(spectra-shared%ss))>2.e-6*maxval(shared%ss)) & + error stop 'JT9 PCM spectrum differs from unwindowed legacy spectrum' + endif + call decoder%decode(observe_reference,shared%ss,shared%id2,1000,.true.,90000, & + 900,900,1100,20,181,.false.,3,9,submode,0) + call decoder%reset() + call workspace%clear() + if(.not.decoder%found) error stop 'JT9 legacy spectrum reference did not decode' + result=decoder%result +end subroutine diff --git a/tests/unit/decoder_engine/q65_engine_signal.f90 b/tests/unit/decoder_engine/q65_engine_signal.f90 new file mode 100644 index 00000000..812f8dde --- /dev/null +++ b/tests/unit/decoder_engine/q65_engine_signal.f90 @@ -0,0 +1,85 @@ +subroutine decoder_engine_test_q65_signal(period,submode,flag,seed,amplitude,noise,frequency,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t,c_float + implicit none + integer(c_int), value :: period,submode,flag,seed + real(c_float), value :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(period*12000) + call q65_engine_make_signal('K1ABC W9XYZ FN42',period,submode,flag,seed,amplitude,noise,frequency,samples) +end subroutine + +subroutine decoder_engine_test_q65_message(message,period,submode,flag,seed,amplitude,noise,frequency,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t,c_float,c_char + implicit none + character(c_char), intent(in) :: message(37) + integer(c_int), value :: period,submode,flag,seed + real(c_float), value :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(period*12000) + character(len=37) :: text + integer :: i + do i=1,37 + text(i:i)=message(i) + enddo + call q65_engine_make_signal(text,period,submode,flag,seed,amplitude,noise,frequency,samples) +end subroutine + +subroutine q65_engine_make_signal(message,period,submode,flag,seed,amplitude,noise,frequency,samples) + use iso_c_binding, only: c_int,c_int16_t,c_float + use iso_fortran_env, only: int64,real64 + use packjt77, only: pack77_state + use q65, only: q65_state,q65_work + implicit none + character(len=*), intent(in) :: message + integer(c_int), intent(in) :: period,submode,flag,seed + real(c_float), intent(in) :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(period*12000) + real(real64), parameter :: twopi=6.283185307179586476925286766559_real64 + integer(int64) :: state + integer :: tones(85),nsps,start,i,symbol,i3,n3 + real(real64) :: phase,value,u1,u2,freq + character(len=37) :: encoded,sent + type(pack77_state), target :: knowledge + type(q65_state), allocatable, target :: encoder + type(q65_state), pointer :: previous + + select case(period) + case(15) + nsps=1800 + case(30) + nsps=3600 + case(60) + nsps=7200 + case(120) + nsps=16000 + case(300) + nsps=41472 + case default + error stop 'invalid Q65 fixture period' + end select + ! Fixture encoding must not populate the decoder callsign knowledge. + allocate(encoder) + encoder%knowledge=>knowledge + previous=>q65_work + q65_work=>encoder + encoded=message + call genq65(encoded,0,sent,tones,i3,n3,flag) + q65_work=>previous + if(i3<0.or.n3<0) error stop 'Q65 fixture message failed to encode' + start=12000 + if(period.le.30) start=6000 + state=104729_int64+int(seed,int64) + phase=0.0_real64 + do i=1,size(samples) + state=modulo(16807_int64*state,2147483647_int64) + u1=max(real(state,real64)/2147483647.0_real64,tiny(1.0_real64)) + state=modulo(16807_int64*state,2147483647_int64) + u2=real(state,real64)/2147483647.0_real64 + value=noise*sqrt(-2.0_real64*log(u1))*cos(twopi*u2) + if(i.gt.start .and. i.le.start+85*nsps) then + symbol=(i-start-1)/nsps+1 + freq=frequency+tones(symbol)*(12000.0_real64/nsps)*2**submode + phase=modulo(phase+twopi*freq/12000.0_real64,twopi) + value=value+amplitude*cos(phase) + endif + samples(i)=int(nint(max(-32768.0_real64,min(32767.0_real64,value))),c_int16_t) + enddo +end subroutine q65_engine_make_signal diff --git a/tests/unit/decoder_engine/test_decoder_engine.c b/tests/unit/decoder_engine/test_decoder_engine.c new file mode 100644 index 00000000..218688b3 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine.c @@ -0,0 +1,373 @@ +#include "DecoderEngine.h" + +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +extern void decoder_engine_test_signal(int16_t samples[180000], int8_t payload[77], + int8_t tones[79], int32_t start_sample); +extern void decoder_engine_test_records(decoder_observation records[2], size_t *record_size); +extern void decoder_engine_test_residual(float samples[180000]); +extern void decoder_engine_test_host_windows(void); + +static void check_evidence_layout(void) +{ + decoder_observation records[2]; + size_t record_size = 0; + decoder_engine_test_records(records, &record_size); + CHECK(record_size == sizeof records[0]); + CHECK(records[0].mode == DECODER_MODE_FT4); + CHECK(records[0].dt_seconds == 0.25f); + CHECK(records[0].ft4.payload77[76] == 1 && records[0].ft4.tones[102] == 3); + CHECK(records[0].ft4.payload_origin == DECODER_PAYLOAD_DECODED); + CHECK(records[0].ft4.has_tones == 1 && records[0].ft4.has_waveform_start == 1); + CHECK(records[0].ft4.waveform_start_seconds == -0.125f); + CHECK(records[0].ft8.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(records[1].mode == DECODER_MODE_FT8); + CHECK(records[1].variant == DECODER_FT8_SUPERFOX); + CHECK(records[1].superfox.symbols[49] == 127); + CHECK(records[1].superfox.kind == DECODER_SUPERFOX_VERIFICATION); + CHECK(records[1].superfox.child_index == 4); + CHECK(records[1].ft8.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(records[1].ft4.payload_origin == DECODER_PAYLOAD_NONE); +} + +typedef struct { + decoder_engine_handle engine; + const decoder_attempt_request *request; + const decoder_audio_view *audio; + int count; + int found_expected; + int8_t expected_payload[77]; + int8_t expected_tones[79]; + float expected_start_seconds; + decoder_observation retained; + decoder_observation expected_record; +} callback_context; + +static void observe(const decoder_observation *record, void *opaque) +{ + callback_context *context = opaque; + decoder_attempt_outcome outcome; + CHECK(record->input_id == context->request->input_id); + CHECK(record->analysis_id == context->request->analysis_id); + CHECK(record->attempt_no == context->request->attempt_no); + CHECK(record->mode == DECODER_MODE_FT8); + ++context->count; + context->retained = *record; + + if (strcmp(record->message, "CQ K1JT FN20") == 0) { + CHECK(record->ft8.payload_origin == DECODER_PAYLOAD_DECODED); + CHECK(memcmp(record->ft8.payload77, context->expected_payload, 77) == 0); + CHECK(memcmp(record->ft8.tones, context->expected_tones, 79) == 0); + CHECK(record->ft8.has_tones != 0); + CHECK(record->ft8.has_waveform_start != 0); + CHECK(fabsf(record->ft8.waveform_start_seconds - context->expected_start_seconds) < 0.035f); + CHECK(fabsf(record->dt_seconds - (context->expected_start_seconds - 0.5f)) < 0.035f); + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->ft4.has_tones == 0 && record->ft4.has_waveform_start == 0); + CHECK(record->superfox.kind == 0 && record->superfox.child_index == 0); + context->expected_record = *record; + ++context->found_expected; + } + + CHECK(decoder_engine_release_input(context->engine, record->input_id) == DECODER_BUSY); + CHECK(decoder_engine_reset_session(context->engine) == DECODER_BUSY); + CHECK(decoder_engine_destroy(context->engine) == DECODER_BUSY); + CHECK(decoder_engine_decode(context->engine, context->request, context->audio, + observe, context, &outcome) == DECODER_BUSY); +} + +static decoder_attempt_request request_for(int64_t input_id, int64_t analysis_id) +{ + decoder_attempt_request request = {0}; + request.input_id = input_id; + request.analysis_id = analysis_id; + request.attempt_no = 1; + request.mode = DECODER_MODE_FT8; + request.phase = DECODER_PHASE_NORMAL; + request.source = DECODER_SOURCE_FILE; + request.ft8.half_symbol_stage = 50; + request.ft8.utc = 120000; + request.ft8.receive_frequency_hz = 1500; + request.ft8.transmit_frequency_hz = 1500; + request.ft8.search_low_hz = 200; + request.ft8.search_high_hz = 4000; + request.ft8.tolerance_hz = 20; + request.ft8.depth = 1; + request.ft8.ap_width_hz = 75; + request.ft8.cycles = 1; + request.ft8.threads = 1; + request.ft8.discard_leading_seconds = 0; + request.ft8.date = 260928; + memset(request.ft8.mycall, ' ', sizeof request.ft8.mycall); + memset(request.ft8.my_base_call, ' ', sizeof request.ft8.my_base_call); + memset(request.ft8.hiscall, ' ', sizeof request.ft8.hiscall); + memset(request.ft8.his_base_call, ' ', sizeof request.ft8.his_base_call); + memset(request.ft8.mygrid, ' ', sizeof request.ft8.mygrid); + memset(request.ft8.hisgrid, ' ', sizeof request.ft8.hisgrid); + return request; +} + +static decoder_attempt_request mtd_request_for(int64_t input_id, int64_t analysis_id) +{ + decoder_attempt_request request = request_for(input_id, analysis_id); + request.ft8.mtd = 1; + request.ft8.depth = 3; + request.ft8.threads = 2; + request.ft8.candidate_thinning = 100; + request.ft8.receive_sensitivity = 3; + request.ft8.low_threshold = 1; + request.ft8.subtract_pass = 1; + request.ft8.wide_dx_search = 1; + return request; +} + +static void decode_signal(callback_context *context, const int16_t *original, + decoder_attempt_outcome *outcome) +{ + context->count = 0; + context->found_expected = 0; + CHECK(decoder_engine_decode(context->engine, context->request, context->audio, + observe, context, outcome) == DECODER_OK); + CHECK(outcome->status == DECODER_OK); + CHECK(context->found_expected > 0); + CHECK(context->count == outcome->observation_count); + CHECK(outcome->retained_count > 0 && outcome->evidence_dropped == 0); + CHECK(memcmp(context->audio->samples, original, 180000 * sizeof *original) == 0); +} + +static void check_same_result(const callback_context *context, + const decoder_observation *reference, int count) +{ + CHECK(context->count == count); + CHECK(strcmp(context->expected_record.message, reference->message) == 0); + CHECK(context->expected_record.variant == reference->variant); + CHECK(context->expected_record.ft8.payload_origin == reference->ft8.payload_origin); + CHECK(memcmp(context->expected_record.ft8.payload77, reference->ft8.payload77, 77) == 0); + CHECK(memcmp(context->expected_record.ft8.tones, reference->ft8.tones, 79) == 0); +} + +static void check_reset_and_recreate(callback_context *context, + decoder_attempt_request *request, + const int16_t *original, + const decoder_engine_options *options, + decoder_attempt_outcome *outcome) +{ + decoder_observation reference = context->expected_record; + int reference_count = context->count; + CHECK(decoder_engine_reset_session(context->engine) == DECODER_OK); + ++request->input_id; + ++request->analysis_id; + decode_signal(context, original, outcome); + check_same_result(context, &reference, reference_count); + CHECK(decoder_engine_destroy(context->engine) == DECODER_OK); + CHECK(decoder_engine_create(options, &context->engine) == DECODER_OK); + ++request->input_id; + ++request->analysis_id; + decode_signal(context, original, outcome); + check_same_result(context, &reference, reference_count); +} + +static void check_repeat_stages_and_eme(callback_context *context, const int16_t *original) +{ + decoder_attempt_request request = request_for(701, 801); + decoder_attempt_outcome outcome; + context->request = &request; + request.phase = DECODER_PHASE_REPEAT; + request.ft8.eme_delay_seconds = 2.0f; + CHECK(decoder_engine_reset_session(context->engine) == DECODER_OK); + for (int stage = 41; stage < 50; ++stage) { + request.ft8.half_symbol_stage = stage; + ++request.attempt_no; + CHECK(decoder_engine_decode(context->engine, &request, context->audio, + NULL, NULL, &outcome) == DECODER_OK); + CHECK(outcome.observation_count == 0); + } + request.ft8.half_symbol_stage = 50; + ++request.attempt_no; + decode_signal(context, original, &outcome); +} + +static void probe_mtd_residual(callback_context *context, decoder_attempt_request *request, + int source, float *residual) +{ + decoder_attempt_request probe = *request; + decoder_attempt_outcome outcome; + /* Stop after input preparation so decoding cannot modify the residual. */ + probe.ft8.filtered_retry = 1; + probe.ft8.receive_frequency_hz = 3000; + probe.ft8.search_low_hz = 1000; + probe.ft8.search_high_hz = 2000; + probe.phase = DECODER_PHASE_REPEAT; + probe.source = source; + probe.attempt_no = ++request->attempt_no; + CHECK(decoder_engine_decode(context->engine, &probe, context->audio, + NULL, NULL, &outcome) == DECODER_OK); + decoder_engine_test_residual(residual); +} + +static void check_mtd_lifecycle(callback_context *context, decoder_attempt_request *request, + const int16_t *original, const decoder_engine_options *options) +{ + float *saved = malloc(180000 * sizeof *saved); + float *current = malloc(180000 * sizeof *current); + decoder_attempt_outcome outcome; + decoder_observation reference = context->expected_record; + int reference_count = context->count; + int changed = 0; + CHECK(saved != NULL && current != NULL); + decoder_engine_test_residual(saved); + for (int i = 0; i < 180000; ++i) + changed |= saved[i] != context->audio->samples[i]; + CHECK(changed); + + probe_mtd_residual(context, request, DECODER_SOURCE_FILE, current); + CHECK(memcmp(saved, current, 180000 * sizeof *saved) == 0); + + for (int recreate = 0; recreate <= 1; ++recreate) { + if (recreate) { + CHECK(decoder_engine_destroy(context->engine) == DECODER_OK); + CHECK(decoder_engine_create(options, &context->engine) == DECODER_OK); + } else { + CHECK(decoder_engine_reset_session(context->engine) == DECODER_OK); + } + ++request->input_id; + ++request->analysis_id; + request->attempt_no = 1; + probe_mtd_residual(context, request, DECODER_SOURCE_FILE, current); + for (int i = 0; i < 180000; ++i) + CHECK(current[i] == context->audio->samples[i]); + + ++request->attempt_no; + decode_signal(context, original, &outcome); + check_same_result(context, &reference, reference_count); + decoder_engine_test_residual(current); + changed = 0; + for (int i = 0; i < 180000; ++i) + changed |= current[i] != context->audio->samples[i]; + CHECK(changed); + if (recreate) { + CHECK(decoder_engine_release_input(context->engine, request->input_id) == DECODER_OK); + ++request->input_id; + ++request->analysis_id; + request->attempt_no = 1; + } + probe_mtd_residual(context, request, + recreate ? DECODER_SOURCE_FILE : DECODER_SOURCE_LIVE, current); + for (int i = 0; i < 180000; ++i) + CHECK(current[i] == context->audio->samples[i]); + } + free(current); + free(saved); +} + +int main(void) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + decoder_engine_handle engine = NULL, second = NULL; + decoder_engine_capabilities capabilities; + decoder_attempt_request request = request_for(101, 201); + decoder_attempt_outcome outcome; + int16_t *samples = calloc(180000, sizeof *samples); + int16_t *before = calloc(180000, sizeof *before); + decoder_audio_view audio = {samples, 180000, 12000}; + callback_context context = {0}; + CHECK(samples != NULL && before != NULL); + check_evidence_layout(); + + options.abi_version = DECODER_ENGINE_ABI - 1; + CHECK(decoder_engine_create(&options, &engine) == DECODER_UNSUPPORTED); + CHECK(engine == NULL); + options.abi_version = DECODER_ENGINE_ABI; + CHECK(decoder_engine_create(&options, &engine) == DECODER_OK); + CHECK(engine != NULL); + CHECK(decoder_engine_create(&options, &second) == DECODER_BUSY); + CHECK(decoder_engine_get_capabilities(engine, &capabilities) == DECODER_OK); + CHECK(capabilities.abi_version == DECODER_ENGINE_ABI); + CHECK(capabilities.supported_modes == (DECODER_SUPPORT_FT8 | DECODER_SUPPORT_FT4 | DECODER_SUPPORT_JT9 | DECODER_SUPPORT_JT65 | DECODER_SUPPORT_Q65 | DECODER_SUPPORT_FST4 | DECODER_SUPPORT_FST4W)); + CHECK(capabilities.cancellation == 0); + CHECK(capabilities.concurrent_sessions == 0); + CHECK(capabilities.evidence_capacity == 1024); + + context.engine = engine; + context.request = &request; + context.audio = &audio; + request.mode = 123; + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_UNSUPPORTED); + request.mode = DECODER_MODE_FT4; + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_INVALID); + request.mode = DECODER_MODE_FT8; + audio.sample_rate_hz = 48000; + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_UNSUPPORTED); + audio.sample_rate_hz = 12000; + audio.sample_count = 180001; + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_INVALID); + audio.sample_count = 0; + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_INVALID); + audio.sample_count = 180000; + for (int stage = 40; stage <= 51; stage += 11) { + request.ft8.half_symbol_stage = stage; + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_INVALID); + } + request.ft8.half_symbol_stage = 50; + CHECK(context.count == 0); + + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_OK); + CHECK(outcome.status == DECODER_OK); + CHECK(outcome.observation_count == 0 && context.count == 0); + CHECK(outcome.retained_count == 0 && outcome.evidence_dropped == 0); + CHECK(memcmp(samples, before, 180000 * sizeof *samples) == 0); + CHECK(decoder_engine_release_input(engine, request.input_id) == DECODER_OK); + + context.expected_start_seconds = 0.5f; + decoder_engine_test_signal(samples, context.expected_payload, context.expected_tones, 6000); + memcpy(before, samples, 180000 * sizeof *samples); + request = request_for(102, 202); + decode_signal(&context, before, &outcome); + + /* A different reception cannot silently replace retained input state. */ + request.input_id = 103; + CHECK(decoder_engine_decode(engine, &request, &audio, observe, &context, &outcome) == DECODER_INVALID); + request.input_id = 102; + check_reset_and_recreate(&context, &request, before, &options, &outcome); + CHECK(decoder_engine_release_input(context.engine, request.input_id) == DECODER_OK); + CHECK(context.retained.input_id == request.input_id); + CHECK(context.retained.analysis_id == request.analysis_id); + + memset(samples, 0, 180000 * sizeof *samples); + context.count = 0; + request = request_for(105, 205); + CHECK(decoder_engine_decode(context.engine, &request, &audio, observe, &context, &outcome) == DECODER_OK); + CHECK(outcome.observation_count == 0 && context.count == 0); + CHECK(outcome.retained_count == 0); + CHECK(decoder_engine_reset_session(context.engine) == DECODER_OK); + memcpy(samples, before, 180000 * sizeof *samples); + request = mtd_request_for(301, 401); + decode_signal(&context, before, &outcome); + CHECK(context.expected_record.variant == DECODER_FT8_MTD); + check_mtd_lifecycle(&context, &request, before, &options); + /* Classic crops EME input; MTD analyzes the original sample coordinates. */ + context.expected_start_seconds = 2.15f; + decoder_engine_test_signal(samples, context.expected_payload, context.expected_tones, 25800); + memcpy(before, samples, 180000 * sizeof *samples); + check_repeat_stages_and_eme(&context, before); + context.request = &request; + CHECK(decoder_engine_reset_session(context.engine) == DECODER_OK); + request = mtd_request_for(502, 602); + request.ft8.eme_delay_seconds = 2.0f; + decode_signal(&context, before, &outcome); + CHECK(decoder_engine_destroy(context.engine) == DECODER_OK); + decoder_engine_test_host_windows(); + free(before); + free(samples); + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_fst4.c b/tests/unit/decoder_engine/test_decoder_engine_fst4.c new file mode 100644 index 00000000..d93bc080 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_fst4.c @@ -0,0 +1,369 @@ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#include "DecoderEngine.h" +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#ifdef __linux__ +#include +#endif +#define CHECK(c) do { if (!(c)) { fprintf(stderr,"%s:%d: %s\n",__FILE__,__LINE__,#c); exit(EXIT_FAILURE); } } while (0) +extern void decoder_engine_test_fst4_signal(int, int, float, int16_t *); +extern void decoder_engine_test_fst4_weak_signal(int, float, int16_t *); +extern void decoder_engine_test_fst4_ap_signal(int16_t *); +extern void decoder_engine_test_fst4_rr73_signal(int16_t *); +extern void decoder_engine_test_fst4_workspace(void); +extern void decoder_engine_test_fst4_hash_signals(int, int16_t *); +typedef struct { + decoder_engine_handle engine; + decoder_attempt_request request; + decoder_audio_view audio; + int16_t *samples, *before; + int count, effective_bits, ap_type, expected_bits; + int hash_count, hash_seen; + const char *expected_message; +} fixture; +static int long_periods; + +static void observe(const decoder_observation *o, void *opaque) +{ + fixture *f=opaque; + CHECK(o->input_id==f->request.input_id && o->analysis_id==f->request.analysis_id); + CHECK(o->attempt_no==f->request.attempt_no && o->mode==f->request.mode); + CHECK(o->fst4.period_seconds==f->request.fst4.period_seconds); + CHECK(o->fst4.effective_bits==(f->expected_bits ? f->expected_bits : o->mode==DECODER_MODE_FST4 ? 91 : 66)); + f->effective_bits=o->fst4.effective_bits; + f->ap_type=o->ap_type; + CHECK(o->fst4.blanker_percent==0); + CHECK(o->fst4.has_doppler==f->request.fst4.measure_doppler); + if(o->fst4.has_doppler) CHECK(isfinite(o->fst4.fmid_hz) && isfinite(o->fst4.width_hz) && o->fst4.width_hz>=0); + else CHECK(o->fst4.fmid_hz==0 && o->fst4.width_hz==0); + CHECK(isfinite(o->sync) && o->sync>0 && isfinite(o->quality)); + CHECK(fabsf(o->dt_seconds)<0.3f); + if(f->hash_count) { + CHECK(o->fst4.has_hash22==1); + int index=o->fst4.hash22==1234567 ? 0 : o->fst4.hash22==2345678 ? 1 : -1; + CHECK(index>=0 && indexhash_count); + CHECK(!(f->hash_seen&(1<hash_seen|=1<message,"<...> FN42AB")); + CHECK(fabsf(o->frequency_hz-(f->hash_count==1 ? 1500 : index==0 ? 1450 : 1550))<5); + ++f->count; + } else { + CHECK(o->fst4.has_hash22==0 && o->fst4.hash22==0); + CHECK(fabsf(o->frequency_hz-1500)<5); + CHECK(!strcmp(o->message,f->expected_message ? f->expected_message : + o->mode==DECODER_MODE_FST4 ? "K1ABC W9XYZ FN42" : "K1ABC FN42 37")); + CHECK(!f->count++); + } + CHECK(decoder_engine_release_input(f->engine,o->input_id)==DECODER_BUSY); + CHECK(decoder_engine_reset_session(f->engine)==DECODER_BUSY); + CHECK(decoder_engine_set_fst4w_calls(f->engine,NULL,0)==DECODER_BUSY); +} +static void configure(fixture *f,int mode,int period) +{ + static int64_t id=800; + memset(&f->request,0,sizeof f->request); + f->request.input_id=++id; + f->request.analysis_id=id; + f->request.attempt_no=1; + f->request.mode=mode; + f->request.phase=DECODER_PHASE_NORMAL; + f->request.source=DECODER_SOURCE_FILE; + f->request.fst4.period_seconds=period; + f->request.fst4.receive_frequency_hz=1500; + f->request.fst4.search_low_hz=1400; + f->request.fst4.search_high_hz=1600; + f->request.fst4.tolerance_hz=50; + f->request.fst4.depth=1; + f->request.fst4.single_decode=1; + memset(f->request.fst4.mycall,' ',12); + memset(f->request.fst4.hiscall,' ',12); + f->audio.samples=f->samples; + f->audio.sample_count=period*12000; + f->audio.sample_rate_hz=12000; +} +static void decode(fixture *f,int expected) +{ + decoder_attempt_request saved=f->request; + decoder_attempt_outcome outcome; + size_t bytes=(size_t)f->audio.sample_count*sizeof *f->samples; + memcpy(f->before,f->samples,bytes); + f->count=0; + f->hash_seen=0; + CHECK(decoder_engine_decode(f->engine,&f->request,&f->audio,observe,f,&outcome)==DECODER_OK); + CHECK(outcome.status==DECODER_OK && outcome.observation_count==f->count); + if(expected>=0 && f->count!=expected) fprintf(stderr, + "FST4 mode %d progress %d attempt %d expected %d observations, got %d (AP %d, message %s)\n", + f->request.mode,f->request.fst4.qso_progress,f->request.attempt_no,expected,f->count, + f->ap_type,f->expected_message ? f->expected_message : "ordinary fixture"); + CHECK((expected<0 || f->count==expected) && !outcome.evidence_dropped); + if(f->hash_count) CHECK(f->hash_seen==(1<hash_count)-1); + CHECK(!memcmp(&saved,&f->request,sizeof saved)); + CHECK(!memcmp(f->before,f->samples,bytes)); +} +static void release(fixture *f) +{ CHECK(decoder_engine_release_input(f->engine,f->request.input_id)==DECODER_OK); } +static void repeat(fixture *f) +{ + f->request.phase=DECODER_PHASE_REPEAT; + ++f->request.analysis_id; + ++f->request.attempt_no; +} +static void check_rr73_ap(fixture *f) +{ + decoder_engine_options options={DECODER_ENGINE_ABI}; + decoder_engine_test_fst4_rr73_signal(f->samples); + f->hash_count=0; + f->expected_message="K1ABC W9XYZ RR73"; + for(int lifecycle=0;lifecycle<3;++lifecycle) { + if(lifecycle==1) CHECK(decoder_engine_reset_session(f->engine)==DECODER_OK); + if(lifecycle==2) { + CHECK(decoder_engine_destroy(f->engine)==DECODER_OK); + CHECK(decoder_engine_create(&options,&f->engine)==DECODER_OK); + } + configure(f,DECODER_MODE_FST4,15); + f->request.fst4.depth=3; + f->request.fst4.qso_progress=1; + memcpy(f->request.fst4.mycall,"K1ABC ",12); + memcpy(f->request.fst4.hiscall,"W9XYZ ",12); + decode(f,0); + repeat(f); + f->request.fst4.qso_progress=lifecycle==1 ? 4 : 3; + decode(f,1); + CHECK(f->ap_type==6); + repeat(f); + decode(f,1); + CHECK(f->ap_type==6); + release(f); + } + f->expected_message=NULL; +} +static void run_tests(void) +{ + decoder_engine_options options={DECODER_ENGINE_ABI}; + decoder_engine_capabilities caps; + fixture f={0}; + const int capacity=120*12000; + int16_t *short_pcm=malloc(15*12000*sizeof *short_pcm); + f.samples=malloc((size_t)capacity*sizeof *f.samples); + f.before=malloc((size_t)capacity*sizeof *f.before); + CHECK(short_pcm && f.samples && f.before); + CHECK(decoder_engine_create(&options,&f.engine)==DECODER_OK); + CHECK(decoder_engine_get_capabilities(f.engine,&caps)==DECODER_OK); + CHECK((caps.supported_modes&(DECODER_SUPPORT_FST4|DECODER_SUPPORT_FST4W))==(DECODER_SUPPORT_FST4|DECODER_SUPPORT_FST4W)); + decoder_engine_test_fst4_signal(DECODER_MODE_FST4,15,1500,short_pcm); + decoder_engine_test_fst4_signal(DECODER_MODE_FST4W,120,1500,f.samples); + configure(&f,DECODER_MODE_FST4W,120); + decode(&f,1); + repeat(&f); + f.request.fst4.tolerance_hz=0; + decode(&f,1); + f.request.fst4.tolerance_hz=50; + decoder_attempt_outcome invalid_outcome; + int saved_mode=f.request.mode; + f.request.mode=DECODER_MODE_FST4; + CHECK(decoder_engine_decode(f.engine,&f.request,&f.audio,observe,&f,&invalid_outcome)==DECODER_INVALID); + f.request.mode=saved_mode; + f.request.fst4.period_seconds=60; + CHECK(decoder_engine_decode(f.engine,&f.request,&f.audio,observe,&f,&invalid_outcome)==DECODER_INVALID); + f.request.fst4.period_seconds=120; + --f.audio.sample_count; + CHECK(decoder_engine_decode(f.engine,&f.request,&f.audio,observe,&f,&invalid_outcome)==DECODER_INVALID); + ++f.audio.sample_count; + repeat(&f); + decode(&f,1); + release(&f); + decoder_fst4w_call history={{0}},copied; + int32_t count; + memset(history.call_grid,' ',sizeof history.call_grid); + memcpy(history.call_grid,"K1ABC FN42",10); + CHECK(decoder_engine_set_fst4w_calls(f.engine,&history,1)==DECODER_OK); + memset(&history,0,sizeof history); + CHECK(decoder_engine_get_fst4w_calls(f.engine,NULL,0,&count)==DECODER_OK && count==1); + CHECK(decoder_engine_get_fst4w_calls(f.engine,&copied,1,&count)==DECODER_OK); + CHECK(!memcmp(copied.call_grid,"K1ABC FN42",10)); + CHECK(decoder_engine_set_fst4w_calls(f.engine,NULL,1)==DECODER_INVALID); + CHECK(decoder_engine_set_fst4w_calls(f.engine,NULL,DECODER_FST4W_CALL_CAPACITY+1)==DECODER_INVALID); + decoder_engine_test_fst4_weak_signal(120,2.0f,f.samples); + configure(&f,DECODER_MODE_FST4W,120); + f.request.fst4.depth=3; + f.expected_bits=50; + CHECK(decoder_engine_set_fst4w_calls(f.engine,NULL,0)==DECODER_OK); + decode(&f,0); + repeat(&f); + CHECK(decoder_engine_set_fst4w_calls(f.engine,&copied,1)==DECODER_OK); + decode(&f,1); + release(&f); + f.expected_bits=0; + memcpy(f.samples,short_pcm,15*12000*sizeof *short_pcm); + configure(&f,DECODER_MODE_FST4,15); + decode(&f,1); + CHECK(decoder_engine_get_fst4w_calls(f.engine,NULL,0,&count)==DECODER_OK && count==1); + repeat(&f); + f.request.fst4.search_low_hz=1499; + f.request.fst4.search_high_hz=1501; + f.request.fst4.tolerance_hz=1; + decode(&f,1); + f.request.fst4.search_low_hz=1400; + f.request.fst4.search_high_hz=1600; + f.request.fst4.tolerance_hz=50; + repeat(&f); + f.request.fst4.measure_doppler=1; + f.request.fst4.mycall[0]='K'; + f.request.fst4.hiscall[0]='W'; + decode(&f,1); + release(&f); + CHECK(decoder_engine_reset_session(f.engine)==DECODER_OK); + CHECK(decoder_engine_get_fst4w_calls(f.engine,NULL,0,&count)==DECODER_OK && count==0); + decoder_engine_test_fst4_ap_signal(f.samples); + configure(&f,DECODER_MODE_FST4,15); + f.request.fst4.depth=3; + f.request.fst4.qso_progress=1; + memcpy(f.request.fst4.mycall,"K1ABC ",12); + memcpy(f.request.fst4.hiscall,"W9XYZ ",12); + decode(&f,1); + fprintf(stderr,"corrupted-call fixture AP type %d\n",f.ap_type); + CHECK(f.ap_type==2 || f.ap_type==3); + repeat(&f); + memcpy(f.request.fst4.mycall,"N0CALL ",12); + memcpy(f.request.fst4.hiscall,"K9XYZ ",12); + decode(&f,0); + release(&f); + configure(&f,DECODER_MODE_FST4,15); + decoder_attempt_outcome outcome; + f.request.fst4.period_seconds=INT32_MAX; + CHECK(decoder_engine_decode(f.engine,&f.request,&f.audio,observe,&f,&outcome)==DECODER_INVALID); + f.request.fst4.period_seconds=15; + f.audio.sample_count=15*12000+1; + CHECK(decoder_engine_decode(f.engine,&f.request,&f.audio,observe,&f,&outcome)==DECODER_INVALID); + f.audio.sample_count=1; + f.samples[0]=0; + decode(&f,0); + release(&f); + CHECK(decoder_engine_destroy(f.engine)==DECODER_OK); + CHECK(decoder_engine_create(&options,&f.engine)==DECODER_OK); + memcpy(f.samples,short_pcm,15*12000*sizeof *short_pcm); + configure(&f,DECODER_MODE_FST4,15); + decode(&f,1); + release(&f); + configure(&f,DECODER_MODE_FST4,15); + f.request.fst4.eme_delay_seconds=15; + decode(&f,0); + release(&f); + for(int count=1;count<=2;++count) { + decoder_engine_test_fst4_hash_signals(count,f.samples); + configure(&f,DECODER_MODE_FST4W,15); + f.hash_count=count; + f.request.fst4.single_decode=0; + f.request.fst4.tolerance_hz=100; + f.request.fst4.blanker_mode=5; + decode(&f,count); + repeat(&f); + decode(&f,count); + release(&f); + } + check_rr73_ap(&f); + CHECK(decoder_engine_destroy(f.engine)==DECODER_OK); + free(short_pcm); free(f.samples); free(f.before); +} +static void run_long_periods(void) +{ + decoder_engine_options options={DECODER_ENGINE_ABI}; + fixture f={0}; + const int periods[]={300,900,1800,30,60}; + f.samples=malloc((size_t)1800*12000*sizeof *f.samples); + f.before=malloc((size_t)1800*12000*sizeof *f.before); + CHECK(f.samples && f.before); + CHECK(decoder_engine_create(&options,&f.engine)==DECODER_OK); + for(size_t i=0;i>(8*i))&255,file)!=EOF); } +static void write_wav(const char *path,int mode,int period) +{ + int count=period*12000; + int16_t *pcm=malloc((size_t)count*sizeof *pcm); + CHECK(pcm); + decoder_engine_test_fst4_signal(mode,period,1500,pcm); + FILE *file=fopen(path,"wb"); CHECK(file); + CHECK(fwrite("RIFF",1,4,file)==4); write_le(file,36+count*2,4); + CHECK(fwrite("WAVEfmt ",1,8,file)==8); write_le(file,16,4); + write_le(file,1,2); write_le(file,1,2); write_le(file,12000,4); write_le(file,24000,4); + write_le(file,2,2); write_le(file,16,2); CHECK(fwrite("data",1,4,file)==4); + write_le(file,count*2,4); + for(int i=0;idlpi_phnum; ++i) { + const ElfW(Phdr) *header = &info->dlpi_phdr[i]; + if (header->p_type == PT_TLS) *stack_size += header->p_memsz + header->p_align; + } + return 0; +} +#endif + +int main(int argc,char **argv) +{ + if(argc==5 && !strcmp(argv[1],"--write-wav")) { + write_wav(argv[2],atoi(argv[3]),atoi(argv[4])); + return EXIT_SUCCESS; + } + CHECK(argc==1 || (argc==2 && (!strcmp(argv[1],"--small-stack") || !strcmp(argv[1],"--long-periods")))); + long_periods=argc==2 && !strcmp(argv[1],"--long-periods"); +#ifdef _WIN32 + HANDLE thread=CreateThread(NULL,1024*1024,run_on_small_stack,NULL,STACK_SIZE_PARAM_IS_A_RESERVATION,NULL); + CHECK(thread!=NULL && WaitForSingleObject(thread,INFINITE)==WAIT_OBJECT_0); + DWORD status; CHECK(GetExitCodeThread(thread,&status) && status==0); CHECK(CloseHandle(thread)); +#else + pthread_attr_t attributes; + pthread_t thread; + size_t stack_size=1024*1024; +#ifdef __linux__ + dl_iterate_phdr(add_tls_size,&stack_size); +#endif + CHECK(pthread_attr_init(&attributes)==0); + CHECK(pthread_attr_setstacksize(&attributes,stack_size)==0); + CHECK(pthread_create(&thread,&attributes,run_on_small_stack,NULL)==0); + CHECK(pthread_attr_destroy(&attributes)==0); + CHECK(pthread_join(thread,NULL)==0); +#endif + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_fst4_host.f90 b/tests/unit/decoder_engine/test_decoder_engine_fst4_host.f90 new file mode 100644 index 00000000..fc2cb27d --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_fst4_host.f90 @@ -0,0 +1,211 @@ +program test_decoder_engine_fst4_host + use iso_c_binding, only: c_int,c_int16_t,c_int64_t,c_float,c_int8_t,c_sizeof,c_loc,c_f_pointer + use iso_fortran_env, only: error_unit + use decoder_engine, only: engine_host_decode + use ft8_engine_kernel, only: params_block + use decode_completion_module, only: decode_completion_result + use prog_args, only: data_dir,temp_dir + use ieee_arithmetic, only: ieee_is_finite + implicit none + integer(c_int16_t), allocatable, target :: samples(:) + integer(c_int16_t), allocatable :: before(:) + type(params_block), target :: params + type(decode_completion_result) :: completion + integer(c_int8_t), pointer :: parameter_bytes(:) + integer(c_int8_t), allocatable :: saved_parameters(:) + integer(c_int64_t) :: input_id=100,analysis_id=100 + integer, parameter :: modes(4)=[240,241,240,240] + integer, parameter :: receive_frequencies(4)=[1500,1500,1500,200] + integer :: mode,mode_index,period,attempt,unit,ios,matches,bins,first_fst4_bins=0 + real :: frequency,power,last_frequency + character(len=256) :: line + character(len=37) :: expected + interface + subroutine signal(mode,period,frequency,samples) bind(C,name='decoder_engine_test_fst4_signal') + import c_int,c_int16_t,c_float + integer(c_int), value :: mode,period + real(c_float), value :: frequency + integer(c_int16_t), intent(out) :: samples(*) + end subroutine + subroutine hash_signals(count,samples) bind(C,name='decoder_engine_test_fst4_hash_signals') + import c_int,c_int16_t + integer(c_int), value :: count + integer(c_int16_t), intent(out) :: samples(*) + end subroutine + end interface + data_dir='.' + temp_dir='.' + call check_patience_mapping() + open(newunit=unit,file='plotspec',status='replace') + close(unit) + call c_f_pointer(c_loc(params),parameter_bytes,[int(c_sizeof(params))]) + allocate(saved_parameters(size(parameter_bytes))) + do mode_index=1,size(modes) + mode=modes(mode_index) + period=15 + expected='K1ABC W9XYZ FN42' + if(mode==241) then + period=120 + expected='K1ABC FN42 37' + endif + allocate(samples(period*12000),before(period*12000)) + call signal(mode,period,real(receive_frequencies(mode_index),c_float),samples) + before=samples + parameter_bytes=0 + params%nmode=mode + params%ntr=period + params%nfqso=receive_frequencies(mode_index) + params%nfa=1400 + params%nfb=1600 + params%ntol=50 + if(params%nfqso==200) then + params%ntol=500 + params%nfa=params%nfqso-params%ntol + params%nfb=params%nfqso+params%ntol + endif + params%ndepth=1 + params%nexp_decode=32+3*256 + params%ndiskdat=.true. + params%mycall=' ' + params%hiscall=' ' + input_id=input_id+1 + do attempt=1,2 + params%nagain=attempt==2 + params%newdat=attempt==1 + analysis_id=analysis_id+1 + open(newunit=unit,file='decoded.txt',status='replace') + close(unit) + open(52,file='fst4-spectrum.txt',status='replace') + saved_parameters=parameter_bytes + call engine_host_decode(samples,params,12000,completion,0,input_id,analysis_id,attempt,size(samples)) + close(52) + bins=0 + last_frequency=-huge(0.0) + open(newunit=unit,file='fst4-spectrum.txt',status='old',action='read') + do + read(unit,*,iostat=ios) frequency,power + if(ios<0) exit + call require(ios==0,'readable Doppler spectrum') + call require(ieee_is_finite(frequency).and.ieee_is_finite(power),'finite Doppler spectrum') + call require(frequency>last_frequency.and.power>=0,'ordered bins with nonnegative power') + last_frequency=frequency + bins=bins+1 + enddo + close(unit) + call require(bins>0,'host emits Doppler spectrum') + if(mode==240) then + if(first_fst4_bins==0) first_fst4_bins=bins + call require(bins==first_fst4_bins,'shorter period emits only its active spectrum bins') + endif + call require(completion%available,'completion available') + call require(completion%decoded==1,'one decoded message') + call require(all(samples==before),'immutable PCM') + call require(all(parameter_bytes==saved_parameters),'immutable parameters') + matches=0 + open(newunit=unit,file='decoded.txt',status='old',action='read') + do + read(unit,'(a)',iostat=ios) line + if(ios/=0) exit + if(period<60) then + if(line(37:73)==expected) matches=matches+1 + else + if(line(35:71)==expected) matches=matches+1 + endif + enddo + close(unit) + call require(matches==1,'one legacy result in current attempt') + enddo + deallocate(samples,before) + enddo + open(newunit=unit,file='plotspec',status='old') + close(unit,status='delete') + allocate(samples(15*12000),before(15*12000)) + call hash_signals(2,samples) + before=samples + do mode=241,242 + parameter_bytes=0 + params%nmode=mode + params%ntr=15 + params%nfqso=1500 + params%nfa=1400 + params%nfb=1600 + params%ntol=100 + params%ndepth=1 + params%nexp_decode=512 + params%ndiskdat=.true. + params%mycall=' ' + params%hiscall=' ' + input_id=input_id+1 + do attempt=1,2 + params%nagain=attempt==2 + params%newdat=attempt==1 + analysis_id=analysis_id+1 + open(newunit=unit,file='decoded.txt',status='replace') + close(unit) + open(6,file='fst4-hash-output.txt',status='replace') + saved_parameters=parameter_bytes + call engine_host_decode(samples,params,12000,completion,0,input_id,analysis_id,attempt,size(samples)) + close(6) + call require(completion%available.and.completion%decoded==2,'two distinct unresolved hash results') + call require(all(samples==before),'immutable hash PCM') + call require(all(parameter_bytes==saved_parameters),'immutable hash parameters') + call verify_hash_output('decoded.txt',mode) + call verify_hash_output('fst4-hash-output.txt',mode) + enddo + enddo + deallocate(samples,before) +contains + subroutine check_patience_mapping() + use fst4_decode, only: fst4_decoder,fst4_options + use fst4_host_support, only: prepare_fst4_host + use fftw3, only: FFTW_ESTIMATE,FFTW_ESTIMATE_PATIENT,FFTW_MEASURE,FFTW_PATIENT,FFTW_EXHAUSTIVE + type(fst4_decoder) :: decoder + type(fst4_options) :: options + integer, parameter :: flags(0:4)=[FFTW_ESTIMATE,FFTW_ESTIMATE_PATIENT,FFTW_MEASURE,FFTW_PATIENT,FFTW_EXHAUSTIVE] + integer :: npatience,nthreads,saved_patience,level + common/patience/npatience,nthreads + saved_patience=npatience + decoder%host_history_loaded=.true. + call require(options%fft_flags==FFTW_ESTIMATE,'default FFT planning effort') + do level=0,4 + npatience=level + options%fft_flags=-1 + call prepare_fst4_host(decoder,options) + call require(options%fft_flags==flags(level),'host patience applies with history already loaded') + enddo + npatience=saved_patience + end subroutine + + subroutine verify_hash_output(path,mode) + character(len=*), intent(in) :: path + integer, intent(in) :: mode + integer :: unit,ios,canonical,first_hash,second_hash + character(len=256) :: line + canonical=0 + first_hash=0 + second_hash=0 + open(newunit=unit,file=path,status='old',action='read') + do + read(unit,'(a)',iostat=ios) line + if(ios/=0) exit + if(index(line,'<...> FN42AB')>0) canonical=canonical+1 + if(index(line,'<1234567> FN42AB')>0) first_hash=first_hash+1 + if(index(line,'<2345678> FN42AB')>0) second_hash=second_hash+1 + enddo + close(unit) + if(mode==241) then + call require(canonical==2.and.first_hash==0.and.second_hash==0,'ordinary host keeps canonical hash text') + else + call require(canonical==0.and.first_hash==1.and.second_hash==1,'hash-print host renders each distinct hash') + endif + end subroutine + + subroutine require(condition,description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if(.not.condition) then + write(error_unit,'(a)') 'FAIL: '//description + error stop 1 + endif + end subroutine +end program test_decoder_engine_fst4_host diff --git a/tests/unit/decoder_engine/test_decoder_engine_ft4.c b/tests/unit/decoder_engine/test_decoder_engine_ft4.c new file mode 100644 index 00000000..f2e46e60 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_ft4.c @@ -0,0 +1,225 @@ +#include "DecoderEngine.h" +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +extern void decoder_engine_test_message(int mode, const char text[37], int16_t samples[180000], + int8_t payload[77], int8_t tones[103], int start_sample); +extern void decoder_engine_test_legacy_isolation(void); +extern void decoder_engine_test_gui_codec(void); + +typedef struct { + decoder_engine_handle engine; + decoder_attempt_request request; + decoder_audio_view audio; + const char *expected_message; + int8_t payload[77], tones[103]; + float start; + int count, found; +} fixture; + +static void observe(const decoder_observation *record, void *opaque) +{ + fixture *f = opaque; + CHECK(record->input_id == f->request.input_id); + CHECK(record->analysis_id == f->request.analysis_id); + CHECK(record->attempt_no == f->request.attempt_no); + CHECK(record->mode == f->request.mode); + ++f->count; + if (strcmp(record->message, f->expected_message)) return; + ++f->found; + CHECK(fabsf(record->frequency_hz - 1500.0f) < 2.0f); + if (record->mode == DECODER_MODE_FT4) { + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_DECODED); + CHECK(record->ft4.has_tones && record->ft4.has_waveform_start); + CHECK(!memcmp(record->ft4.payload77, f->payload, 77)); + CHECK(!memcmp(record->ft4.tones, f->tones, 103)); + CHECK(fabsf(record->ft4.waveform_start_seconds - f->start) < 0.01f); + CHECK(fabsf(record->dt_seconds - (f->start + 0.048f - 0.5f)) < 0.01f); + CHECK(record->ft8.payload_origin == DECODER_PAYLOAD_NONE && record->superfox.kind == 0); + } else { + CHECK(!memcmp(record->ft8.payload77, f->payload, 77)); + CHECK(!memcmp(record->ft8.tones, f->tones, 79)); + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_NONE); + } + CHECK(decoder_engine_release_input(f->engine, record->input_id) == DECODER_BUSY); +} + +static void prepare(fixture *f, int mode, const char *message, float start) +{ + static int64_t next_id = 100; + char padded[37]; + memset(padded, ' ', sizeof padded); + memcpy(padded, message, strlen(message)); + memset(&f->request, 0, sizeof f->request); + f->request.input_id = ++next_id; + f->request.analysis_id = next_id; + f->request.attempt_no = 1; + f->request.mode = mode; + f->request.phase = DECODER_PHASE_NORMAL; + f->request.source = DECODER_SOURCE_FILE; + f->request.ft4.utc = 120000; + f->request.ft4.receive_frequency_hz = 1500; + f->request.ft4.search_low_hz = 200; + f->request.ft4.search_high_hz = 3500; + f->request.ft4.depth = 3; + memset(f->request.ft4.mycall, ' ', 12); + memset(f->request.ft4.hiscall, ' ', 12); + f->request.ft8.half_symbol_stage = 50; + f->request.ft8.utc = 120000; + f->request.ft8.receive_frequency_hz = 1500; + f->request.ft8.transmit_frequency_hz = 1500; + f->request.ft8.search_low_hz = 1300; + f->request.ft8.search_high_hz = 1800; + f->request.ft8.depth = 3; + f->request.ft8.cycles = 1; + f->request.ft8.threads = 2; + f->request.ft8.candidate_thinning = 100; + f->request.ft8.receive_sensitivity = 3; + f->request.ft8.low_threshold = 1; + f->request.ft8.subtract_pass = 1; + memset(f->request.ft8.mycall, ' ', 12); + memset(f->request.ft8.hiscall, ' ', 12); + memset(f->request.ft8.my_base_call, ' ', 12); + memset(f->request.ft8.his_base_call, ' ', 12); + memset(f->request.ft8.mygrid, ' ', 6); + memset(f->request.ft8.hisgrid, ' ', 6); + f->audio.sample_count = mode == DECODER_MODE_FT4 ? 72576 : 180000; + f->audio.sample_rate_hz = 12000; + f->expected_message = message; + f->start = start; + decoder_engine_test_message(mode, padded, (int16_t *)f->audio.samples, f->payload, f->tones, + (int)lroundf(start * 12000.0f)); +} + +static void decode(fixture *f) +{ + decoder_attempt_outcome outcome; + int16_t before[180000]; + memcpy(before, f->audio.samples, sizeof before); + f->count = f->found = 0; + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_OK); + if (!f->found) fprintf(stderr, "Missing mode %d message: %s (start %.3f, depth %d, input %lld, observations %d)\n", + f->request.mode, f->expected_message, f->start, f->request.ft4.depth, + (long long)f->request.input_id, f->count); + CHECK(f->found > 0 && f->count == outcome.observation_count); + CHECK(outcome.retained_count >= f->count && outcome.evidence_dropped == 0); + CHECK(!memcmp(before, f->audio.samples, sizeof before)); +} + +static void decode_silence(fixture *f, int retained_count) +{ + decoder_attempt_outcome outcome; + f->count = f->found = 0; + CHECK(feclearexcept(FE_ALL_EXCEPT) == 0); + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_OK); + CHECK(fetestexcept(FE_DIVBYZERO | FE_INVALID) == 0); + CHECK(outcome.status == DECODER_OK && outcome.observation_count == 0); + CHECK(f->count == 0 && outcome.retained_count == retained_count); + CHECK(outcome.evidence_dropped == 0); +} + +int main(void) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + decoder_attempt_outcome outcome; + int16_t samples[180000]; + fixture f = {0}; + f.audio.samples = samples; + CHECK(decoder_engine_create(&options, &f.engine) == DECODER_OK); + + prepare(&f, DECODER_MODE_FT4, "CQ K1JT FN20", 0.452f); + memset(samples, 0, sizeof samples); + decode_silence(&f, 0); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + prepare(&f, DECODER_MODE_FT4, "CQ K1JT FN20", 0.452f); + decode(&f); + int retained_count = f.count; + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.attempt_no; + f.audio.sample_count = 1; + samples[0] = 0; + /* A decodable signal beyond the valid prefix must not reach the decoder. */ + decode_silence(&f, retained_count); + ++f.request.attempt_no; + f.audio.sample_count = 72576; + memset(samples, 0, sizeof samples); + decode_silence(&f, retained_count); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + for (int depth = 1; depth <= 3; ++depth) { + prepare(&f, DECODER_MODE_FT4, "CQ K1JT FN20", 0.452f); + f.request.ft4.depth = depth; + decode(&f); + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + decode(&f); + f.request.mode = DECODER_MODE_FT8; + ++f.request.attempt_no; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + + /* Repeat with a short valid prefix and poisoned storage beyond it. */ + prepare(&f, DECODER_MODE_FT4, "CQ K1JT FN20", -0.048f); + f.audio.sample_count = 64000; + for (int i = 64000; i < 180000; ++i) samples[i] = 32767; + decode(&f); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + for (int mtd = 0; mtd <= 1; ++mtd) { + CHECK(decoder_engine_reset_session(f.engine) == DECODER_OK); + prepare(&f, DECODER_MODE_FT4, "CQ K1JT FN20", 0.452f); + decode(&f); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + prepare(&f, DECODER_MODE_FT8, "PJ2/W1AW RR73", 0.5f); + f.request.ft8.mtd = mtd; + decode(&f); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + CHECK(decoder_engine_reset_session(f.engine) == DECODER_OK); + prepare(&f, DECODER_MODE_FT8, "CQ K1JT FN20", 0.5f); + f.request.ft8.mtd = mtd; + decode(&f); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + prepare(&f, DECODER_MODE_FT4, "PJ2/W1AW RR73", 0.452f); + decode(&f); + CHECK(decoder_engine_reset_session(f.engine) == DECODER_OK); + f.expected_message = "PJ2/W1AW <...> RR73"; + decode(&f); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + + /* Contest configurations must remain usable across repeated calls and resets. */ + for (int contest = 3; contest <= 4; ++contest) { + prepare(&f, DECODER_MODE_FT4, "CQ K1JT FN20", 0.452f); + f.request.ft4.contest = contest; + memcpy(f.request.ft4.mycall, "W9XYZ", 5); + memcpy(f.request.ft4.hiscall, "K1JT", 4); + decode(&f); + ++f.request.attempt_no; + decode(&f); + CHECK(decoder_engine_reset_session(f.engine) == DECODER_OK); + decode(&f); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + decoder_engine_test_legacy_isolation(); + CHECK(decoder_engine_destroy(f.engine) == DECODER_OK); + CHECK(decoder_engine_create(&options, &f.engine) == DECODER_OK); + prepare(&f, DECODER_MODE_FT4, "CQ K1JT FN20", 0.452f); + decode(&f); + CHECK(decoder_engine_destroy(f.engine) == DECODER_OK); + decoder_engine_test_gui_codec(); + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt65.c b/tests/unit/decoder_engine/test_decoder_engine_jt65.c new file mode 100644 index 00000000..2ac6b363 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt65.c @@ -0,0 +1,578 @@ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#include "DecoderEngine.h" +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#ifdef __linux__ +#include +#endif + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +enum { SAMPLE_COUNT = 720000 }; +extern void decoder_engine_test_jt65_signal(int submode, int kind, int seed, int16_t *samples); + +typedef struct { + decoder_engine_handle engine; + decoder_attempt_request request; + decoder_audio_view audio; + int16_t *samples, *before; + int count, messages, sync_only, max_average, polarity, method, ap_type; + int expected_kind, seen; + decoder_observation last_message; +} fixture; + +static void observe(const decoder_observation *record, void *opaque) +{ + fixture *f = opaque; + CHECK(record->input_id == f->request.input_id); + CHECK(record->analysis_id == f->request.analysis_id); + CHECK(record->attempt_no == f->request.attempt_no); + CHECK(record->mode == DECODER_MODE_JT65); + CHECK(record->variant == f->request.jt65.submode); + CHECK(isfinite(record->sync) && isfinite(record->dt_seconds)); + CHECK(record->ft8.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->superfox.kind == 0); + CHECK(record->jt65.has_width == f->request.jt65.vhf); + CHECK(isfinite(record->jt65.width_hz)); + CHECK(record->jt65.has_drift == (record->jt65.sync_polarity != 0)); + CHECK(isfinite(record->jt65.drift_hz)); + if (!record->jt65.has_drift) CHECK(record->jt65.drift_hz == 0.0f); + if (!record->jt65.has_width) CHECK(record->jt65.width_hz == 0.0f); + ++f->count; + if (record->jt65.kind == DECODER_JT65_MESSAGE) { + const char *expected = "K1ABC W9XYZ FN42"; + int bit = 1; + float frequency = 1500.0f; + if (f->expected_kind >= 3 && f->expected_kind <= 5) { + const char *shorthand[] = {"RO", "RRR", "73"}; + expected = shorthand[f->expected_kind - 3]; + CHECK(record->jt65.method == DECODER_JT65_METHOD_NONE); + CHECK(!record->jt65.has_drift); + } else { + CHECK(record->jt65.method > 0); + if (f->expected_kind == 6 && !strcmp(record->message, "K2DEF N0XYZ EM00")) { + expected = "K2DEF N0XYZ EM00"; + frequency = 2100.0f; + bit = 2; + } + } + if (strcmp(record->message, expected)) + fprintf(stderr, "input %lld attempt %d samples %d kind %d frequency %.1f message [%s] expected [%s]\n", + (long long)f->request.input_id, f->request.attempt_no, f->audio.sample_count, + f->expected_kind, record->frequency_hz, record->message, expected); + CHECK(!strcmp(record->message, expected)); + CHECK(!(f->seen & bit)); + f->seen |= bit; + f->last_message = *record; + CHECK(fabsf(record->frequency_hz - frequency) <= 4.0f); + if (f->expected_kind < 3 || f->expected_kind > 5) + CHECK(fabsf(record->dt_seconds) <= 1.0f); + ++f->messages; + if (record->jt65.average_count > f->max_average) f->max_average = record->jt65.average_count; + f->polarity = record->jt65.sync_polarity; + f->method = record->jt65.method; + f->ap_type = record->ap_type; + } else { + CHECK(record->jt65.kind == DECODER_JT65_SYNC); + CHECK(record->message[0] == '\0'); + CHECK(record->jt65.method == 0); + ++f->sync_only; + } + CHECK(decoder_engine_release_input(f->engine, record->input_id) == DECODER_BUSY); + CHECK(decoder_engine_clear_jt65_averages(f->engine) == DECODER_BUSY); + CHECK(decoder_engine_set_jt65_calls(f->engine, NULL, 0) == DECODER_BUSY); +} + +static void initialize_request(fixture *f, int submode, int kind, int utc) +{ + static int64_t next_id = 100; + memset(&f->request, 0, sizeof f->request); + f->request.input_id = ++next_id; + f->request.analysis_id = next_id; + f->request.attempt_no = 1; + f->request.mode = DECODER_MODE_JT65; + f->request.phase = DECODER_PHASE_NORMAL; + f->request.source = DECODER_SOURCE_FILE; + f->request.jt65.utc = utc; + f->request.jt65.qso_progress = 5; + f->request.jt65.receive_frequency_hz = 1500; + f->request.jt65.search_low_hz = 1300; + f->request.jt65.search_high_hz = 1700; + f->request.jt65.tolerance_hz = 100; + f->request.jt65.depth = 1; + f->request.jt65.submode = submode; + f->request.jt65.passes = 1; + f->request.jt65.trials = 1000; + f->request.jt65.aggressiveness = 5; + f->request.jt65.single_decode = 1; + memcpy(f->request.jt65.mycall, "K1ABC ", 12); + memcpy(f->request.jt65.hiscall, "W9XYZ ", 12); + memcpy(f->request.jt65.hisgrid, "FN42 ", 6); + f->expected_kind = kind; + f->audio.sample_count = SAMPLE_COUNT; + f->audio.sample_rate_hz = 12000; +} + +static void prepare(fixture *f, int submode, int kind, int utc) +{ + initialize_request(f, submode, kind, utc); + decoder_engine_test_jt65_signal(submode, kind, utc, f->samples); +} + +static void decode(fixture *f, int expect_message) +{ + decoder_attempt_outcome outcome; + memcpy(f->before, f->samples, SAMPLE_COUNT * sizeof *f->samples); + f->count = f->messages = f->sync_only = f->max_average = f->polarity = f->method = 0; + f->ap_type = f->seen = 0; + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_OK); + CHECK(outcome.status == DECODER_OK && outcome.observation_count == f->count); + CHECK(outcome.evidence_dropped == 0); + CHECK(!memcmp(f->before, f->samples, SAMPLE_COUNT * sizeof *f->samples)); + if (!!f->messages != !!expect_message) { + fprintf(stderr, "JT65%c input %lld attempt %d: %d messages, %d sync observations, expected message %d\n", + 'A' + f->request.jt65.submode, (long long)f->request.input_id, + f->request.attempt_no, f->messages, f->sync_only, expect_message); + } + CHECK(!!f->messages == !!expect_message); +} + +static int average_count(fixture *f) +{ + decoder_jt65_average_entry entries[64]; + int32_t count, queried; + CHECK(decoder_engine_get_jt65_averages(f->engine, NULL, 0, &queried) == DECODER_OK); + CHECK(decoder_engine_get_jt65_averages(f->engine, entries, 64, &count) == DECODER_OK); + CHECK(count == queried && count >= 0 && count <= 64); + for (int i = 0; i < count; ++i) { + CHECK(isfinite(entries[i].sync) && isfinite(entries[i].dt_seconds)); + CHECK(abs(entries[i].frequency_hz - 1500) <= 5); + } + if (count > 1) { + CHECK(decoder_engine_get_jt65_averages(f->engine, entries, 1, &queried) == DECODER_CAPACITY); + CHECK(queried == count); + } + return count; +} + +static void release(fixture *f) +{ + CHECK(decoder_engine_release_input(f->engine, f->request.input_id) == DECODER_OK); +} + +static void weak_reception(fixture *f, int utc) +{ + prepare(f, 0, 2, utc); + f->request.jt65.vhf = 1; + f->request.jt65.averaging = 1; +} + +static void create_fixture(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + decoder_engine_capabilities capabilities; + f->samples = malloc(SAMPLE_COUNT * sizeof *f->samples); + f->before = malloc(SAMPLE_COUNT * sizeof *f->before); + CHECK(f->samples && f->before); + f->audio.samples = f->samples; + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + CHECK(decoder_engine_get_capabilities(f->engine, &capabilities) == DECODER_OK); + CHECK(capabilities.supported_modes & DECODER_SUPPORT_JT65); +} + +static void check_lifecycle_and_destroy(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + CHECK(average_count(f) == 0); + prepare(f, 0, 0, 9); + decode(f, 1); + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + prepare(f, 0, 0, 11); + decode(f, 1); + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + free(f->before); + free(f->samples); +} + +static void run_smoke(void) +{ + fixture f = {0}; + create_fixture(&f); + prepare(&f, 0, 0, 1); + decode(&f, 1); + release(&f); + check_lifecycle_and_destroy(&f); +} + +static void run_tests(void) +{ + decoder_attempt_outcome outcome; + fixture f = {0}; + create_fixture(&f); + + prepare(&f, 0, 0, 1); + f.request.jt65.single_decode = 0; + f.request.jt65.aggressiveness = 0; + f.request.jt65.ap_enabled = 1; + f.request.jt65.qso_progress = 0; + memset(f.request.jt65.mycall, ' ', sizeof f.request.jt65.mycall); + memset(f.request.jt65.hiscall, ' ', sizeof f.request.jt65.hiscall); + memset(f.request.jt65.hisgrid, ' ', sizeof f.request.jt65.hisgrid); + decode(&f, 1); + release(&f); + + for (int gap = 0; gap < 3; ++gap) { + prepare(&f, 0, 0, gap + 1); + f.request.jt65.single_decode = 0; + f.request.jt65.search_low_hz = 200; + f.request.jt65.search_high_hz = 2600; + f.request.jt65.tolerance_hz = 1000; + f.request.jt65.ap_enabled = 1; + f.request.jt65.qso_progress = 0; + if (gap == 0) f.audio.sample_count = 40 * 12000; + if (gap == 1) memset(f.samples + 40 * 12000, 0, (SAMPLE_COUNT - 40 * 12000) * sizeof *f.samples); + if (gap == 2) memset(f.samples + 20 * 12000, 0, 5 * 12000 * sizeof *f.samples); + decode(&f, 0); + CHECK(f.count == 0); + release(&f); + } + + for (int submode = 0; submode <= 2; ++submode) { + prepare(&f, submode, 0, 1); + decode(&f, 1); + if (submode == 0) { + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + decode(&f, 1); + /* The unused caller storage remains decodable; only its prefix is borrowed. */ + f.audio.sample_count = 1; + f.samples[0] = 0; + ++f.request.attempt_no; + decode(&f, 0); + CHECK(f.count == 0); + f.samples[0] = 1000; + ++f.request.attempt_no; + decode(&f, 0); + CHECK(f.count == 0); + f.audio.sample_count = 9600; + ++f.request.attempt_no; + decode(&f, 0); + CHECK(f.count == 0); + } + release(&f); + } + + prepare(&f, 0, 0, 1); + f.request.jt65.vhf = 1; + f.request.jt65.trials = 100; + f.request.jt65.receive_frequency_hz = 2300; + f.request.jt65.search_low_hz = 2200; + f.request.jt65.search_high_hz = 2400; + decode(&f, 0); + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + f.request.jt65.receive_frequency_hz = 1500; + f.request.jt65.search_low_hz = 1300; + f.request.jt65.search_high_hz = 1700; + decode(&f, 1); + decoder_observation retained = f.last_message; + release(&f); + CHECK(decoder_engine_reset_session(f.engine) == DECODER_OK); + prepare(&f, 0, 0, 1); + f.request.jt65.vhf = 1; + f.request.jt65.trials = 100; + decode(&f, 1); + CHECK(!strcmp(retained.message, f.last_message.message)); + CHECK(fabsf(retained.frequency_hz - f.last_message.frequency_hz) <= 0.5f); + CHECK(fabsf(retained.dt_seconds - f.last_message.dt_seconds) <= 0.05f); + CHECK(retained.jt65.method == f.last_message.jt65.method); + release(&f); + + for (int kind = 3; kind <= 5; ++kind) { + prepare(&f, 0, kind, 1); + f.request.jt65.vhf = 1; + decode(&f, 1); + CHECK(f.messages == 1); + release(&f); + } + + prepare(&f, 0, 6, 1); + f.request.jt65.aggressiveness = 0; + f.request.jt65.vhf = 1; + f.request.jt65.tolerance_hz = 1000; + f.request.jt65.passes = 2; + f.request.jt65.trials = 100; + f.request.jt65.single_decode = 0; + f.request.jt65.search_high_hz = 2200; + decode(&f, 1); + CHECK(f.messages == 2 && f.seen == 3); + /* VHF repeats search at the selected receive frequency. */ + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + decode(&f, 1); + CHECK(f.messages == 1 && f.seen == 1); + release(&f); + prepare(&f, 0, 6, 3); + f.request.jt65.aggressiveness = 0; + f.request.jt65.vhf = 1; + f.request.jt65.tolerance_hz = 1000; + f.request.jt65.passes = 2; + f.request.jt65.trials = 100; + f.request.jt65.single_decode = 0; + f.request.jt65.search_high_hz = 2200; + decode(&f, 1); + CHECK(f.messages == 2 && f.seen == 3); + release(&f); + + prepare(&f, 0, 1, 1); + f.request.jt65.vhf = 1; + decode(&f, 1); + CHECK(f.polarity < 0); + release(&f); + prepare(&f, 0, 0, 1); + decode(&f, 1); + release(&f); + + prepare(&f, 0, 0, 1); + f.audio.sample_count = 45 * 12000; + decode(&f, 0); + CHECK(f.count == 0); + release(&f); + prepare(&f, 0, 0, 1); + memset(f.samples + 20 * 12000, 0, 1200 * sizeof *f.samples); + decode(&f, 0); + CHECK(f.count == 0); + release(&f); + + CHECK(decoder_engine_clear_jt65_averages(f.engine) == DECODER_OK); + weak_reception(&f, 1); + int64_t reused_input_id = f.request.input_id; + decode(&f, 0); + CHECK(f.sync_only > 0 && average_count(&f) == 1); + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + decode(&f, 0); + CHECK(average_count(&f) == 1); + CHECK(decoder_engine_clear_jt65_averages(f.engine) == DECODER_OK); + CHECK(average_count(&f) == 0); + ++f.request.attempt_no; + decode(&f, 0); + CHECK(average_count(&f) == 1); + release(&f); + CHECK(average_count(&f) == 1); + weak_reception(&f, 2); + decode(&f, 0); + CHECK(average_count(&f) == 2); + release(&f); + weak_reception(&f, 3); + f.request.input_id = reused_input_id; + decode(&f, 1); + CHECK(f.max_average == 2 && average_count(&f) == 3); + decoder_jt65_average_entry selected[64]; + int32_t selected_count; + CHECK(decoder_engine_get_jt65_averages(f.engine, selected, 64, &selected_count) == DECODER_OK); + CHECK(selected_count == 3); + CHECK(selected[0].utc == 1 && selected[0].used); + CHECK(selected[1].utc == 2 && !selected[1].used); + CHECK(selected[2].utc == 3 && selected[2].used); + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + decode(&f, 0); + CHECK(average_count(&f) == 3); + release(&f); + + prepare(&f, 1, 0, 5); + f.request.jt65.vhf = 1; + decode(&f, 1); + CHECK(average_count(&f) == 0); + release(&f); + weak_reception(&f, 1); + decode(&f, 0); + CHECK(average_count(&f) == 1); + release(&f); + prepare(&f, 0, 0, 5); + decode(&f, 1); + CHECK(average_count(&f) == 0); + release(&f); + + weak_reception(&f, 1); + f.request.jt65.auto_clear = 1; + decode(&f, 0); + release(&f); + weak_reception(&f, 3); + f.request.jt65.auto_clear = 1; + decode(&f, 1); + CHECK(f.max_average >= 2); + release(&f); + weak_reception(&f, 5); + f.request.jt65.auto_clear = 1; + decode(&f, 0); + CHECK(average_count(&f) == 1); + release(&f); + + decoder_jt65_call calls[1]; + memcpy(calls[0].call, "W9XYZ ", 12); + memcpy(calls[0].grid, "FN42", 4); + CHECK(decoder_engine_set_jt65_calls(f.engine, calls, 1) == DECODER_OK); + memset(calls, 0, sizeof calls); + CHECK(decoder_engine_set_jt65_calls(f.engine, NULL, 1) == DECODER_INVALID); + weak_reception(&f, 1); + f.request.jt65.averaging = 0; + f.request.jt65.deep_search = 1; + memset(f.request.jt65.hiscall, ' ', sizeof f.request.jt65.hiscall); + memset(f.request.jt65.hisgrid, ' ', sizeof f.request.jt65.hisgrid); + decode(&f, 1); + CHECK(f.method == 2); + memcpy(calls[0].call, "N0CALL ", 12); + memcpy(calls[0].grid, "EM00", 4); + CHECK(decoder_engine_set_jt65_calls(f.engine, calls, 1) == DECODER_OK); + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + decode(&f, 0); + CHECK(decoder_engine_set_jt65_calls(f.engine, NULL, 0) == DECODER_OK); + release(&f); + + weak_reception(&f, 3); + f.request.jt65.averaging = 0; + f.request.jt65.ap_enabled = 1; + f.request.jt65.qso_progress = 1; + decode(&f, 1); + CHECK(f.method == 1 && f.ap_type > 0); + release(&f); + + initialize_request(&f, 0, 0, 7); + memset(f.samples, 0, SAMPLE_COUNT * sizeof *f.samples); + f.request.phase = DECODER_PHASE_EARLY; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.request.phase = DECODER_PHASE_NORMAL; + f.audio.sample_count = SAMPLE_COUNT + 1; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.audio.sample_count = SAMPLE_COUNT; + const int32_t trial_limits[] = {-1, 0, 1000000, 1000001, INT32_MAX}; + for (unsigned i = 0; i < sizeof trial_limits / sizeof *trial_limits; ++i) { + f.request.jt65.trials = trial_limits[i]; + if (trial_limits[i] >= 0 && trial_limits[i] <= 1000000) { + decode(&f, 0); + CHECK(f.count == 0); + release(&f); + } else { + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + CHECK(outcome.status == DECODER_INVALID && outcome.observation_count == 0); + } + } + check_lifecycle_and_destroy(&f); +} + +static void write_le(FILE *file, uint32_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; ++i) CHECK(fputc((value >> (8 * i)) & 255, file) != EOF); +} + +static void write_wav(const char *path) +{ + int16_t *samples = malloc(SAMPLE_COUNT * sizeof *samples); + CHECK(samples); + decoder_engine_test_jt65_signal(0, 0, 1, samples); + FILE *file = fopen(path, "wb"); + CHECK(file); + CHECK(fwrite("RIFF", 1, 4, file) == 4); + write_le(file, 36 + SAMPLE_COUNT * 2, 4); + CHECK(fwrite("WAVEfmt ", 1, 8, file) == 8); + write_le(file, 16, 4); + write_le(file, 1, 2); + write_le(file, 1, 2); + write_le(file, 12000, 4); + write_le(file, 24000, 4); + write_le(file, 2, 2); + write_le(file, 16, 2); + CHECK(fwrite("data", 1, 4, file) == 4); + write_le(file, SAMPLE_COUNT * 2, 4); + for (int i = 0; i < SAMPLE_COUNT; ++i) write_le(file, (uint16_t)samples[i], 2); + CHECK(fclose(file) == 0); + free(samples); +} + +#ifdef _WIN32 +static DWORD WINAPI run_on_small_stack(LPVOID unused) +#else +static void *run_on_small_stack(void *unused) +#endif +{ + (void)unused; + run_tests(); + return 0; +} + +#ifdef __linux__ +static int add_tls_size(struct dl_phdr_info *info, size_t size, void *opaque) +{ + (void)size; + size_t *stack_size = opaque; + for (int i = 0; i < info->dlpi_phnum; ++i) { + const ElfW(Phdr) *header = &info->dlpi_phdr[i]; + if (header->p_type == PT_TLS) *stack_size += header->p_memsz + header->p_align; + } + return 0; +} +#endif + +int main(int argc, char **argv) +{ + if (argc == 3 && !strcmp(argv[1], "--write-wav")) { + write_wav(argv[2]); + } else if (argc == 2 && !strcmp(argv[1], "--smoke")) { + run_smoke(); + } else if (argc == 1) { + run_tests(); + } else { + CHECK(argc == 2 && !strcmp(argv[1], "--small-stack")); +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 1024 * 1024, run_on_small_stack, NULL, + STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); + CHECK(thread != NULL); + CHECK(WaitForSingleObject(thread, INFINITE) == WAIT_OBJECT_0); + DWORD status; + CHECK(GetExitCodeThread(thread, &status) && status == 0); + CHECK(CloseHandle(thread)); +#else + pthread_attr_t attributes; + pthread_t thread; + size_t stack_size = 1024 * 1024; +#ifdef __linux__ + /* Linux puts static TLS in the stack mapping; reserve 1 MiB for calls. */ + dl_iterate_phdr(add_tls_size, &stack_size); +#endif + CHECK(pthread_attr_init(&attributes) == 0); + CHECK(pthread_attr_setstacksize(&attributes, stack_size) == 0); + int error = pthread_create(&thread, &attributes, run_on_small_stack, NULL); + if (error) fprintf(stderr, "pthread_create with %zu bytes: %s\n", stack_size, strerror(error)); + CHECK(error == 0); + CHECK(pthread_attr_destroy(&attributes) == 0); + CHECK(pthread_join(thread, NULL) == 0); +#endif + } + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt65_host.f90 b/tests/unit/decoder_engine/test_decoder_engine_jt65_host.f90 new file mode 100644 index 00000000..f2aa8609 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt65_host.f90 @@ -0,0 +1,190 @@ +program test_decoder_engine_jt65_host + use iso_c_binding, only: c_int,c_int8_t,c_int16_t,c_int64_t,c_sizeof + use decoder_engine, only: engine_host_decode + use ft8_engine_kernel, only: params_block + use decode_completion_module, only: decode_completion_result + use prog_args, only: data_dir,temp_dir + implicit none + type(params_block) :: params,before_params + type(decode_completion_result) :: completion + integer(c_int8_t) :: zeros(c_sizeof(params)) + integer(c_int16_t), allocatable, target :: samples(:) + integer(c_int16_t), allocatable :: before_samples(:) + integer(c_int64_t) :: input_id=1000,analysis_id=1000 + integer :: unit,attempt=1 + interface + subroutine make_signal(submode,kind,seed,samples) bind(C,name='decoder_engine_test_jt65_signal') + import c_int,c_int16_t + integer(c_int), value :: submode,kind,seed + integer(c_int16_t), intent(out) :: samples(720000) + end subroutine + end interface + allocate(samples(720000),before_samples(720000)) + data_dir='.' + temp_dir='.' + zeros=0 + params=transfer(zeros,params) + params%nmode=65 + params%ntr=60 + params%ndiskdat=.true. + params%newdat=.true. + params%nfqso=1500 + params%nfa=1400 + params%nfb=1600 + params%ntol=100 + params%n2pass=1 + params%nranera=6 + params%naggressive=5 + params%nQSOProgress=5 + params%mycall=transfer('K1ABC ',params%mycall) + params%hiscall=transfer('W9XYZ ',params%hiscall) + params%hisgrid=transfer('FN42 ',params%hisgrid) + params%nexp_decode=32+64 + params%ndepth=1+16 + params%nclearave=.true. + + call reception(1) + call run(0,'first weak reception') + call averages(1,1,0) + params%nclearave=.false. + params%nagain=.true. + call run(0,'repeat does not add an average') + call averages(1,1,0) + params%nclearave=.true. + call run(0,'clear and repeat add only the current reception') + call averages(1,1,0) + params%nclearave=.false. + + call reception(2) + call run(0,'opposite parity does not recover') + call averages(2,0,1) + call reception(3) + call run(1,'averaging packed flag recovers message') + call output_has('K1ABC W9XYZ FN42',1,2,.true.) + call averages(3,2,0) + params%nclearave=.true. + params%ndepth=1 + call reception(5) + call run(0,'averaging disabled control') + call averages(0,0,0) + params%nclearave=.false. + + params%ljt65apon=.true. + params%nQSOProgress=1 + call reception(3) + call run(1,'AP flag recovers weak message') + call output_has('K1ABC W9XYZ FN42',-1,1,.true.) + params%ljt65apon=.false. + call reception(3) + call run(0,'AP disabled control') + call output_has('K1ABC W9XYZ FN42',0,0,.false.) + + params%nQSOProgress=5 + params%hiscall=' ' + params%hisgrid=' ' + open(newunit=unit,file='CALL3.TXT',status='replace') + write(unit,'(a)') 'W9XYZ,FN42,,' + close(unit) + params%ndepth=1+32 + call reception(1) + call run(1,'deep-search packed flag loads caller file') + call output_has('K1ABC W9XYZ FN42',2,1,.true.) + params%ndepth=1 + call reception(1) + call run(0,'deep search disabled control') + params%ndepth=1+32 + open(newunit=unit,file='CALL3.TXT',status='replace') + write(unit,'(a)') 'N0CALL,EM00,,' + close(unit) + call reception(1) + call run(0,'different caller file does not recover target') + deallocate(samples,before_samples) + print '(a)', 'JT65 host adapter tests passed' +contains + subroutine require(condition,description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if(.not.condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine + + subroutine reception(utc) + integer, intent(in) :: utc + input_id=input_id+1 + params%nutc=utc + params%nagain=.false. + attempt=0 + call make_signal(0,2,utc,samples) + end subroutine + + subroutine run(messages,description) + integer, intent(in) :: messages + character(len=*), intent(in) :: description + ! The compatibility writer appends repeats; isolate each attempt's output. + open(newunit=unit,file='decoded.txt',status='replace') + close(unit) + before_params=params + before_samples=samples + attempt=attempt+1 + analysis_id=analysis_id+1 + call engine_host_decode(samples,params,12000,completion,0,input_id,analysis_id,attempt,size(samples)) + call require(completion%available,description//' completion available') + call require(completion%decoded==messages,description//' decoded count') + call require(all(samples==before_samples),description//' immutable PCM') + call require(all(transfer(params,zeros)==transfer(before_params,zeros)),description//' immutable options') + end subroutine + + subroutine output_has(message,method,periods,expected) + character(len=*), intent(in) :: message + integer, intent(in) :: method,periods + logical, intent(in) :: expected + character(len=256) :: line + integer :: ios,matches,ft,nsum,nsmo,start + matches=0 + open(newunit=unit,file='decoded.txt',status='old',action='read') + do + read(unit,'(a)',iostat=ios) line + if(ios/=0) exit + if(index(line,message)>0) then + matches=matches+1 + start=index(line,' JT65') + call require(start>0,'legacy result mode') + read(line(start+5:),*) ft,nsum,nsmo + if(method<0) then + call require(ft>3,'legacy AP qualifier') + else + call require(ft==method,'legacy decoding method') + endif + call require(nsum==periods,'legacy averaging qualifier') + endif + enddo + close(unit) + call require(matches==merge(1,0,expected),'current attempt decoded output') + end subroutine + + subroutine averages(expected,odd_used,even_used) + integer, intent(in) :: expected,odd_used,even_used + character(len=100) :: line + integer :: ios,count,utc,odd,even + count=0 + odd=0 + even=0 + open(newunit=unit,file='avemsg.txt',status='old',action='read') + do + read(unit,'(a)',iostat=ios) line + if(ios/=0) exit + count=count+1 + read(line(2:6),'(i5)') utc + call require(utc==count,'legacy average reception UTC') + if(line(1:1)=='$') then + if(mod(utc,2)==1) odd=odd+1 + if(mod(utc,2)==0) even=even+1 + endif + enddo + close(unit) + call require(count==expected,'legacy average history count') + call require(odd==odd_used.and.even==even_used,'legacy selected averaging periods') + end subroutine +end program test_decoder_engine_jt65_host diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt9.c b/tests/unit/decoder_engine/test_decoder_engine_jt9.c new file mode 100644 index 00000000..955f1498 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt9.c @@ -0,0 +1,361 @@ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#include "DecoderEngine.h" +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#ifdef __linux__ +#include +#endif + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +enum { SAMPLE_COUNT = 720000 }; +extern void decoder_engine_test_jt9_signal(int submode, int start_sample, float spread_hz, + float frequency_hz, int16_t *samples); +extern void decoder_engine_test_jt9_reference(int submode, int windowed, const int16_t *samples, float result[4]); + +typedef struct { + decoder_engine_handle engine; + decoder_attempt_request request; + decoder_audio_view audio; + int16_t *samples, *before; + int count, found, compare_reference, check_dt; + float reference[4], expected_dt, expected_frequency, frequency_tolerance; +} fixture; + +static void observe(const decoder_observation *record, void *opaque) +{ + fixture *f = opaque; + CHECK(record->input_id == f->request.input_id); + CHECK(record->analysis_id == f->request.analysis_id); + CHECK(record->attempt_no == f->request.attempt_no); + CHECK(record->mode == DECODER_MODE_JT9); + CHECK(record->variant == f->request.jt9.submode); + CHECK(record->message[0] != '\0' && record->message[0] != ' '); + CHECK(isfinite(record->sync) && isfinite(record->dt_seconds)); + CHECK(record->ft8.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->superfox.kind == 0); + ++f->count; + if (!strcmp(record->message, "CQ K1JT FN20")) { + ++f->found; + if (fabsf(record->frequency_hz - f->expected_frequency) >= f->frequency_tolerance) { + fprintf(stderr, "JT9%c input %lld attempt %d: frequency %.6f Hz, expected %.3f +/- %.3f Hz\n", + 'A' + f->request.jt9.submode, (long long)f->request.input_id, + f->request.attempt_no, record->frequency_hz, f->expected_frequency, + f->frequency_tolerance); + } + CHECK(fabsf(record->frequency_hz - f->expected_frequency) < f->frequency_tolerance); + if (f->check_dt) CHECK(fabsf(record->dt_seconds - f->expected_dt) < 0.1f); + CHECK(record->jt9.has_drift == (f->request.jt9.submode == 0)); + CHECK(isfinite(record->jt9.drift_hz_per_minute)); + if (record->jt9.has_drift) CHECK(fabsf(record->jt9.drift_hz_per_minute) < 2.0f); + if (f->compare_reference) { + /* FFT layout roundoff is amplified by wide-mode sync normalization. */ + const float sync_tolerance = 0.001f + 0.0001f * fabsf(f->reference[2]); + if (fabsf(record->sync - f->reference[2]) >= sync_tolerance) { + fprintf(stderr, "JT9%c input %lld attempt %d: sync %.9g, reference %.9g, difference %.9g, tolerance %.9g\n", + 'A' + f->request.jt9.submode, (long long)f->request.input_id, + f->request.attempt_no, record->sync, f->reference[2], + record->sync - f->reference[2], sync_tolerance); + } + CHECK(fabsf(record->frequency_hz - f->reference[0]) < 0.001f); + CHECK(fabsf(record->dt_seconds - f->reference[1]) < 0.001f); + CHECK(fabsf(record->sync - f->reference[2]) < sync_tolerance); + CHECK(record->snr_db == (int)f->reference[3]); + } + } + CHECK(decoder_engine_release_input(f->engine, record->input_id) == DECODER_BUSY); +} + +static void prepare(fixture *f, int submode) +{ + static int64_t next_id = 100; + memset(&f->request, 0, sizeof f->request); + f->request.input_id = ++next_id; + f->request.analysis_id = next_id; + f->request.attempt_no = 1; + f->request.mode = DECODER_MODE_JT9; + f->request.phase = DECODER_PHASE_NORMAL; + f->request.source = DECODER_SOURCE_FILE; + f->request.jt9.utc = 1200; + f->request.jt9.receive_frequency_hz = 1000; + f->request.jt9.search_low_hz = 900; + f->request.jt9.search_high_hz = 1100; + f->request.jt9.tolerance_hz = 20; + f->request.jt9.depth = 3; + f->request.jt9.submode = submode; + f->audio.sample_count = SAMPLE_COUNT; + f->audio.sample_rate_hz = 12000; + f->compare_reference = 0; + f->check_dt = 0; + f->frequency_tolerance = 3.0f; + f->expected_frequency = 1000.0f; + decoder_engine_test_jt9_signal(submode, 12000, 0.0f, f->expected_frequency, f->samples); +} + +static int decode(fixture *f, int expect_message) +{ + decoder_attempt_outcome outcome; + memcpy(f->before, f->samples, SAMPLE_COUNT * sizeof *f->samples); + f->count = f->found = 0; + CHECK(feclearexcept(FE_ALL_EXCEPT) == 0); + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_OK); + if (fetestexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW)) { + fprintf(stderr, "JT9%c input %lld attempt %d: floating-point exception at %.3f Hz\n", + 'A' + f->request.jt9.submode, (long long)f->request.input_id, + f->request.attempt_no, f->expected_frequency); + } + CHECK(fetestexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW) == 0); + CHECK(outcome.status == DECODER_OK && outcome.observation_count == f->count); + CHECK(outcome.retained_count >= f->count && outcome.evidence_dropped == 0); + CHECK(!memcmp(f->before, f->samples, SAMPLE_COUNT * sizeof *f->samples)); + if (expect_message > 0 && !f->found) { + fprintf(stderr, "Missing JT9%c message (input %lld, attempt %d, observations %d)\n", + 'A' + f->request.jt9.submode, (long long)f->request.input_id, + f->request.attempt_no, f->count); + } + if (expect_message > 0) CHECK(f->found > 0); + else CHECK(f->count == 0); + return outcome.retained_count; +} + +static void create_fixture(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + f->samples = malloc(SAMPLE_COUNT * sizeof *f->samples); + f->before = malloc(SAMPLE_COUNT * sizeof *f->before); + CHECK(f->samples && f->before); + f->audio.samples = f->samples; + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); +} + +static void check_lifecycle_and_destroy(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + decode(f, 1); + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + decode(f, 1); + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + prepare(f, 7); + decode(f, 1); + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + free(f->before); + free(f->samples); +} + +static void run_smoke(void) +{ + fixture f = {0}; + create_fixture(&f); + prepare(&f, 0); + check_lifecycle_and_destroy(&f); +} + +static void run_tests(void) +{ + decoder_attempt_outcome outcome; + fixture f = {0}; + create_fixture(&f); + + for (int submode = 0; submode <= 7; ++submode) { + prepare(&f, submode); + if (submode == 0 || submode == 7) { + float windowed[4]; + decoder_engine_test_jt9_reference(submode, 1, f.samples, windowed); + decoder_engine_test_jt9_reference(submode, 0, f.samples, f.reference); + f.compare_reference = 1; + } + decode(&f, 1); + f.compare_reference = 0; + if (submode == 0 || submode == 7) { + f.request.phase = DECODER_PHASE_REPEAT; + ++f.request.analysis_id; + ++f.request.attempt_no; + f.request.jt9.receive_frequency_hz = 1005; + f.request.jt9.search_low_hz = 950; + f.request.jt9.search_high_hz = 1150; + int retained = decode(&f, 1); + + /* Decodable storage beyond the borrowed prefix must not reach the decoder. */ + f.audio.sample_count = 1; + f.samples[0] = 0; + ++f.request.attempt_no; + CHECK(decode(&f, 0) == retained); + f.audio.sample_count = SAMPLE_COUNT; + memset(f.samples, 0, SAMPLE_COUNT * sizeof *f.samples); + ++f.request.attempt_no; + CHECK(decode(&f, 0) == retained); + } + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + + prepare(&f, 7); + decoder_engine_test_jt9_signal(7, 18000, 3.0f, f.expected_frequency, f.samples); + f.check_dt = 1; + f.expected_dt = 0.45f; + decode(&f, 1); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + const int spectrum_rows[] = {173, 179, 181}; + for (size_t i = 0; i < sizeof spectrum_rows / sizeof *spectrum_rows; ++i) { + prepare(&f, 7); + decoder_engine_test_jt9_signal(7, 18000, 3.0f, f.expected_frequency, f.samples); + f.audio.sample_count = spectrum_rows[i] * 3456 + 2048; + f.check_dt = 1; + f.expected_dt = 0.45f; + decode(&f, 1); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + + const int tolerances[] = {1, 2, 5}; + for (size_t i = 0; i < sizeof tolerances / sizeof *tolerances; ++i) { + prepare(&f, 7); + f.request.jt9.tolerance_hz = tolerances[i]; + f.frequency_tolerance = 0.5f; + f.check_dt = 1; + f.expected_dt = -0.05f; + decode(&f, 1); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + + const float boundary_frequencies[] = {999.2f, 1000.8f, 998.8f, 1001.2f}; + for (size_t i = 0; i < sizeof boundary_frequencies / sizeof *boundary_frequencies; ++i) { + prepare(&f, 7); + f.expected_frequency = boundary_frequencies[i]; + decoder_engine_test_jt9_signal(7, 12000, 0.0f, f.expected_frequency, f.samples); + f.request.jt9.tolerance_hz = 1; + f.frequency_tolerance = 0.2f; + f.check_dt = 1; + f.expected_dt = -0.05f; + decode(&f, fabsf(f.expected_frequency - f.request.jt9.receive_frequency_hz) < 1.0f); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + + const int excluded_frequencies[] = {0, 1010, 4999}; + for (size_t i = 0; i < sizeof excluded_frequencies / sizeof *excluded_frequencies; ++i) { + prepare(&f, 7); + f.request.jt9.receive_frequency_hz = excluded_frequencies[i]; + f.request.jt9.tolerance_hz = 5; + decode(&f, 0); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + + prepare(&f, 0); + f.request.jt9.depth = 1; + memset(f.samples, 0, 16 * 12000 * sizeof *f.samples); + decode(&f, 1); + CHECK(f.count == 1 && f.found == 1); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + for (int submode = 0; submode <= 7; submode += 7) { + prepare(&f, submode); + f.audio.sample_count = 45 * 12000; + decode(&f, 1); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + prepare(&f, submode); + memset(f.samples + 20 * 12000, 0, 1200 * sizeof *f.samples); + decode(&f, 1); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + prepare(&f, submode); + for (int i = 0; i < SAMPLE_COUNT; ++i) f.samples[i] = 2; + decode(&f, 0); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + } + prepare(&f, 7); + f.request.jt9.receive_frequency_hz = 3500; + f.request.jt9.search_low_hz = 3400; + f.request.jt9.search_high_hz = 3600; + decode(&f, 0); + CHECK(decoder_engine_release_input(f.engine, f.request.input_id) == DECODER_OK); + + prepare(&f, 0); + f.request.phase = DECODER_PHASE_EARLY; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.request.phase = DECODER_PHASE_NORMAL; + f.audio.sample_count = SAMPLE_COUNT + 1; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.audio.sample_count = SAMPLE_COUNT; + check_lifecycle_and_destroy(&f); +} + +#ifdef _WIN32 +static DWORD WINAPI run_on_small_stack(LPVOID unused) +#else +static void *run_on_small_stack(void *unused) +#endif +{ + (void)unused; + run_tests(); + return 0; +} + +#ifdef __linux__ +static int add_tls_size(struct dl_phdr_info *info, size_t size, void *opaque) +{ + (void)size; + size_t *stack_size = opaque; + for (int i = 0; i < info->dlpi_phnum; ++i) { + const ElfW(Phdr) *header = &info->dlpi_phdr[i]; + if (header->p_type == PT_TLS) + *stack_size += header->p_memsz + header->p_align; + } + return 0; +} +#endif + +int main(int argc, char **argv) +{ + /* FFTW threading must be initialized before creating any plans. */ + CHECK(fftwf_init_threads() != 0); + if (argc == 2 && !strcmp(argv[1], "--smoke")) { + run_smoke(); + } else if (argc == 1) { + run_tests(); + } else { + CHECK(argc == 2 && !strcmp(argv[1], "--small-stack")); +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 1024 * 1024, run_on_small_stack, NULL, + STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); + CHECK(thread != NULL); + CHECK(WaitForSingleObject(thread, INFINITE) == WAIT_OBJECT_0); + DWORD status; + CHECK(GetExitCodeThread(thread, &status) && status == 0); + CHECK(CloseHandle(thread)); +#else + pthread_attr_t attributes; + pthread_t thread; + size_t stack_size = 1024 * 1024; +#ifdef __linux__ + /* Linux puts static TLS in the stack mapping; reserve 1 MiB for calls. */ + dl_iterate_phdr(add_tls_size, &stack_size); +#endif + CHECK(pthread_attr_init(&attributes) == 0); + CHECK(pthread_attr_setstacksize(&attributes, stack_size) == 0); + int error = pthread_create(&thread, &attributes, run_on_small_stack, NULL); + if (error) fprintf(stderr, "pthread_create with %zu bytes: %s\n", stack_size, strerror(error)); + CHECK(error == 0); + CHECK(pthread_attr_destroy(&attributes) == 0); + CHECK(pthread_join(thread, NULL) == 0); +#endif + } + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_q65.c b/tests/unit/decoder_engine/test_decoder_engine_q65.c new file mode 100644 index 00000000..a8c4e955 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_q65.c @@ -0,0 +1,535 @@ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#include "DecoderEngine.h" +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#ifdef __linux__ +#include +#endif + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +enum { SAMPLE_CAPACITY = 300 * 12000 }; +extern void decoder_engine_test_q65_signal(int, int, int, int, float, float, float, int16_t *); +extern void decoder_engine_test_q65_message(const char *, int, int, int, int, float, float, float, int16_t *); + +typedef struct { + decoder_engine_handle engine; + decoder_attempt_request request; + decoder_audio_view audio; + int16_t *samples, *before; + int count, bit78, max_average, method; + const char *expected[2]; + float frequencies[2]; + int seen[2]; + char message[38]; +} fixture; + +static void observe(const decoder_observation *record, void *opaque) +{ + fixture *f = opaque; + CHECK(record->input_id == f->request.input_id); + CHECK(record->analysis_id == f->request.analysis_id); + CHECK(record->attempt_no == f->request.attempt_no); + CHECK(record->mode == DECODER_MODE_Q65); + CHECK(record->variant == f->request.q65.submode); + CHECK(record->q65.period_seconds == f->request.q65.period_seconds); + CHECK(record->q65.recovered_bit78 == f->bit78); + CHECK(record->q65.method >= 0); + CHECK(record->q65.average_count >= 1); + CHECK(isfinite(record->sync) && isfinite(record->dt_seconds)); + CHECK(record->ft8.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_NONE); + int candidate = 0; + if (f->expected[0]) { + while (candidate < 2 && (!f->expected[candidate] || + strcmp(record->message, f->expected[candidate]))) ++candidate; + if (candidate == 2) fprintf(stderr, "unexpected Q65 message [%s]\n", record->message); + CHECK(candidate < 2); + } + CHECK(!f->seen[candidate]++); + CHECK(fabsf(record->frequency_hz - f->frequencies[candidate]) <= 10.0f); + snprintf(f->message, sizeof f->message, "%s", record->message); + CHECK(fabsf(record->dt_seconds) <= 0.3f); + ++f->count; + if (record->q65.average_count > f->max_average) f->max_average = record->q65.average_count; + f->method = record->q65.method; + CHECK(decoder_engine_release_input(f->engine, record->input_id) == DECODER_BUSY); + CHECK(decoder_engine_clear_q65_averages(f->engine) == DECODER_BUSY); + CHECK(decoder_engine_set_q65_callers(f->engine, NULL, 0) == DECODER_BUSY); +} + +static void initialize_request(fixture *f, int period, int submode, int utc, int bit78) +{ + static int64_t next_id = 200; + memset(&f->request, 0, sizeof f->request); + f->request.input_id = ++next_id; + f->request.analysis_id = next_id; + f->request.attempt_no = 1; + f->request.mode = DECODER_MODE_Q65; + f->request.phase = DECODER_PHASE_NORMAL; + f->request.source = DECODER_SOURCE_FILE; + f->request.q65.utc = utc; + f->request.q65.period_seconds = period; + f->request.q65.submode = submode; + f->request.q65.receive_frequency_hz = 1000; + f->request.q65.tolerance_hz = 50; + f->request.q65.search_low_hz = 850; + f->request.q65.search_high_hz = 1150; + f->request.q65.depth = 1; + f->request.q65.single_decode = 1; + f->request.q65.extended_eme_search = 1; + f->request.q65.now_seconds = 1700000000; + memset(f->request.q65.mycall, ' ', sizeof f->request.q65.mycall); + memset(f->request.q65.hiscall, ' ', sizeof f->request.q65.hiscall); + memset(f->request.q65.hisgrid, ' ', sizeof f->request.q65.hisgrid); + f->bit78 = bit78; + f->expected[0] = "K1ABC W9XYZ FN42"; + f->expected[1] = NULL; + f->frequencies[0] = 1000.0f; + f->audio.sample_count = period * 12000; + f->audio.sample_rate_hz = 12000; +} + +static void prepare(fixture *f, int period, int submode, int utc, int bit78) +{ + initialize_request(f, period, submode, utc, bit78); + decoder_engine_test_q65_signal(period, submode, bit78, utc + 1, 300.0f, 100.0f, 1000.0f, f->samples); +} + +static void decode(fixture *f, int expect_message) +{ + decoder_attempt_outcome outcome; + decoder_attempt_request before_request = f->request; + size_t bytes = f->audio.sample_count * sizeof *f->samples; + memcpy(f->before, f->samples, bytes); + f->count = f->max_average = 0; + memset(f->seen, 0, sizeof f->seen); + memset(f->message, 0, sizeof f->message); + f->method = -1; + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_OK); + CHECK(outcome.status == DECODER_OK && outcome.observation_count == f->count); + CHECK(outcome.evidence_dropped == 0); + CHECK(!memcmp(&before_request, &f->request, sizeof before_request)); + CHECK(!memcmp(f->before, f->samples, bytes)); + if (expect_message >= 0) { + if (!!f->count != !!expect_message) + fprintf(stderr, "Q65-%d%c UTC %06d attempt %d: got %d messages, expected %d\n", + f->request.q65.period_seconds, 'A' + f->request.q65.submode, + f->request.q65.utc, f->request.attempt_no, f->count, expect_message); + CHECK(!!f->count == !!expect_message); + } +} + +static void counts(fixture *f, int even, int odd) +{ + decoder_q65_snapshot snapshot; + CHECK(decoder_engine_get_q65_snapshot(f->engine, &snapshot, NULL, NULL, 0) == DECODER_OK); + if (snapshot.even_count != even || snapshot.odd_count != odd) + fprintf(stderr, "Q65 averages: got %d/%d, expected %d/%d\n", + snapshot.even_count, snapshot.odd_count, even, odd); + CHECK(snapshot.even_count == even && snapshot.odd_count == odd); + CHECK(snapshot.curve_count >= 0); + if (snapshot.curve_count) { + float *instant = malloc(snapshot.curve_count * sizeof *instant); + float *averaged = malloc(snapshot.curve_count * sizeof *averaged); + CHECK(instant && averaged); + CHECK(decoder_engine_get_q65_snapshot(f->engine, &snapshot, instant, averaged, snapshot.curve_count) == DECODER_OK); + for (int i = 0; i < snapshot.curve_count; ++i) CHECK(isfinite(instant[i]) && isfinite(averaged[i])); + free(instant); + free(averaged); + } +} + +static void release(fixture *f) +{ + CHECK(decoder_engine_release_input(f->engine, f->request.input_id) == DECODER_OK); +} + +static void repeat(fixture *f) +{ + f->request.phase = DECODER_PHASE_REPEAT; + ++f->request.analysis_id; + ++f->request.attempt_no; +} + +static void signal_message(fixture *f, const char *message, int seed, float amplitude, + float noise, float frequency, int16_t *samples) +{ + char padded[37]; + CHECK(strlen(message) <= sizeof padded); + memset(padded, ' ', sizeof padded); + memcpy(padded, message, strlen(message)); + decoder_engine_test_q65_message(padded, f->request.q65.period_seconds, + f->request.q65.submode, f->bit78, seed, + amplitude, noise, frequency, samples); +} + +static void retained_options(fixture *f) +{ + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 15, 0, 0, 0); + f->request.q65.receive_frequency_hz = 1500; + f->request.q65.search_low_hz = 1450; + f->request.q65.search_high_hz = 1550; + decode(f, 0); + repeat(f); + f->request.q65.receive_frequency_hz = 1000; + f->request.q65.search_low_hz = 950; + f->request.q65.search_high_hz = 1050; + decode(f, 1); + CHECK(f->count == 1); + int method = f->method; + release(f); + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 15, 0, 0, 0); + f->request.q65.search_low_hz = 950; + f->request.q65.search_high_hz = 1050; + decode(f, 1); + CHECK(f->count == 1 && f->method == method); + release(f); +} + +static void knowledge_lifetime(fixture *f) +{ + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + initialize_request(f, 15, 0, 0, 0); + f->expected[0] = "CQ PJ4/K1ABC"; + signal_message(f, "CQ PJ4/K1ABC", 1, 300, 100, 1000, f->samples); + decode(f, 1); + release(f); + initialize_request(f, 15, 0, 15, 0); + f->expected[0] = " W9XYZ -10"; + signal_message(f, " W9XYZ -10", 2, 300, 100, 1000, f->samples); + decode(f, 1); + CHECK(f->count == 1); + release(f); + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + initialize_request(f, 15, 0, 15, 0); + f->expected[0] = NULL; + signal_message(f, " W9XYZ -10", 2, 300, 100, 1000, f->samples); + decode(f, -1); + CHECK(!strstr(f->message, "PJ4/K1ABC")); + int reset_count = f->count; + char reset_message[sizeof f->message]; + memcpy(reset_message, f->message, sizeof reset_message); + release(f); + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + decoder_engine_options options = {DECODER_ENGINE_ABI}; + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + initialize_request(f, 15, 0, 15, 0); + f->expected[0] = NULL; + signal_message(f, " W9XYZ -10", 2, 300, 100, 1000, f->samples); + decode(f, -1); + CHECK(f->count == reset_count && !strcmp(f->message, reset_message)); + release(f); +} + +static void contest_retries(fixture *f) +{ + decoder_q65_caller callers[2] = { + {"W9XYZ ", "FN42", 1700000000, 1000}, + {"K9XYZ ", "EN50", 1700000000, 1250} + }; + for (int control = 0; control < 5; ++control) { + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + initialize_request(f, 60, 0, 10000, 0); + f->request.q65.contest = 1; + f->request.q65.receive_frequency_hz = 1500; + f->request.q65.search_high_hz = 1350; + f->request.q65.single_decode = 0; + f->request.q65.qso_progress = 5; + memcpy(f->request.q65.mycall, "K1ABC ", 12); + f->expected[1] = "K1ABC K9XYZ EN50"; + f->frequencies[1] = 1250; + signal_message(f, f->expected[0], 1, 3.0f, 100, 1000, f->samples); + signal_message(f, f->expected[1], 2, 3.0f, 0, 1250, f->before); + for (int i = 0; i < f->audio.sample_count; ++i) f->samples[i] += f->before[i]; + if (control == 1 || control == 2) + CHECK(decoder_engine_set_q65_callers(f->engine, callers + control - 1, 1) == DECODER_OK); + if (control >= 3) + CHECK(decoder_engine_set_q65_callers(f->engine, callers, 2) == DECODER_OK); + if (control == 4) f->request.phase = DECODER_PHASE_REPEAT; + decode(f, control >= 1 && control <= 3); + CHECK(f->count == (control == 3 ? 2 : control >= 1 && control <= 2)); + CHECK(f->seen[0] == (control == 1 || control == 3)); + CHECK(f->seen[1] == (control == 2 || control == 3)); + if (f->count) CHECK(f->method == 3 && f->max_average == 1); + counts(f, control == 4 ? 0 : 1, 0); + release(f); + } +} + +static void create_fixture(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + decoder_engine_capabilities capabilities; + f->samples = malloc(SAMPLE_CAPACITY * sizeof *f->samples); + f->before = malloc(SAMPLE_CAPACITY * sizeof *f->before); + CHECK(f->samples && f->before); + f->audio.samples = f->samples; + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + CHECK(decoder_engine_get_capabilities(f->engine, &capabilities) == DECODER_OK); + CHECK(capabilities.supported_modes & DECODER_SUPPORT_Q65); +} + +static void check_recreate_and_destroy(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + prepare(f, 15, 0, 0, 0); + decode(f, 1); + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + free(f->before); + free(f->samples); +} + +static void run_smoke(void) +{ + fixture f = {0}; + create_fixture(&f); + prepare(&f, 15, 0, 0, 0); + decode(&f, 1); + counts(&f, 1, 0); + release(&f); + CHECK(decoder_engine_reset_session(f.engine) == DECODER_OK); + counts(&f, 0, 0); + prepare(&f, 15, 0, 0, 0); + decode(&f, 1); + release(&f); + check_recreate_and_destroy(&f); +} + +static void run_tests(void) +{ + decoder_attempt_outcome outcome; + fixture f = {0}; + create_fixture(&f); + + decoder_q65_caller caller = {"W9XYZ ", "FN42", 1700000000, 1000}; + decoder_q65_caller copied; + int32_t caller_count; + CHECK(decoder_engine_set_q65_callers(f.engine, &caller, 1) == DECODER_OK); + memset(&caller, 0, sizeof caller); + CHECK(decoder_engine_get_q65_callers(f.engine, NULL, 0, &caller_count) == DECODER_OK); + CHECK(caller_count == 1); + CHECK(decoder_engine_get_q65_callers(f.engine, &copied, 1, &caller_count) == DECODER_OK); + CHECK(!memcmp(copied.call, "W9XYZ ", 12) && !memcmp(copied.grid, "FN42", 4)); + CHECK(copied.last_seen == 1700000000 && copied.frequency_hz == 1000); + CHECK(decoder_engine_set_q65_callers(f.engine, NULL, 1) == DECODER_INVALID); + CHECK(decoder_engine_set_q65_callers(f.engine, NULL, DECODER_Q65_CALL_CAPACITY + 1) == DECODER_INVALID); + + prepare(&f, 60, 0, 1500, 0); + decode(&f, 1); + counts(&f, 0, 1); + --f.audio.sample_count; + ++f.request.attempt_no; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + ++f.audio.sample_count; + int64_t reused_input_id = f.request.input_id; + repeat(&f); + decode(&f, 1); + counts(&f, 0, 1); + CHECK(decoder_engine_clear_q65_averages(f.engine) == DECODER_OK); + counts(&f, 0, 0); + repeat(&f); + decode(&f, 1); + counts(&f, 0, 0); + release(&f); + prepare(&f, 60, 0, 1700, 0); + f.request.input_id = reused_input_id; + decode(&f, 1); + counts(&f, 0, 1); + release(&f); + prepare(&f, 60, 0, 1800, 0); + decode(&f, 1); + counts(&f, 1, 1); + release(&f); + + prepare(&f, 15, 0, 0, 1); + f.request.q65.pileup = 1; + decode(&f, 1); + counts(&f, 1, 0); + release(&f); + + prepare(&f, 15, 0, 30, 0); + f.request.q65.auto_clear = 1; + decode(&f, 1); + counts(&f, 0, 0); + repeat(&f); + decode(&f, 1); + counts(&f, 0, 0); + release(&f); + + prepare(&f, 15, 1, 15, 0); + decode(&f, 1); + counts(&f, 0, 1); + release(&f); + CHECK(decoder_engine_reset_session(f.engine) == DECODER_OK); + counts(&f, 0, 0); + CHECK(decoder_engine_get_q65_callers(f.engine, NULL, 0, &caller_count) == DECODER_OK); + CHECK(caller_count == 0); + + for (int reception = 0; reception < 2; ++reception) { + initialize_request(&f, 60, 0, 10000 + reception * 200, 0); + f.request.q65.averaging = 1; + f.request.q65.auto_clear = 1; + decoder_engine_test_q65_signal(60, 0, 0, reception + 1, 3.8f, 100.0f, 1000.0f, f.samples); + decode(&f, reception == 1); + counts(&f, reception == 0 ? 1 : 0, 0); + if (reception == 1) { + decoder_q65_snapshot snapshot; + CHECK(f.max_average == 2); + CHECK(decoder_engine_get_q65_snapshot(f.engine, &snapshot, NULL, NULL, 0) == DECODER_OK); + CHECK(snapshot.curve_average_count == 2); + } + release(&f); + } + + contest_retries(&f); + + prepare(&f, 60, 0, 2000, 0); + f.audio.sample_count = 50 * 12000; + decode(&f, 1); + release(&f); + prepare(&f, 15, 0, 0, 0); + memset(f.samples + 5 * 12000, 0, 1200 * sizeof *f.samples); + decode(&f, 1); + release(&f); + + initialize_request(&f, 15, 0, 0, 0); + f.request.phase = DECODER_PHASE_EARLY; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.request.phase = DECODER_PHASE_NORMAL; + f.request.q65.search_high_hz = 5001; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.request.q65.search_high_hz = 1150; + f.request.q65.period_seconds = INT32_MAX; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.request.q65.period_seconds = 15; + f.audio.sample_count++; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_INVALID); + f.audio.sample_count = 1; + f.samples[0] = 0; + decode(&f, 0); + release(&f); + + retained_options(&f); + knowledge_lifetime(&f); + prepare(&f, 120, 5, 0, 0); + decode(&f, 1); + CHECK(f.count == 1); + release(&f); + + prepare(&f, 300, 0, 0, 0); + decode(&f, 1); + release(&f); + check_recreate_and_destroy(&f); +} + +static void write_le(FILE *file, uint32_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; ++i) CHECK(fputc((value >> (8 * i)) & 255, file) != EOF); +} + +static void write_wav(const char *path, int period) +{ + CHECK(period == 15 || period == 60); + const int count = period * 12000; + int16_t *samples = malloc(count * sizeof *samples); + CHECK(samples); + decoder_engine_test_q65_signal(period, 0, 0, 1, 300.0f, 100.0f, 1500.0f, samples); + FILE *file = fopen(path, "wb"); + CHECK(file); + CHECK(fwrite("RIFF", 1, 4, file) == 4); + write_le(file, 36 + count * 2, 4); + CHECK(fwrite("WAVEfmt ", 1, 8, file) == 8); + write_le(file, 16, 4); + write_le(file, 1, 2); + write_le(file, 1, 2); + write_le(file, 12000, 4); + write_le(file, 24000, 4); + write_le(file, 2, 2); + write_le(file, 16, 2); + CHECK(fwrite("data", 1, 4, file) == 4); + write_le(file, count * 2, 4); + for (int i = 0; i < count; ++i) write_le(file, (uint16_t)samples[i], 2); + CHECK(fclose(file) == 0); + free(samples); +} + +#ifdef _WIN32 +static DWORD WINAPI run_on_small_stack(LPVOID unused) +#else +static void *run_on_small_stack(void *unused) +#endif +{ + (void)unused; + run_tests(); + return 0; +} + +#ifdef __linux__ +static int add_tls_size(struct dl_phdr_info *info, size_t size, void *opaque) +{ + (void)size; + size_t *stack_size = opaque; + for (int i = 0; i < info->dlpi_phnum; ++i) { + const ElfW(Phdr) *header = &info->dlpi_phdr[i]; + if (header->p_type == PT_TLS) *stack_size += header->p_memsz + header->p_align; + } + return 0; +} +#endif + +int main(int argc, char **argv) +{ + if ((argc == 3 || argc == 4) && !strcmp(argv[1], "--write-wav")) { + write_wav(argv[2], argc == 4 ? atoi(argv[3]) : 15); + } else if (argc == 2 && !strcmp(argv[1], "--smoke")) { + run_smoke(); + } else if (argc == 1) { + run_tests(); + } else { + CHECK(argc == 2 && !strcmp(argv[1], "--small-stack")); +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 1024 * 1024, run_on_small_stack, NULL, + STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); + CHECK(thread != NULL); + CHECK(WaitForSingleObject(thread, INFINITE) == WAIT_OBJECT_0); + DWORD status; + CHECK(GetExitCodeThread(thread, &status) && status == 0); + CHECK(CloseHandle(thread)); +#else + pthread_attr_t attributes; + pthread_t thread; + size_t stack_size = 1024 * 1024; +#ifdef __linux__ + /* Linux puts static TLS in the stack mapping; reserve 1 MiB for calls. */ + dl_iterate_phdr(add_tls_size, &stack_size); +#endif + CHECK(pthread_attr_init(&attributes) == 0); + CHECK(pthread_attr_setstacksize(&attributes, stack_size) == 0); + int error = pthread_create(&thread, &attributes, run_on_small_stack, NULL); + if (error) fprintf(stderr, "pthread_create with %zu bytes: %s\n", stack_size, strerror(error)); + CHECK(error == 0); + CHECK(pthread_attr_destroy(&attributes) == 0); + CHECK(pthread_join(thread, NULL) == 0); +#endif + } + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_q65_host.f90 b/tests/unit/decoder_engine/test_decoder_engine_q65_host.f90 new file mode 100644 index 00000000..c46eea53 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_q65_host.f90 @@ -0,0 +1,236 @@ +program test_decoder_engine_q65_host + use iso_c_binding, only: c_int,c_int16_t,c_int64_t,c_float,c_int8_t,c_sizeof,c_loc,c_f_pointer + use iso_fortran_env, only: error_unit + use decoder_engine, only: engine_host_decode + use ft8_engine_kernel, only: params_block + use decode_completion_module, only: decode_completion_result + use prog_args, only: data_dir,temp_dir + use q65_callers, only: Q65_MAX_CALLERS,q65_load_callers,q65_save_callers + use types, only: q3list + implicit none + integer, parameter :: sample_count=60*12000 + integer(c_int16_t), allocatable, target :: samples(:),before(:) + type(params_block), target :: params + type(decode_completion_result) :: completion + integer(c_int8_t), pointer :: parameter_bytes(:) + integer(c_int8_t), allocatable :: saved_parameters(:) + type(q3list), allocatable :: callers(:) + integer(c_int64_t) :: input_id=0,analysis_id=0 + integer :: attempt=0,status,count,now + character(len=16) :: scenario + + interface + subroutine signal(period,submode,flag,seed,amplitude,noise,frequency,samples) & + bind(C,name='decoder_engine_test_q65_signal') + import c_int,c_int16_t,c_float + integer(c_int), value :: period,submode,flag,seed + real(c_float), value :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(*) + end subroutine + end interface + + allocate(samples(sample_count),before(sample_count),callers(Q65_MAX_CALLERS)) + call c_f_pointer(c_loc(params),parameter_bytes,[int(c_sizeof(params))]) + allocate(saved_parameters(size(parameter_bytes))) + parameter_bytes=0 + data_dir='.' + temp_dir='.' + params%nmode=66 + params%ntr=60 + params%nfqso=1000 + params%nfa=850 + params%nfb=1150 + params%ntol=50 + params%ndepth=17 + params%nexp_decode=32 + params%emedelay=1 + params%ndiskdat=.true. + params%mycall=' ' + params%hiscall=' ' + params%hisgrid=' ' + call remove_file('tsil.3q') + + call get_command_argument(1,scenario) + select case(trim(scenario)) + case('') + call check_averaging() + case('--contest') + call check_contest_history() + case default + error stop 'unknown host test scenario' + end select + + deallocate(samples,before,callers,saved_parameters) + +contains + + subroutine check_averaging() + integer(c_int16_t), allocatable :: fixtures(:,:) + integer :: seed + + allocate(fixtures(sample_count,4)) + do seed=1,3 + call signal(60,0,0,seed,3.8,100.0,1000.0,fixtures(:,seed)) + enddo + call signal(60,0,0,4,300.0,100.0,1000.0,fixtures(:,4)) + call fresh(10000,fixtures(:,1),.true.) + call decode(0,1000) + call repeat() + call decode(0,1000) + call fresh(10200,fixtures(:,2),.false.) + params%lbandchanged=.true. + call decode(1,2000,.true.) + params%lbandchanged=.false. + call fresh(10300,fixtures(:,3),.false.) + call decode(0,2001) + call repeat() + params%nclearave=.true. + call decode(0,0) + params%nclearave=.false. + + params%ndepth=145 + call fresh(10400,fixtures(:,4),.false.) + call decode(1,0) + call repeat() + call decode(1,0) + call fresh(10600,fixtures(:,1),.true.) + call decode(0,1000) + params%lmodechanged=.true. + call fresh(10800,fixtures(:,2),.false.) + call decode(1,0) + params%lmodechanged=.false. + + params%ndepth=1 + call fresh(11000,fixtures(:,1),.true.) + call decode(0,1000) + call fresh(11200,fixtures(:,2),.false.) + call decode(0,2000) + end subroutine + + subroutine check_contest_history() + integer(c_int16_t), allocatable :: fixture(:) + + allocate(fixture(sample_count)) + call signal(60,0,0,1,3.0,100.0,1000.0,fixture) + params%ndepth=1 + params%nexp_decode=1 + params%nQSOProgress=5 + params%nfqso=1500 + params%mycall=transfer('K1ABC ',params%mycall) + call fresh(11400,fixture,.true.) + call decode(0,1000) + callers=q3list('','',0,0,0) + now=time() + callers(1)=q3list('W9XYZ','FN42',now-3600,1000,0) + call q65_save_callers('tsil.3q',callers,1,status) + call expect(status==0,'seed contest caller history') + call fresh(11600,fixture,.true.) + call decode(1,1000) + call expect(file_contains('host-output.txt','q3'),'contest history enables list-decode retry') + call q65_load_callers('tsil.3q',callers,count,status) + call expect(status==0.and.count==1,'contest history persists one caller') + call expect(callers(1)%call=='W9XYZ'.and.callers(1)%grid=='FN42','contest caller survives host round trip') + call expect(callers(1)%nsec>=now.and.abs(callers(1)%nfreq-1000)<=10,'successful decode refreshes caller history') + end subroutine + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if(condition) return + write(error_unit,'(a)') message + error stop 1 + end subroutine + + subroutine fresh(utc,fixture,clear_averages) + integer, intent(in) :: utc + integer(c_int16_t), intent(in) :: fixture(:) + logical, intent(in) :: clear_averages + input_id=input_id+1 + analysis_id=analysis_id+1 + attempt=1 + params%nutc=utc + params%nagain=.false. + params%newdat=.true. + params%nclearave=clear_averages + samples=fixture + before=fixture + end subroutine + + subroutine repeat() + analysis_id=analysis_id+1 + attempt=attempt+1 + params%nagain=.true. + params%newdat=.false. + params%nclearave=.false. + end subroutine + + subroutine decode(messages,averages,require_average) + integer, intent(in) :: messages,averages + logical, intent(in), optional :: require_average + logical :: check_average + + check_average=.false. + if(present(require_average)) check_average=require_average + saved_parameters=parameter_bytes + call remove_file('decoded.txt') + call remove_file('red.dat') + open(unit=6,file='host-output.txt',status='replace') + call engine_host_decode(samples,params,12000,completion,0,input_id,analysis_id,attempt,sample_count) + close(6) + call expect(all(before==samples),'host leaves supplied PCM unchanged') + call expect(all(saved_parameters==parameter_bytes),'host leaves packed parameters unchanged') + call expect(completion%available,'host reports completion') + if(completion%decoded/=messages.or.completion%average/=averages) then + write(error_unit,'(a,i6.6,4(a,i0))') 'UTC ',params%nutc,': decoded ',completion%decoded, & + ' expected ',messages,' averages ',completion%average,' expected ',averages + error stop 1 + endif + call expect(file_contains('decoded.txt','K1ABC W9XYZ FN42').eqv.(messages>0),'current legacy decoded output') + call expect(file_contains('host-output.txt','K1ABC W9XYZ FN42').eqv.(messages>0),'current GUI decode line') + call check_curves(check_average) + end subroutine + + subroutine check_curves(require_average) + logical, intent(in) :: require_average + integer :: unit,ios,rows + real :: x,average,current,maximum + open(newunit=unit,file='red.dat',status='old',iostat=ios) + call expect(ios==0,'host writes synchronization curves') + read(unit,*,iostat=ios) x,average,current + call expect(ios==0,'curve header is readable') + rows=0 + maximum=0 + do + read(unit,*,iostat=ios) x,average,current + if(ios/=0) exit + rows=rows+1 + maximum=max(maximum,average) + call expect(x>=850.and.x<=1155,'curve frequency range follows request') + enddo + close(unit) + call expect(rows>0,'host writes nonempty curve data') + if(require_average) call expect(maximum>0,'two-reception average is visible in red curve') + end subroutine + + logical function file_contains(filename,text) result(found) + character(len=*), intent(in) :: filename,text + integer :: unit,ios + character(len=512) :: line + found=.false. + open(newunit=unit,file=filename,status='old',iostat=ios) + if(ios/=0) return + do + read(unit,'(a)',iostat=ios) line + if(ios/=0) exit + if(index(line,text)>0) found=.true. + enddo + close(unit) + end function + + subroutine remove_file(filename) + character(len=*), intent(in) :: filename + integer :: unit,ios + open(newunit=unit,file=filename,status='old',iostat=ios) + if(ios==0) close(unit,status='delete') + end subroutine +end program diff --git a/tests/unit/decoder_ipc/CMakeLists.txt b/tests/unit/decoder_ipc/CMakeLists.txt index 0d8c0083..a7e46c4d 100644 --- a/tests/unit/decoder_ipc/CMakeLists.txt +++ b/tests/unit/decoder_ipc/CMakeLists.txt @@ -10,28 +10,36 @@ add_executable (test_decoder_ipc_protocol test_decoder_ipc_protocol.cpp ${decoder_ipc_fortran_probe_sources} ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp - ${CMAKE_SOURCE_DIR}/lib/decoder_ipc_control.cpp ) set_target_properties (test_decoder_ipc_protocol PROPERTIES LINKER_LANGUAGE CXX) target_include_directories (test_decoder_ipc_protocol PRIVATE ${CMAKE_SOURCE_DIR}/lib) +target_compile_definitions (test_decoder_ipc_protocol PRIVATE + JT9_TEST_EXECUTABLE="$") +add_dependencies (test_decoder_ipc_protocol jt9) if (APPLE) - target_link_libraries (test_decoder_ipc_protocol Qt5::Test test_decoder_ipc_fortran_probe) + target_link_libraries (test_decoder_ipc_protocol wsjt_cxx Qt5::Test test_decoder_ipc_fortran_probe) else () - target_link_libraries (test_decoder_ipc_protocol Qt5::Test) + target_link_libraries (test_decoder_ipc_protocol wsjt_cxx Qt5::Test) endif () add_test (NAME test_decoder_ipc_protocol COMMAND test_decoder_ipc_protocol) +add_executable (test_decoder_session + test_decoder_session.cpp + ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp +) +target_link_libraries (test_decoder_session wsjt_cxx Qt5::Test) +add_test (NAME test_decoder_session COMMAND test_decoder_session) + add_executable (test_decoder_output_framer test_decoder_output_framer.cpp ${CMAKE_SOURCE_DIR}/DecoderOutputFramer.cpp ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp - ${CMAKE_SOURCE_DIR}/lib/decoder_ipc_control.cpp ) target_include_directories (test_decoder_output_framer PRIVATE ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/lib ) -target_link_libraries (test_decoder_output_framer Qt5::Test) +target_link_libraries (test_decoder_output_framer wsjt_cxx Qt5::Test) add_test (NAME test_decoder_output_framer COMMAND test_decoder_output_framer) add_executable (test_decode_operating_context @@ -40,3 +48,28 @@ add_executable (test_decode_operating_context target_include_directories (test_decode_operating_context PRIVATE ${CMAKE_SOURCE_DIR}) target_link_libraries (test_decode_operating_context Qt5::Test) add_test (NAME test_decode_operating_context COMMAND test_decode_operating_context) + +add_library (test_decoder_ipc_fortran_layout STATIC + ${CMAKE_SOURCE_DIR}/lib/decoder_ipc_layout.f90) +file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/layout-modules) +set_target_properties (test_decoder_ipc_fortran_layout PROPERTIES + Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/layout-modules) +target_include_directories (test_decoder_ipc_fortran_layout PRIVATE ${CMAKE_SOURCE_DIR}/lib) +add_executable (test_decoder_ipc_layout + test_decoder_ipc_layout.cpp + ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp +) +target_link_libraries (test_decoder_ipc_layout wsjt_cxx Qt5::Test test_decoder_ipc_fortran_layout) +add_test (NAME test_decoder_ipc_layout COMMAND test_decoder_ipc_layout) + +add_executable (test_decoder_ipc_handshake + test_decoder_ipc_handshake.cpp + ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp +) +target_link_libraries (test_decoder_ipc_handshake wsjt_cxx Qt5::Test) +target_compile_definitions (test_decoder_ipc_handshake PRIVATE + DECODER_IPC_JT9="$" + DECODER_IPC_SOURCE="${CMAKE_SOURCE_DIR}") +add_dependencies (test_decoder_ipc_handshake jt9) +add_test (NAME test_decoder_ipc_handshake COMMAND test_decoder_ipc_handshake) +set_tests_properties (test_decoder_ipc_handshake PROPERTIES TIMEOUT 90) diff --git a/tests/unit/decoder_ipc/check_gui_handshake.py b/tests/unit/decoder_ipc/check_gui_handshake.py new file mode 100644 index 00000000..93230b29 --- /dev/null +++ b/tests/unit/decoder_ipc/check_gui_handshake.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Exercise GUI startup rejection with isolated decoder substitutes on macOS.""" + +import argparse +import os +from pathlib import Path +import shutil +import signal +import subprocess +import time + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("bundle", type=Path) + parser.add_argument("output", type=Path) + parser.add_argument("--signer", type=Path) + args = parser.parse_args() + source = Path(__file__).resolve().parents[3] + root = args.output.resolve() / str(os.getpid()) + root.mkdir(parents=True) + cases = { + "missing": ("", "within five seconds"), + "version": (" version=2", "incompatible or unexpected"), + "malformed": (" version=3 extra", "malformed or out-of-order"), + } + for name, (reply, expected) in cases.items(): + directory = root / name + bundle = directory / "wsjtx.app" + shutil.copytree(args.bundle.resolve(), bundle, symlinks=True) + decoder = bundle / "Contents/MacOS/jt9" + decoder.unlink() + decoder.write_text("#!/bin/sh\n" + (f"echo '{reply}'\n" if reply else "") + + "exec /bin/sleep 20\n") + decoder.chmod(0o755) + if args.signer: + with (directory / "sign.log").open("w") as log: + subprocess.run([str(args.signer), str(bundle)], check=True, + stdout=log, stderr=subprocess.STDOUT) + command = [str(bundle / "Contents/MacOS/wsjtx"), "--live-audio-test", + str(source / "samples/FT8/210703_133430.wav"), + "--live-audio-expected", + str(source / "test/fixtures/ft8_210703_133430_mtd.expected.txt"), + "--live-audio-data-dir", str(source), + "--rig-name", f"IPC-{name}-{os.getpid()}"] + environment = dict(os.environ) + environment["WSJT_QMAP_SHARED_MEMORY_KEY"] = f"ipc-{name}-{os.getpid()}" + started = time.monotonic() + with (directory / "output.log").open("w+") as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, + env=environment, start_new_session=True) + try: + code = process.wait(timeout=18) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + raise RuntimeError(f"{name}: GUI did not fail promptly; see {log.name}") + elapsed = time.monotonic() - started + log.seek(0) + output = log.read() + if code == 0 or expected not in output: + raise RuntimeError(f"{name}: unexpected exit {code}; see {directory / 'output.log'}") + if name == "missing" and elapsed < 4.5: + raise RuntimeError("Missing handshake failed before the handshake deadline") + print(f"{name}: PASS, exit={code}, elapsed={elapsed:.2f}s, log={directory / 'output.log'}", + flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/decoder_ipc/decoder_ipc_fortran_probe.f90 b/tests/unit/decoder_ipc/decoder_ipc_fortran_probe.f90 index c1304ee7..a87e7716 100644 --- a/tests/unit/decoder_ipc/decoder_ipc_fortran_probe.f90 +++ b/tests/unit/decoder_ipc/decoder_ipc_fortran_probe.f90 @@ -3,7 +3,7 @@ subroutine decoder_ipc_fortran_probe(address, values) bind(C) include 'jt9com.f90' type(c_ptr), value :: address - integer(c_int), intent(out) :: values(10) + integer(c_int), intent(out) :: values(11) type(shared_dec_data), pointer :: shared call c_f_pointer(address, shared) @@ -17,7 +17,12 @@ subroutine decoder_ipc_fortran_probe(address, values) bind(C) values(8) = DECODER_IPC_DECODING values(9) = DECODER_IPC_COMPLETE values(10) = DECODER_IPC_SHUTDOWN + values(11) = c_sizeof(shared%metadata) shared%control%generation = shared%control%generation + 1 shared%payload%id2(1) = 1234 + shared%metadata%input_id = 12345678901_c_int64_t + shared%metadata%analysis_id = 12345678902_c_int64_t + shared%metadata%attempt_no = 3 + shared%metadata%valid_samples = 180000 end subroutine decoder_ipc_fortran_probe diff --git a/tests/unit/decoder_ipc/test_decode_operating_context.cpp b/tests/unit/decoder_ipc/test_decode_operating_context.cpp index 0380434d..f4233d94 100644 --- a/tests/unit/decoder_ipc/test_decode_operating_context.cpp +++ b/tests/unit/decoder_ipc/test_decode_operating_context.cpp @@ -9,6 +9,7 @@ class TestDecodeOperatingContext final : public QObject private Q_SLOTS: void identityMatchesEquivalentContext (); void sequenceStartIsAttributionOnly (); + void receiveRolloverPreservesPendingSnapshot (); void identityChangeMakesContextObsolete_data (); void identityChangeMakesContextObsolete (); void ft8PendingIdentityChangeMakesSnapshotObsolete_data (); @@ -62,6 +63,19 @@ void TestDecodeOperatingContext::sequenceStartIsAttributionOnly () QVERIFY (captured.hasSameDecodeIdentity (current)); } +void TestDecodeOperatingContext::receiveRolloverPreservesPendingSnapshot () +{ + auto captured = context (); + captured.inputId = 10; + captured.analysisId = 20; + auto current = captured; + ++current.inputId; + ++current.analysisId; + current.sequenceStart = current.sequenceStart.addSecs (15); + + QVERIFY (captured.hasSameFt8PendingIdentity (current)); +} + void TestDecodeOperatingContext::identityChangeMakesContextObsolete_data () { QTest::addColumn ("field"); diff --git a/tests/unit/decoder_ipc/test_decoder_ipc_handshake.cpp b/tests/unit/decoder_ipc/test_decoder_ipc_handshake.cpp new file mode 100644 index 00000000..d1ab0dbd --- /dev/null +++ b/tests/unit/decoder_ipc/test_decoder_ipc_handshake.cpp @@ -0,0 +1,603 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "DecoderIpc.hpp" +#include "lib/NativeSharedMemory.hpp" +#include "lib/DecoderWorkerLock.hpp" + +#ifndef Q_OS_WIN +#include +#include +#include +#endif +#ifdef Q_OS_LINUX +#include +#endif + +namespace +{ + QString lockPath (QString const& directory) + { + return directory + "/worker.lock"; + } + + class DecoderProcess : public QProcess + { + public: + ~DecoderProcess () override + { + if (state () != NotRunning) + { + kill (); + waitForFinished (5000); + } + } + void launch (QString const& key, QString const& directory) + { + start (QStringLiteral (DECODER_IPC_JT9), + {"--shmem", key, "--ipc-lock", lockPath (directory), "-w", "1", "-m", "1", "-e", directory, + "-a", directory, "-t", directory, "-r", QStringLiteral (DECODER_IPC_SOURCE)}); + } + bool waitForOutput (QByteArray const& marker, QByteArray& output) + { + auto completeLine = [&] { + auto const position = output.indexOf (marker); + return position >= 0 && output.indexOf ('\n', position) >= 0; + }; + QElapsedTimer timer; + timer.start (); + while (timer.elapsed () < 5000) + { + output += readAllStandardOutput (); + if (completeLine ()) return true; + if (state () == NotRunning) break; + waitForReadyRead (100); + } + output += readAllStandardOutput (); + return completeLine (); + } + }; + + QString uniqueKey () + { + return DecoderIpc::memoryName (QUuid::createUuid ().toString ()); + } +} + +class TestDecoderIpcHandshake final : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void readyBeforePublication (); + void rejectsSegment_data (); + void rejectsSegment (); + void staleNameRecovery_data (); + void staleNameRecovery (); + void mappingOwnership (); + void missingMappingFails (); + void replacementWorkerCompletesRequest (); + void simultaneousSessionsStayIsolated (); + void orphanLockLifetime_data (); + void orphanLockLifetime (); + void blockedWorkerPreservesFiles (); + void insufficientLinuxSharedMemory (); +}; + +void TestDecoderIpcHandshake::readyBeforePublication () +{ + using namespace DecoderIpc; + auto const key = uniqueKey (); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + QCOMPARE (session.open (key, lockPath (directory.path ())), Status::Ok); + auto source = std::make_unique (); + QCOMPARE (session.submit (Request::snapshot (*source)).status, Status::Unavailable); + DecoderProcess child; + child.launch (key, directory.path ()); + QVERIFY (child.waitForStarted (5000)); + QByteArray output; + QElapsedTimer timer; + timer.start (); + while (!output.contains ('\n') && timer.elapsed () < 5000) + { + child.waitForReadyRead (100); + output += child.readAllStandardOutput (); + if (child.state () == QProcess::NotRunning) break; + } + auto const ready = QByteArray {" version="} + QByteArray::number (DECODER_IPC_VERSION); + QVERIFY2 (output.startsWith (ready + "\r\n") + || output.startsWith (ready + "\n"), output.constData ()); + QVERIFY (!output.contains ("")); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + QVERIFY (session.ready ()); + session.shutdown (); + QVERIFY (child.waitForFinished (5000)); + output += child.readAllStandardOutput (); + QCOMPARE (child.exitStatus (), QProcess::NormalExit); + QCOMPARE (child.exitCode (), 0); + QVERIFY2 (!output.contains (""), output.constData ()); + QFile wisdom {directory.filePath ("jt9_wisdom.dat")}; + QVERIFY (wisdom.open (QIODevice::ReadOnly)); + auto const savedWisdom = wisdom.readAll (); + QVERIFY (savedWisdom.contains ("fftwf_wisdom")); + wisdom.close (); + QVERIFY (QFile::exists (directory.filePath ("timer.out"))); + + QVERIFY (session.reset ()); + child.launch (key, directory.path ()); + QVERIFY (child.waitForStarted (5000)); + output.clear (); + QVERIFY2 (child.waitForOutput ("", output), output.constData ()); + session.shutdown (); + QVERIFY (child.waitForFinished (5000)); + QCOMPARE (child.exitStatus (), QProcess::NormalExit); + QCOMPARE (child.exitCode (), 0); + QVERIFY (wisdom.open (QIODevice::ReadOnly)); + QCOMPARE (wisdom.readAll (), savedWisdom); +} + +void TestDecoderIpcHandshake::rejectsSegment_data () +{ + QTest::addColumn ("mutation"); + QTest::addColumn ("status"); + QTest::newRow ("v1") << QString {"v1"} << QByteArray {"unsupported-version"}; + QTest::newRow ("v2") << QString {"v2"} << QByteArray {"unsupported-version"}; + QTest::newRow ("v3") << QString {"v3"} << QByteArray {"unsupported-version"}; + QTest::newRow ("future-version") << QString {"v%1"}.arg (DECODER_IPC_VERSION + 1) + << QByteArray {"unsupported-version"}; + QTest::newRow ("header-size") << QString {"header"} << QByteArray {"wrong-header-size"}; + QTest::newRow ("payload-size") << QString {"payload"} << QByteArray {"wrong-payload-size"}; + QTest::newRow ("field-offset") << QString {"offset"} << QByteArray {"incompatible-layout"}; + QTest::newRow ("capabilities") << QString {"caps"} << QByteArray {"unsupported-capabilities"}; + QTest::newRow ("truncated") << QString {"truncated"} << QByteArray {"truncated-segment"}; +} + +void TestDecoderIpcHandshake::rejectsSegment () +{ + QFETCH (QString, mutation); + QFETCH (QByteArray, status); + auto const key = uniqueKey (); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QByteArray const sentinel {"existing decoder output\n"}; + for (auto const& name : {"timer.out", "jt9_wisdom.dat"}) + { + QFile file {directory.filePath (name)}; + QVERIFY (file.open (QIODevice::WriteOnly)); + QCOMPARE (file.write (sentinel), qint64 {sentinel.size ()}); + } + NativeSharedMemory memory; + bool const truncated = mutation == "truncated"; + QVERIFY2 (memory.create (key.toStdString (), truncated ? offsetof (shared_dec_data_t, payload) + : sizeof (shared_dec_data_t)), + memory.errorString ().c_str ()); + if (truncated) + { + auto * control = static_cast (memory.data ()); + *control = {1, DECODER_IPC_READY, DECODER_IPC_VERSION, 0}; + decoder_ipc_layout_t layout; + decoder_ipc_expected_layout (&layout); + std::memcpy (static_cast (memory.data ()) + + offsetof (shared_dec_data_t, layout), + &layout, sizeof layout); + } + else + { + auto& shared = *static_cast (memory.data ()); + DecoderIpc::initialize (shared); + shared.control.state = DECODER_IPC_READY; + shared.control.generation = 1; + if (mutation.startsWith ('v')) shared.control.version = mutation.mid (1).toInt (); + if (mutation == "header") ++shared.layout.header_bytes; + if (mutation == "payload") --shared.layout.payload_bytes; + if (mutation == "offset") ++shared.layout.fields[7].offset; + if (mutation == "caps") shared.layout.capabilities = 0; + } + QByteArray const before {static_cast (memory.data ()), static_cast (memory.size ())}; + DecoderProcess child; + child.launch (key, directory.path ()); + QVERIFY (child.waitForStarted (5000)); + QVERIFY (child.waitForFinished (5000)); + auto const output = child.readAllStandardOutput (); + QCOMPARE (child.exitStatus (), QProcess::NormalExit); + QCOMPARE (child.exitCode (), 1); + QVERIFY2 (output.contains (" status=" + status), output.constData ()); + QVERIFY (!output.contains ("")); + QVERIFY (!output.contains ("")); + QCOMPARE (std::memcmp (before.constData (), memory.data (), before.size ()), 0); + for (auto const& name : {"timer.out", "jt9_wisdom.dat"}) + { + QFile file {directory.filePath (name)}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.readAll (), sentinel); + } +} + +void TestDecoderIpcHandshake::staleNameRecovery_data () +{ + QTest::addColumn ("compatible"); + QTest::newRow ("compatible") << true; + QTest::newRow ("incompatible") << false; +} + +void TestDecoderIpcHandshake::staleNameRecovery () +{ + QFETCH (bool, compatible); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const key = uniqueKey (); + NativeSharedMemory memory; +#ifdef Q_OS_WIN + QVERIFY (memory.create (key.toStdString (), sizeof (shared_dec_data_t))); +#else + // A crashed creator leaves its name behind while decoder attachments stay alive. + auto const descriptor = shm_open (key.toStdString ().c_str (), O_CREAT | O_EXCL | O_RDWR, 0600); + QVERIFY (descriptor >= 0); + auto cleanup = qScopeGuard ([&] { NativeSharedMemory::remove (key.toStdString ()); }); + auto const resized = ftruncate (descriptor, sizeof (shared_dec_data_t)); + auto const closed = close (descriptor); + QCOMPARE (resized, 0); + QCOMPARE (closed, 0); + auto const attached = memory.attach (key.toStdString ()); + QVERIFY2 (attached, memory.errorString ().c_str ()); +#endif + auto& shared = *static_cast (memory.data ()); + DecoderIpc::initialize (shared); + shared.payload.d2[0] = 41; + if (!compatible) shared.control.version = 2; + QByteArray const before {static_cast (memory.data ()), static_cast (memory.size ())}; + DecoderIpc::Session session; +#ifdef Q_OS_WIN + QCOMPARE (session.open (key, lockPath (directory.path ())), DecoderIpc::Status::Orphaned); + QVERIFY (!session.errorString ().isEmpty ()); +#else + QCOMPARE (session.open (key, lockPath (directory.path ())), DecoderIpc::Status::Ok); +#endif + if (compatible) + { + QCOMPARE (DecoderIpc::state (shared), int {DECODER_IPC_SHUTDOWN}); + QCOMPARE (shared.payload.d2[0], short {41}); + } + else + { + QCOMPARE (std::memcmp (before.constData (), memory.data (), before.size ()), 0); + } + QVERIFY (memory.detach ()); +#ifdef Q_OS_WIN + QCOMPARE (session.open (key, lockPath (directory.path ())), DecoderIpc::Status::Ok); +#endif + NativeSharedMemory replacement; + QVERIFY2 (replacement.attach (key.toStdString ()), replacement.errorString ().c_str ()); + auto const& fresh = *static_cast (replacement.data ()); + QCOMPARE (DecoderIpc::state (fresh), int {DECODER_IPC_IDLE}); + QCOMPARE (fresh.control.version, int {DECODER_IPC_VERSION}); + QCOMPARE (fresh.payload.d2[0], short {0}); +} + +void TestDecoderIpcHandshake::mappingOwnership () +{ + auto const name = uniqueKey ().toStdString (); + NativeSharedMemory owner; + QVERIFY2 (owner.create (name, 4096), owner.errorString ().c_str ()); + std::memset (owner.data (), 0x5a, 4096); + QByteArray const before {static_cast (owner.data ()), 4096}; + { + NativeSharedMemory duplicate; + QVERIFY (!duplicate.create (name, 4096)); + QVERIFY (duplicate.alreadyExists ()); + QVERIFY (!duplicate.isAttached ()); + QVERIFY (!duplicate.errorString ().empty ()); + } + QCOMPARE (std::memcmp (owner.data (), before.constData (), before.size ()), 0); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (name), peer.errorString ().c_str ()); + QVERIFY (peer.size () >= 4096); + QCOMPARE (std::memcmp (owner.data (), peer.data (), 4096), 0); + QCOMPARE (static_cast (owner.data ())[0], static_cast (0x5a)); + QVERIFY (peer.detach ()); + QVERIFY2 (peer.attach (name), peer.errorString ().c_str ()); + QVERIFY (owner.detach ()); + QCOMPARE (static_cast (peer.data ())[0], static_cast (0x5a)); +#ifndef Q_OS_WIN + NativeSharedMemory retired; + QVERIFY (!retired.attach (name)); +#endif + QVERIFY (peer.detach ()); + NativeSharedMemory retiredAfterLastPeer; + QVERIFY (!retiredAfterLastPeer.attach (name)); +} + +void TestDecoderIpcHandshake::missingMappingFails () +{ + auto const key = uniqueKey (); + NativeSharedMemory memory; + QVERIFY (!memory.attach (key.toStdString ())); + QVERIFY (memory.notFound ()); + QVERIFY (!memory.isAttached ()); + QVERIFY (!memory.errorString ().empty ()); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + DecoderProcess child; + child.launch (key, directory.path ()); + QVERIFY (child.waitForStarted (5000)); + QVERIFY (child.waitForFinished (5000)); + auto const output = child.readAllStandardOutput (); + QCOMPARE (child.exitStatus (), QProcess::NormalExit); + QCOMPARE (child.exitCode (), 1); + QVERIFY2 (output.contains (""), output.constData ()); + QVERIFY (!output.contains ("")); +} + +void TestDecoderIpcHandshake::replacementWorkerCompletesRequest () +{ + using namespace DecoderIpc; + auto const key = uniqueKey (); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + QCOMPARE (session.open (key, lockPath (directory.path ())), Status::Ok); + NativeSharedMemory peer; + QVERIFY (peer.attach (key.toStdString ())); + auto const* retained = peer.data (); + auto payload = std::make_unique (); + payload->params.nmode = 8; + payload->params.ntrperiod = 15; + payload->params.nzhsym = 50; + payload->params.newdat = true; + payload->params.nfa = 200; + payload->params.nfb = 4000; + qint32 previousGeneration {0}; + DecoderProcess child; + for (int worker = 0; worker < 2; ++worker) + { + child.launch (key, directory.path ()); + QVERIFY (child.waitForStarted (5000)); + QByteArray output; + QVERIFY2 (child.waitForOutput ("", output), output.constData ()); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + auto const submission = session.submit (Request::snapshot (*payload, {11, 12, worker + 1, 180000})); + QVERIFY (submission); + QVERIFY (submission.generation.value () > previousGeneration); + previousGeneration = submission.generation.value (); + QVERIFY2 (child.waitForOutput ("", output), output.constData ()); + Completion completion {}; + bool completed {false}; + for (auto const& line : output.split ('\n')) + if (parseCompletion (line, &completion)) completed = true; + QVERIFY2 (completed, output.constData ()); + QCOMPARE (completion.generation, submission.generation.value ()); + QCOMPARE (session.complete (completion), Status::Ok); + QVERIFY2 (!output.contains (""), output.constData ()); + QVERIFY2 (!output.contains (""), output.constData ()); + if (worker == 0) + { + child.kill (); + QVERIFY (child.waitForFinished (5000)); + QCOMPARE (child.state (), QProcess::NotRunning); + QVERIFY (session.reset ()); + QVERIFY (!session.ready ()); + QVERIFY (peer.data () == retained); + QCOMPARE (state (*static_cast (retained)), int {DECODER_IPC_IDLE}); + } + } + session.shutdown (); + QVERIFY (child.waitForFinished (5000)); + QCOMPARE (child.exitStatus (), QProcess::NormalExit); + QCOMPARE (child.exitCode (), 0); +} + +void TestDecoderIpcHandshake::simultaneousSessionsStayIsolated () +{ + using namespace DecoderIpc; + auto const firstKey = uniqueKey (); + auto const secondKey = uniqueKey (); + QTemporaryDir firstDirectory; + QTemporaryDir secondDirectory; + QVERIFY (firstDirectory.isValid ()); + QVERIFY (secondDirectory.isValid ()); + Session first; + Session second; + QCOMPARE (first.open (firstKey, lockPath (firstDirectory.path ())), Status::Ok); + QCOMPARE (second.open (secondKey, lockPath (secondDirectory.path ())), Status::Ok); + DecoderProcess firstChild; + DecoderProcess secondChild; + firstChild.launch (firstKey, firstDirectory.path ()); + secondChild.launch (secondKey, secondDirectory.path ()); + QVERIFY (firstChild.waitForStarted (5000)); + QVERIFY (secondChild.waitForStarted (5000)); + QByteArray firstOutput; + QByteArray secondOutput; + QVERIFY2 (firstChild.waitForOutput ("", firstOutput), firstOutput.constData ()); + QVERIFY2 (secondChild.waitForOutput ("", secondOutput), secondOutput.constData ()); + QCOMPARE (first.acceptReady (DECODER_IPC_VERSION), Status::Ok); + QCOMPARE (second.acceptReady (DECODER_IPC_VERSION), Status::Ok); + first.shutdown (); + QVERIFY (firstChild.waitForFinished (5000)); + QCOMPARE (firstChild.exitCode (), 0); + first.detach (); + QCOMPARE (secondChild.state (), QProcess::Running); + auto payload = std::make_unique (); + payload->params.nmode = 8; + payload->params.ntrperiod = 15; + payload->params.nzhsym = 50; + payload->params.newdat = true; + payload->params.nfa = 200; + payload->params.nfb = 4000; + auto const submission = second.submit (Request::snapshot (*payload, {21, 22, 1, 180000})); + QVERIFY (submission); + QVERIFY2 (secondChild.waitForOutput ("", secondOutput), secondOutput.constData ()); + Completion completion {}; + bool completed {false}; + for (auto const& line : secondOutput.split ('\n')) + if (parseCompletion (line, &completion)) completed = true; + QVERIFY2 (completed, secondOutput.constData ()); + QCOMPARE (second.complete (completion), Status::Ok); + QVERIFY2 (!secondOutput.contains (""), secondOutput.constData ()); + QVERIFY2 (!secondOutput.contains (""), secondOutput.constData ()); + second.shutdown (); + QVERIFY (secondChild.waitForFinished (5000)); + QCOMPARE (secondChild.exitStatus (), QProcess::NormalExit); + QCOMPARE (secondChild.exitCode (), 0); +} + +void TestDecoderIpcHandshake::orphanLockLifetime_data () +{ + QTest::addColumn ("killed"); + QTest::newRow ("normal-exit") << false; + QTest::newRow ("process-death") << true; +} + +void TestDecoderIpcHandshake::orphanLockLifetime () +{ +#ifdef Q_OS_WIN + QSKIP ("POSIX worker locks protect cleanup after mapping detach"); +#else + QFETCH (bool, killed); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const key = uniqueKey (); + auto const nativeName = key.toStdString (); + auto const descriptor = shm_open (nativeName.c_str (), O_CREAT | O_EXCL | O_RDWR, 0600); + QVERIFY (descriptor >= 0); + auto cleanup = qScopeGuard ([&] { NativeSharedMemory::remove (key.toStdString ()); }); + auto const resized = ftruncate (descriptor, sizeof (shared_dec_data_t)); + auto const closed = close (descriptor); + QCOMPARE (resized, 0); + QCOMPARE (closed, 0); + NativeSharedMemory memory; + QVERIFY (memory.attach (nativeName)); + auto& shared = *static_cast (memory.data ()); + DecoderIpc::initialize (shared); + shared.payload.d2[0] = 41; + + DecoderProcess holder; + holder.start (QCoreApplication::applicationFilePath (), + {"--hold-worker-lock", lockPath (directory.path ()), key}); + QVERIFY (holder.waitForStarted (5000)); + QByteArray output; + QVERIFY2 (holder.waitForOutput ("", output), output.constData ()); + QCOMPARE (holder.write ("d", 1), qint64 {1}); + QVERIFY2 (holder.waitForOutput ("", output), output.constData ()); + + DecoderIpc::Session session; + QElapsedTimer timer; + timer.start (); + QCOMPARE (session.open (key, lockPath (directory.path ())), DecoderIpc::Status::Orphaned); + QVERIFY (timer.elapsed () >= 2900); + QVERIFY (!session.errorString ().isEmpty ()); + QCOMPARE (holder.state (), QProcess::Running); + QCOMPARE (DecoderIpc::state (shared), int {DECODER_IPC_SHUTDOWN}); + NativeSharedMemory retained; + QVERIFY (retained.attach (nativeName)); + auto const& stillOld = *static_cast (retained.data ()); + QCOMPARE (stillOld.payload.d2[0], short {41}); + QCOMPARE (DecoderIpc::state (stillOld), int {DECODER_IPC_SHUTDOWN}); + QVERIFY (retained.detach ()); + + if (killed) holder.kill (); + else QCOMPARE (holder.write ("r", 1), qint64 {1}); + QVERIFY (holder.waitForFinished (5000)); + if (!killed) QCOMPARE (holder.exitCode (), 0); + QCOMPARE (session.open (key, lockPath (directory.path ())), DecoderIpc::Status::Ok); + NativeSharedMemory replacement; + QVERIFY (replacement.attach (nativeName)); + auto const& fresh = *static_cast (replacement.data ()); + QCOMPARE (fresh.payload.d2[0], short {0}); + QCOMPARE (DecoderIpc::state (fresh), int {DECODER_IPC_IDLE}); + QCOMPARE (shared.payload.d2[0], short {41}); +#endif +} + +void TestDecoderIpcHandshake::blockedWorkerPreservesFiles () +{ +#ifdef Q_OS_WIN + QSKIP ("The worker lifetime lock is POSIX-only"); +#else + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const key = uniqueKey (); + DecoderIpc::Session session; + QCOMPARE (session.open (key, lockPath (directory.path ())), DecoderIpc::Status::Ok); + DecoderWorkerLock holder {QFile::encodeName (lockPath (directory.path ())).constData ()}; + QVERIFY2 (holder.tryLock (), holder.errorString ().c_str ()); + QByteArray const sentinel {"existing decoder output\n"}; + for (auto const& name : {"timer.out", "jt9_wisdom.dat"}) + { + QFile file {directory.filePath (name)}; + QVERIFY (file.open (QIODevice::WriteOnly)); + QCOMPARE (file.write (sentinel), qint64 {sentinel.size ()}); + } + DecoderProcess child; + child.launch (key, directory.path ()); + QVERIFY (child.waitForStarted (5000)); + QVERIFY (child.waitForFinished (5000)); + QCOMPARE (child.exitStatus (), QProcess::NormalExit); + QCOMPARE (child.exitCode (), 1); + auto const output = child.readAllStandardOutput (); + QVERIFY2 (output.contains (""), output.constData ()); + QVERIFY (!output.contains ("")); + for (auto const& name : {"timer.out", "jt9_wisdom.dat"}) + { + QFile file {directory.filePath (name)}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.readAll (), sentinel); + } +#endif +} + +void TestDecoderIpcHandshake::insufficientLinuxSharedMemory () +{ +#ifdef Q_OS_LINUX + if (qgetenv ("WSJTX_TEST_SMALL_SHM") != "1") + QSKIP ("Run alone in a container with --shm-size=16m and WSJTX_TEST_SMALL_SHM=1"); + struct statvfs capacity {}; + QCOMPARE (statvfs ("/dev/shm", &capacity), 0); + QVERIFY2 (capacity.f_blocks * capacity.f_frsize <= 16 * 1024 * 1024, + "This test requires an isolated /dev/shm mount of at most 16 MiB"); + auto const name = uniqueKey ().toStdString (); + NativeSharedMemory memory; + QVERIFY (!memory.create (name, sizeof (shared_dec_data_t))); + QVERIFY (!memory.isAttached ()); + auto const error = QString::fromStdString (memory.errorString ()); + QVERIFY2 (error.startsWith ("posix_fallocate:"), qPrintable (error)); + QVERIFY2 (error.endsWith (QString {"(%1)"}.arg (ENOSPC)), qPrintable (error)); + NativeSharedMemory leftover; + QVERIFY (!leftover.attach (name)); + QVERIFY (leftover.notFound ()); +#else + QSKIP ("Linux allocation reservation regression"); +#endif +} + +int main (int argc, char ** argv) +{ + QCoreApplication application {argc, argv}; + auto const arguments = application.arguments (); + if (arguments.size () == 4 && arguments[1] == "--hold-worker-lock") + { + DecoderWorkerLock lock {QFile::encodeName (arguments[2]).constData ()}; + if (!lock.tryLock ()) return 1; + NativeSharedMemory memory; + if (!memory.attach (arguments[3].toStdString ())) return 2; + std::puts (""); + std::fflush (stdout); + if (std::getchar () != 'd' || !memory.detach ()) return 3; + std::puts (""); + std::fflush (stdout); + return std::getchar () == 'r' ? 0 : 4; + } + TestDecoderIpcHandshake test; + return QTest::qExec (&test, argc, argv); +} +#include "test_decoder_ipc_handshake.moc" diff --git a/tests/unit/decoder_ipc/test_decoder_ipc_layout.cpp b/tests/unit/decoder_ipc/test_decoder_ipc_layout.cpp new file mode 100644 index 00000000..ea8dc09f --- /dev/null +++ b/tests/unit/decoder_ipc/test_decoder_ipc_layout.cpp @@ -0,0 +1,192 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "DecoderIpc.hpp" +#include "lib/decoder_ipc_layout.h" + +class TestDecoderIpcLayout final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void compiledLayoutsAgree (); + void everyDescriptorWordIsRequired (); + void equalSizeParameterSwapIsRejected (); + void malformedStorageIsRejected (); + void truncatedStorageIsRejectedBeforePayloadAccess (); + void allocationPaddingIsAccepted (); + void publicationAndClaimRejectIncompatibleLayout (); +}; + +void TestDecoderIpcLayout::compiledLayoutsAgree () +{ + decoder_ipc_layout_t cpp {}; + decoder_ipc_layout_t fortran {}; + decoder_ipc_expected_layout (&cpp); + decoder_ipc_fortran_layout (&fortran); + QCOMPARE (std::memcmp (&cpp, &fortran, sizeof cpp), 0); + QCOMPARE (cpp.field_count, DECODER_IPC_LAYOUT_FIELDS); + QCOMPARE (cpp.payload_offset, static_cast (offsetof (shared_dec_data_t, payload))); + QCOMPARE (cpp.payload_bytes, static_cast (sizeof (dec_data_t))); + QCOMPARE (cpp.logical_bytes, static_cast (sizeof (shared_dec_data_t))); + + std::unique_ptr shared {new shared_dec_data_t}; + DecoderIpc::initialize (*shared); + QCOMPARE (decoder_ipc_validate_layout (shared.get (), sizeof *shared, &fortran), + int {DECODER_IPC_LAYOUT_OK}); + QCOMPARE (decoder_ipc_fortran_validate (shared.get (), sizeof *shared), + int {DECODER_IPC_LAYOUT_OK}); +} + +void TestDecoderIpcLayout::everyDescriptorWordIsRequired () +{ + std::unique_ptr shared {new shared_dec_data_t}; + DecoderIpc::initialize (*shared); + auto const valid = shared->layout; + std::array words; + std::memcpy (words.data (), &valid, sizeof valid); + + for (std::size_t index = 0; index < words.size (); ++index) + { + words[index] ^= 1; + std::memcpy (&shared->layout, words.data (), sizeof valid); + auto const before = shared->layout; + auto const message = QByteArray::number (static_cast (index)); + QVERIFY2 (decoder_ipc_validate_layout (shared.get (), sizeof *shared, nullptr) + != DECODER_IPC_LAYOUT_OK, message.constData ()); + QVERIFY2 (decoder_ipc_fortran_validate (shared.get (), sizeof *shared) + != DECODER_IPC_LAYOUT_OK, message.constData ()); + QCOMPARE (std::memcmp (&before, &shared->layout, sizeof before), 0); + shared->layout = valid; + QCOMPARE (decoder_ipc_validate_layout (shared.get (), sizeof *shared, &before), + int {DECODER_IPC_LAYOUT_MISMATCH}); + words[index] ^= 1; + } +} + +void TestDecoderIpcLayout::equalSizeParameterSwapIsRejected () +{ + std::unique_ptr shared {new shared_dec_data_t}; + DecoderIpc::initialize (*shared); + auto& first = shared->layout.fields[9]; // params.nutc + auto& second = shared->layout.fields[11]; // params.ntrperiod + QCOMPARE (first.bytes, second.bytes); + std::swap (first.offset, second.offset); + QCOMPARE (decoder_ipc_fortran_validate (shared.get (), sizeof *shared), + int {DECODER_IPC_LAYOUT_MISMATCH}); +} + +void TestDecoderIpcLayout::malformedStorageIsRejected () +{ + QCOMPARE (decoder_ipc_validate_layout (nullptr, sizeof (shared_dec_data_t), nullptr), + int {DECODER_IPC_LAYOUT_NULL}); + QCOMPARE (decoder_ipc_fortran_validate (nullptr, sizeof (shared_dec_data_t)), + int {DECODER_IPC_LAYOUT_NULL}); + + std::unique_ptr shared {new shared_dec_data_t}; + DecoderIpc::initialize (*shared); + auto const* unaligned = reinterpret_cast (shared.get ()) + 1; + QCOMPARE (decoder_ipc_validate_layout (unaligned, sizeof *shared - 1, nullptr), + int {DECODER_IPC_LAYOUT_ALIGNMENT}); + QCOMPARE (decoder_ipc_fortran_validate (unaligned, sizeof *shared - 1), + int {DECODER_IPC_LAYOUT_ALIGNMENT}); + + for (auto const version : {0, 1, 2, 3, DECODER_IPC_VERSION + 1}) + { + shared->control.version = version; + QCOMPARE (decoder_ipc_fortran_validate (shared.get (), sizeof *shared), + int {DECODER_IPC_LAYOUT_VERSION}); + QCOMPARE (shared->control.version, version); + } + shared->control.version = DECODER_IPC_VERSION; + shared->control.state = -1; + QCOMPARE (decoder_ipc_fortran_validate (shared.get (), sizeof *shared), + int {DECODER_IPC_LAYOUT_STATE}); + QCOMPARE (shared->control.state, -1); + shared->control.state = DECODER_IPC_IDLE; + + for (auto const capabilities : {0, DECODER_IPC_CAPABILITIES & ~DECODER_IPC_CAP_HANDSHAKE, + DECODER_IPC_CAPABILITIES | 8}) + { + shared->layout.capabilities = capabilities; + QCOMPARE (decoder_ipc_fortran_validate (shared.get (), sizeof *shared), + int {DECODER_IPC_LAYOUT_CAPABILITIES}); + QCOMPARE (shared->layout.capabilities, capabilities); + } +} + +void TestDecoderIpcLayout::truncatedStorageIsRejectedBeforePayloadAccess () +{ + alignas(shared_dec_data_t) std::array header {}; + decoder_ipc_control_t const control {0, DECODER_IPC_IDLE, DECODER_IPC_VERSION, 0}; + decoder_ipc_layout_t layout; + decoder_ipc_expected_layout (&layout); + std::memcpy (header.data (), &control, sizeof control); + std::memcpy (header.data () + offsetof (shared_dec_data_t, layout), &layout, sizeof layout); + auto const before = header; + for (auto const size : {std::size_t {0}, sizeof control - 1, + sizeof control, header.size () - 1, header.size ()}) + { + QCOMPARE (decoder_ipc_validate_layout (header.data (), size, nullptr), + int {DECODER_IPC_LAYOUT_TRUNCATED}); + QCOMPARE (decoder_ipc_fortran_validate (header.data (), size), + int {DECODER_IPC_LAYOUT_TRUNCATED}); + QVERIFY (header == before); + } + + layout.header_bytes = -1; + std::memcpy (header.data () + offsetof (shared_dec_data_t, layout), &layout, sizeof layout); + QCOMPARE (decoder_ipc_fortran_validate (header.data (), header.size ()), + int {DECODER_IPC_LAYOUT_HEADER_SIZE}); + decoder_ipc_expected_layout (&layout); + layout.payload_bytes = -1; + std::memcpy (header.data () + offsetof (shared_dec_data_t, layout), &layout, sizeof layout); + QCOMPARE (decoder_ipc_fortran_validate (header.data (), header.size ()), + int {DECODER_IPC_LAYOUT_PAYLOAD_SIZE}); +} + +void TestDecoderIpcLayout::allocationPaddingIsAccepted () +{ + std::vector storage ((sizeof (shared_dec_data_t) + 4096) / sizeof (int)); + auto* shared = new (storage.data ()) shared_dec_data_t; + DecoderIpc::initialize (*shared); + QCOMPARE (decoder_ipc_fortran_validate (shared, storage.size () * sizeof (int)), + int {DECODER_IPC_LAYOUT_OK}); + shared->layout.logical_bytes += 4; + QCOMPARE (decoder_ipc_fortran_validate (shared, storage.size () * sizeof (int)), + int {DECODER_IPC_LAYOUT_LOGICAL_SIZE}); + shared->~shared_dec_data_t (); +} + +void TestDecoderIpcLayout::publicationAndClaimRejectIncompatibleLayout () +{ + std::unique_ptr shared {new shared_dec_data_t}; + std::unique_ptr payload {new dec_data_t {}}; + DecoderIpc::initialize (*shared); + shared->payload.d2[0] = 42; + payload->d2[0] = 17; + payload->params.nmode = 8; + shared->layout.payload_bytes -= 4; + QByteArray before (reinterpret_cast (shared.get ()), sizeof *shared); + QVERIFY (!DecoderIpc::publish (*shared, *payload, true, 1)); + QCOMPARE (std::memcmp (shared.get (), before.constData (), sizeof *shared), 0); + + shared->control.state = DECODER_IPC_READY; + shared->control.generation = 1; + before = QByteArray (reinterpret_cast (shared.get ()), sizeof *shared); + qint32 generation {99}; + QVERIFY (!DecoderIpc::claim (*shared, generation)); + QCOMPARE (generation, qint32 {99}); + QCOMPARE (std::memcmp (shared.get (), before.constData (), sizeof *shared), 0); +} + +QTEST_GUILESS_MAIN (TestDecoderIpcLayout) + +#include "test_decoder_ipc_layout.moc" diff --git a/tests/unit/decoder_ipc/test_decoder_ipc_protocol.cpp b/tests/unit/decoder_ipc/test_decoder_ipc_protocol.cpp index 85a414fa..c303541d 100644 --- a/tests/unit/decoder_ipc/test_decoder_ipc_protocol.cpp +++ b/tests/unit/decoder_ipc/test_decoder_ipc_protocol.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include #include #include @@ -7,11 +10,12 @@ #include #include "DecoderIpc.hpp" +#include "lib/NativeSharedMemory.hpp" #include "lib/decoder_ipc_control.h" extern "C" { - void decoder_ipc_fortran_probe (void *, int[10]); + void decoder_ipc_fortran_probe (void *, int[11]); } class TestDecoderIpcProtocol final : public QObject @@ -24,10 +28,14 @@ private Q_SLOTS: void publicationAndClaimValidateControl (); void compactFt8MtdPublicationCopiesRequiredPayload (); void compactFt8MtdPublicationRejectsInvalidRequests (); + void newInputForcesSamplePublication (); void transitionsRequireMatchingGeneration (); void sharedProgressTracksActiveGeneration (); void delayedCompletionCannotClobberNextRequest (); void compatibleShutdownReleasesWorkers (); + void sharedMemoryWorkerExitsOnShutdown_data (); + void sharedMemoryWorkerExitsOnShutdown (); + void rejectedEngineRequestCompletes (); void shutdownReplacesAnyState_data (); void shutdownReplacesAnyState (); void generationWrapsWithoutUsingZero (); @@ -44,14 +52,18 @@ void TestDecoderIpcProtocol::layoutMatchesFortran () struct CompatibleSharedData { int ipc[4]; + decoder_ipc_layout_t layout; dec_data_t payload; + decoder_input_metadata_t metadata; }; QCOMPARE (sizeof (decoder_ipc_control_t), size_t {16}); QCOMPARE (offsetof (decoder_ipc_control_t, state), size_t {4}); - QCOMPARE (offsetof (shared_dec_data_t, payload), size_t {16}); - QCOMPARE (sizeof (shared_dec_data_t), - sizeof (decoder_ipc_control_t) + sizeof (dec_data_t)); + QCOMPARE (offsetof (shared_dec_data_t, payload), + sizeof (decoder_ipc_control_t) + sizeof (decoder_ipc_layout_t)); + QCOMPARE (sizeof (decoder_input_metadata_t), size_t {24}); + QCOMPARE (offsetof (shared_dec_data_t, metadata), + offsetof (CompatibleSharedData, metadata)); QCOMPARE (sizeof (shared_dec_data_t), sizeof (CompatibleSharedData)); QCOMPARE (offsetof (CompatibleSharedData, ipc) + sizeof (int), offsetof (decoder_ipc_control_t, state)); @@ -60,7 +72,7 @@ void TestDecoderIpcProtocol::layoutMatchesFortran () std::unique_ptr shared {new shared_dec_data_t}; shared->control.generation = 41; - int values[10] {}; + int values[11] {}; decoder_ipc_fortran_probe (shared.get (), values); QCOMPARE (values[0], static_cast (sizeof (decoder_ipc_control_t))); @@ -73,26 +85,22 @@ void TestDecoderIpcProtocol::layoutMatchesFortran () QCOMPARE (values[7], int {DECODER_IPC_DECODING}); QCOMPARE (values[8], int {DECODER_IPC_COMPLETE}); QCOMPARE (values[9], int {DECODER_IPC_SHUTDOWN}); + QCOMPARE (values[10], static_cast (sizeof (decoder_input_metadata_t))); QCOMPARE (shared->control.generation, 42); QCOMPARE (shared->payload.d2[0], short {1234}); + QCOMPARE (shared->metadata.input_id, int64_t {12345678901}); + QCOMPARE (shared->metadata.analysis_id, int64_t {12345678902}); + QCOMPARE (shared->metadata.attempt_no, int32_t {3}); + QCOMPARE (shared->metadata.valid_samples, int32_t {180000}); } void TestDecoderIpcProtocol::sharedMemorySizeAllowsPlatformRounding () { auto const required = static_cast (sizeof (shared_dec_data_t)); - auto const shutdownRequired = static_cast ( - offsetof (decoder_ipc_control_t, progress)); - QVERIFY (!DecoderIpc::hasShutdownControlSize (shutdownRequired - 1)); - QVERIFY (DecoderIpc::hasShutdownControlSize (shutdownRequired)); QVERIFY (!DecoderIpc::hasUsableSize (required - 1)); QVERIFY (DecoderIpc::hasUsableSize (required)); QVERIFY (DecoderIpc::hasUsableSize (required + 80)); - int compatibleControl[3] {17, DECODER_IPC_DECODING, 0}; - DecoderIpc::shutdownControl (compatibleControl); - QCOMPARE (compatibleControl[0], 17); - QCOMPARE (compatibleControl[1], int {DECODER_IPC_SHUTDOWN}); - QCOMPARE (compatibleControl[2], 1); } void TestDecoderIpcProtocol::publicationAndClaimValidateControl () @@ -129,6 +137,7 @@ void TestDecoderIpcProtocol::compactFt8MtdPublicationCopiesRequiredPayload () payload->params.nmode = 8; payload->params.lmultift8 = true; payload->params.nutc = 123456; + payload->metadata = {11, 12, 2, 162432}; payload->samples.front () = 17; payload->samples.back () = 29; @@ -137,6 +146,10 @@ void TestDecoderIpcProtocol::compactFt8MtdPublicationCopiesRequiredPayload () QCOMPARE (shared->control.state, int {DECODER_IPC_READY}); QCOMPARE (shared->control.generation, 7); QCOMPARE (shared->payload.params.nutc, 123456); + QCOMPARE (shared->metadata.input_id, int64_t {11}); + QCOMPARE (shared->metadata.analysis_id, int64_t {12}); + QCOMPARE (shared->metadata.attempt_no, int32_t {2}); + QCOMPARE (shared->metadata.valid_samples, int32_t {162432}); QCOMPARE (shared->payload.d2[0], short {17}); QCOMPARE (shared->payload.d2[DecoderIpc::Ft8SampleCount - 1], short {29}); QCOMPARE (shared->payload.d2[DecoderIpc::Ft8SampleCount], short {61}); @@ -189,6 +202,36 @@ void TestDecoderIpcProtocol::compactFt8MtdPublicationRejectsInvalidRequests () QCOMPARE (shared->payload.d2[0], short {22}); } +void TestDecoderIpcProtocol::newInputForcesSamplePublication () +{ + std::unique_ptr shared {new shared_dec_data_t}; + std::unique_ptr payload {new dec_data_t {}}; + DecoderIpc::initialize (*shared); + payload->params.nmode = 8; + payload->params.ntrperiod = 15; + payload->d2[0] = 17; + + QVERIFY (DecoderIpc::publish (*shared, *payload, true, 1, {11, 12, 1, 141696})); + qint32 generation {0}; + QVERIFY (DecoderIpc::claim (*shared, generation)); + QVERIFY (DecoderIpc::finish (*shared, 1)); + QVERIFY (DecoderIpc::consume (*shared, 1)); + + payload->d2[0] = 29; + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 2, {11, 12, 2, 169344})); + QCOMPARE (shared->payload.d2[0], short {17}); + QCOMPARE (shared->metadata.attempt_no, int32_t {2}); + QVERIFY (DecoderIpc::claim (*shared, generation)); + QVERIFY (DecoderIpc::finish (*shared, 2)); + QVERIFY (DecoderIpc::consume (*shared, 2)); + + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 3, {13, 14, 1, 141696})); + QCOMPARE (shared->payload.d2[0], short {29}); + QCOMPARE (shared->metadata.input_id, int64_t {13}); + QCOMPARE (shared->metadata.analysis_id, int64_t {14}); + QCOMPARE (shared->metadata.attempt_no, int32_t {1}); +} + void TestDecoderIpcProtocol::transitionsRequireMatchingGeneration () { std::unique_ptr shared {new shared_dec_data_t}; @@ -298,15 +341,105 @@ void TestDecoderIpcProtocol::delayedCompletionCannotClobberNextRequest () void TestDecoderIpcProtocol::compatibleShutdownReleasesWorkers () { - decoder_ipc_control_t control {17, 0, DECODER_IPC_VERSION, 4}; - DecoderIpc::shutdown (control); + auto shared = std::make_unique (); + DecoderIpc::initialize (*shared); + auto& control = shared->control; + control.generation = 17; + control.progress = 4; + DecoderIpc::shutdown (*shared); QCOMPARE (control.generation, 17); QCOMPARE (control.state, int {DECODER_IPC_SHUTDOWN}); - QCOMPARE (control.version, 1); + QCOMPARE (control.version, int {DECODER_IPC_VERSION}); QCOMPARE (control.progress, 4); } +void TestDecoderIpcProtocol::rejectedEngineRequestCompletes () +{ + auto const key = DecoderIpc::memoryName (QUuid::createUuid ().toString ()); + NativeSharedMemory memory; + QVERIFY2 (memory.create (key.toStdString (), sizeof (shared_dec_data_t)), memory.errorString ().c_str ()); + auto * shared = static_cast (memory.data ()); + DecoderIpc::initialize (*shared); + auto payload = std::make_unique (); + payload->params.nmode = 8; + payload->params.ntrperiod = 15; + payload->params.nzhsym = 50; + payload->params.newdat = true; + payload->params.nfa = -1; + payload->params.nfb = 4000; + + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QProcess decoder; + QByteArray output; + connect (&decoder, &QProcess::readyReadStandardOutput, this, [&] { + output += decoder.readAllStandardOutput (); + }); + decoder.start (QString::fromLocal8Bit (JT9_TEST_EXECUTABLE), {"-s", key, "--ipc-lock", directory.filePath ("worker.lock"), + "-a", directory.path (), "-t", directory.path ()}); + QVERIFY (decoder.waitForStarted ()); + QTRY_VERIFY_WITH_TIMEOUT (output.contains (""), 5000); + QVERIFY (DecoderIpc::publish (*shared, *payload, true, 7, {11, 12, 1, 180000})); + QTRY_VERIFY_WITH_TIMEOUT (output.contains (""), 5000); + QVERIFY2 (output.contains (" status=invalid operation=decode mode=8 input=11 analysis=12 attempt=1"), + output.constData ()); + QVERIFY (!output.contains ("")); + QVERIFY (output.indexOf ("") < output.indexOf ("")); + QVERIFY (DecoderIpc::consume (*shared, 7)); + + output.clear (); + payload->params.nfa = 200; + QVERIFY (DecoderIpc::publish (*shared, *payload, true, 8, {11, 12, 2, 180000})); + QTRY_VERIFY_WITH_TIMEOUT (output.contains (""), 5000); + QVERIFY2 (!output.contains (""), output.constData ()); + QVERIFY (DecoderIpc::consume (*shared, 8)); + DecoderIpc::shutdown (*shared); + QVERIFY (decoder.waitForFinished (5000)); + QCOMPARE (decoder.exitStatus (), QProcess::NormalExit); + QCOMPARE (decoder.exitCode (), 0); +} + +void TestDecoderIpcProtocol::sharedMemoryWorkerExitsOnShutdown_data () +{ + QTest::addColumn ("explicitMode"); + QTest::newRow ("mode-from-shared-memory") << false; + QTest::newRow ("explicit-ft8-mode") << true; +} + +void TestDecoderIpcProtocol::sharedMemoryWorkerExitsOnShutdown () +{ + QFETCH (bool, explicitMode); + + auto const key = DecoderIpc::memoryName (QUuid::createUuid ().toString ()); + NativeSharedMemory memory; + QVERIFY2 (memory.create (key.toStdString (), sizeof (shared_dec_data_t)), + memory.errorString ().c_str ()); + + auto * shared = static_cast (memory.data ()); + DecoderIpc::initialize (*shared); + DecoderIpc::shutdown (*shared); + + QStringList args; + if (explicitMode) args << QStringLiteral ("-8"); + args << QStringLiteral ("-s") << key; + + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QProcess decoder; + args << "--ipc-lock" << directory.filePath ("worker.lock") + << "-a" << directory.path () << "-t" << directory.path (); + decoder.start (QString::fromLocal8Bit (JT9_TEST_EXECUTABLE), args); + if (!decoder.waitForFinished (15000)) + { + decoder.kill (); + decoder.waitForFinished (); + QFAIL ("jt9 did not exit after shared-memory shutdown"); + } + QCOMPARE (decoder.exitStatus (), QProcess::NormalExit); + QCOMPARE (decoder.exitCode (), 0); +} + void TestDecoderIpcProtocol::shutdownReplacesAnyState_data () { QTest::addColumn ("state"); @@ -319,13 +452,16 @@ void TestDecoderIpcProtocol::shutdownReplacesAnyState_data () void TestDecoderIpcProtocol::shutdownReplacesAnyState () { QFETCH (int, state); - decoder_ipc_control_t control {17, state, DECODER_IPC_VERSION, 0}; - - DecoderIpc::shutdown (control); + auto shared = std::make_unique (); + DecoderIpc::initialize (*shared); + auto& control = shared->control; + control.generation = 17; + control.state = state; + DecoderIpc::shutdown (*shared); QCOMPARE (control.generation, 17); QCOMPARE (control.state, int {DECODER_IPC_SHUTDOWN}); - QCOMPARE (control.version, 1); + QCOMPARE (control.version, int {DECODER_IPC_VERSION}); } void TestDecoderIpcProtocol::generationWrapsWithoutUsingZero () diff --git a/tests/unit/decoder_ipc/test_decoder_output_framer.cpp b/tests/unit/decoder_ipc/test_decoder_output_framer.cpp index 5fbb2698..ed6ebaee 100644 --- a/tests/unit/decoder_ipc/test_decoder_output_framer.cpp +++ b/tests/unit/decoder_ipc/test_decoder_output_framer.cpp @@ -49,8 +49,114 @@ private Q_SLOTS: void recordTerminatorsArePreserved (); void malformedFramesAreReported (); void killedFrameCanBeReplaced (); + void startupFrames_data (); + void startupFrames (); + void fragmentedStartupFrame (); + void startupFramesDoNotBecomeDecodeRecords (); + void requestRejectionPreservesCompletion (); }; +void TestDecoderOutputFramer::startupFrames_data () +{ + QTest::addColumn ("line"); + QTest::addColumn ("type"); + QTest::addColumn ("version"); + QTest::addColumn ("status"); + auto const ready = static_cast (DecoderOutputFramer::EventType::Ready); + auto const error = static_cast (DecoderOutputFramer::EventType::Error); + auto const malformed = static_cast (DecoderOutputFramer::EventType::Malformed); + QTest::newRow ("ready") << QByteArray {" version=3\n"} << ready << 3 << QByteArray {}; + QTest::newRow ("crlf") << QByteArray {" version=3\r\n"} << ready << 3 << QByteArray {}; + QTest::newRow ("unsupported-version-is-syntax") << QByteArray {" version=2\n"} + << ready << 2 << QByteArray {}; + QTest::newRow ("error") << QByteArray {" status=wrong-header-size\n"} + << error << 0 << QByteArray {"wrong-header-size"}; + for (auto const& line : {QByteArray {" version=\n"}, + QByteArray {" version=0\n"}, + QByteArray {" version=+3\n"}, + QByteArray {" version=3 extra\n"}, + QByteArray {" version=99999999999\n"}, + QByteArray {" status=\n"}, + QByteArray {" status=wrong size\n"}, + QByteArray {" status=WrongSize\n"}}) + QTest::newRow (line.constData ()) << line << malformed << 0 << QByteArray {}; +} + +void TestDecoderOutputFramer::startupFrames () +{ + QFETCH (QByteArray, line); + QFETCH (int, type); + QFETCH (int, version); + QFETCH (QByteArray, status); + QBuffer buffer {&line}; + QVERIFY (buffer.open (QIODevice::ReadOnly)); + DecoderOutputFramer framer; + QVector events; + framer.drain (buffer, [&] (DecoderOutputFramer::Event const& event) { events.append (event); }); + QCOMPARE (events.size (), 1); + QCOMPARE (static_cast (events[0].type), type); + QCOMPARE (events[0].protocolVersion, version); + QCOMPARE (events[0].errorStatus, status); + QCOMPARE (framer.currentGeneration (), qint32 {0}); +} + +void TestDecoderOutputFramer::fragmentedStartupFrame () +{ + QByteArray output {" ver"}; + QBuffer buffer {&output}; + QVERIFY (buffer.open (QIODevice::ReadOnly)); + DecoderOutputFramer framer; + QVector events; + auto const handler = [&] (DecoderOutputFramer::Event const& event) { events.append (event); }; + framer.drain (buffer, handler); + QVERIFY (events.isEmpty ()); + output.append ("sion=3\n"); + framer.drain (buffer, handler); + QCOMPARE (events.size (), 1); + QCOMPARE (events[0].type, DecoderOutputFramer::EventType::Ready); + QCOMPARE (events[0].protocolVersion, qint32 {3}); +} + +void TestDecoderOutputFramer::startupFramesDoNotBecomeDecodeRecords () +{ + QByteArray output {" gen=7\n" + " version=3\n" + " status=incompatible-layout\n" + " version=bad\n" + " 0 0 0 gen=7\n"}; + QBuffer buffer {&output}; + QVERIFY (buffer.open (QIODevice::ReadOnly)); + DecoderOutputFramer framer; + QVector types; + framer.drain (buffer, [&] (DecoderOutputFramer::Event const& event) { types.append (event.type); }); + QCOMPARE (types, QVector ({ + DecoderOutputFramer::EventType::Started, DecoderOutputFramer::EventType::Ready, + DecoderOutputFramer::EventType::Error, DecoderOutputFramer::EventType::Malformed, + DecoderOutputFramer::EventType::Finished})); +} + +void TestDecoderOutputFramer::requestRejectionPreservesCompletion () +{ + QByteArray const rejection {" status=invalid operation=decode mode=8 input=11 analysis=12 attempt=1\r\n"}; + QByteArray output = rejection + " gen=7\n" + rejection + + "\n 0 0 0 gen=7\n"; + QBuffer buffer {&output}; + QVERIFY (buffer.open (QIODevice::ReadOnly)); + DecoderOutputFramer framer; + QVector events; + framer.drain (buffer, [&] (DecoderOutputFramer::Event const& event) { events.append (event); }); + QCOMPARE (events.size (), 5); + QCOMPARE (events[0].type, DecoderOutputFramer::EventType::Malformed); + QCOMPARE (events[1].type, DecoderOutputFramer::EventType::Started); + QCOMPARE (events[2].type, DecoderOutputFramer::EventType::Rejected); + QCOMPARE (events[2].generation, qint32 {7}); + QCOMPARE (events[2].rawLine, rejection); + QCOMPARE (events[3].type, DecoderOutputFramer::EventType::Malformed); + QCOMPARE (events[4].type, DecoderOutputFramer::EventType::Finished); + QCOMPARE (framer.currentGeneration (), qint32 {0}); +} + void TestDecoderOutputFramer::rejectedRecordDoesNotStopDrain () { QByteArray const output { diff --git a/tests/unit/decoder_ipc/test_decoder_session.cpp b/tests/unit/decoder_ipc/test_decoder_session.cpp new file mode 100644 index 00000000..117e2507 --- /dev/null +++ b/tests/unit/decoder_ipc/test_decoder_session.cpp @@ -0,0 +1,561 @@ +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "DecoderIpc.hpp" +#include "lib/NativeSharedMemory.hpp" + +class TestDecoderSession final : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void ownsGenerationsAndSamples (); + void sharedLockUsesNativePath (); + void compactSnapshotAndContextRefresh (); + void preparedReuseRetainsCompletedInput_data (); + void preparedReuseRetainsCompletedInput (); + void incompatibleSnapshotLeavesNextReceptionUntouched_data (); + void incompatibleSnapshotLeavesNextReceptionUntouched (); + void diskPassesReserveAttemptNumbers (); + void deferredSnapshotKeepsItsInputAfterRollover (); + void reuseStartsNewAnalysisBeforeAttemptOverflow (); + void resetRejectsCorruption (); +}; + +void TestDecoderSession::sharedLockUsesNativePath () +{ +#ifdef Q_OS_WIN + QSKIP ("The native worker lock is POSIX-only"); +#else + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto * previousCodec = QTextCodec::codecForLocale (); + auto restoreCodec = qScopeGuard ([&] { QTextCodec::setCodecForLocale (previousCodec); }); +#ifndef Q_OS_DARWIN + QTextCodec::setCodecForLocale (QTextCodec::codecForName ("ISO-8859-1")); +#endif + auto const path = directory.filePath (QString::fromUtf8 ("décoder.lock")); + auto cleanup = qScopeGuard ([&] { QFile::remove (path); }); + DecoderIpc::Session session; + auto const name = DecoderIpc::memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (name, path), DecoderIpc::Status::Ok); + QVERIFY (QFile::exists (path)); +#endif +} + +void TestDecoderSession::ownsGenerationsAndSamples () +{ + using namespace DecoderIpc; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QVERIFY (!session.ready ()); + auto unavailable = std::make_unique (); + QCOMPARE (session.submit (Request::snapshot (*unavailable)).status, Status::Unavailable); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION - 1), Status::Incompatible); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + auto source = std::make_unique (); + source->params.nmode = 8; + source->params.ntrperiod = 15; + source->params.kin = 150000; + source->params.newdat = true; + source->d2[0] = 17; + source->d2[60 * RX_SAMPLE_RATE - 1] = 29; + + QCOMPARE (session.submit (Request::reuse (*source, {})).status, Status::StaleSamples); + decoder_input_metadata_t metadata {11, 12, 1, 150000}; + auto first = session.submit (Request::snapshot (*source, metadata)); + QVERIFY (first); + QVERIFY (first.samples); + QVERIFY (!session.samples ()); + QVERIFY (!session.completedSnapshot ()); + QCOMPARE (first.generation.value (), 1); + QCOMPARE (shared.metadata.input_id, metadata.input_id); + QCOMPARE (shared.metadata.analysis_id, metadata.analysis_id); + QCOMPARE (shared.metadata.attempt_no, metadata.attempt_no); + QCOMPARE (shared.metadata.valid_samples, metadata.valid_samples); + QCOMPARE (shared.payload.d2[0], short {17}); + QCOMPARE (shared.payload.d2[60 * RX_SAMPLE_RATE - 1], short {29}); + QCOMPARE (session.submit (Request::snapshot (*source)).status, Status::Busy); + QVERIFY (!session.accepts (0)); + QVERIFY (session.accepts (1)); + QCOMPARE (session.complete ({0, 0, 0, 2}), Status::StaleGeneration); + qint32 generation {0}; + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + QVERIFY (session.samples ()); + QCOMPARE (session.completedSnapshot ().metadata.input_id, metadata.input_id); + QCOMPARE (session.completedSnapshot ().lastAttempt, qint32 {1}); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::StaleGeneration); + + source->d2[0] = 99; + source->params.newdat = false; + source->params.nfqso = 1234; + auto const samples = session.samples (); + metadata.analysis_id = 13; + metadata.attempt_no = 2; + auto second = session.submit (Request::reuse (*source, samples, metadata)); + QVERIFY (second); + QCOMPARE (second.generation.value (), 2); + QVERIFY (second.samples == samples); + QCOMPARE (shared.metadata.analysis_id, metadata.analysis_id); + QCOMPARE (shared.metadata.attempt_no, metadata.attempt_no); + QCOMPARE (shared.payload.d2[0], short {17}); + QCOMPARE (shared.payload.params.nfqso, 1234); + QCOMPARE (session.complete ({0, 0, 0, 1}), Status::StaleGeneration); + QCOMPARE (shared.control.generation, 2); + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + + metadata = {14, 15, 1, 150000}; + auto refreshed = session.submit (Request::reuse (*source, samples, metadata)); + QVERIFY (refreshed); + QVERIFY (refreshed.samples != samples); + QCOMPARE (shared.payload.d2[0], short {99}); + QCOMPARE (shared.metadata.input_id, metadata.input_id); + QVERIFY (shared.payload.params.newdat); + QVERIFY (!shared.payload.params.nagain); + + session.abort (); + QVERIFY (!session.samples ()); + QCOMPARE (session.completedSnapshot ().metadata.input_id, int64_t {0}); + QCOMPARE (session.completedSnapshot ().lastAttempt, qint32 {0}); + QVERIFY (!session.accepts (2)); + session.shutdown (); + QVERIFY (session.reset ()); + QVERIFY (!session.ready ()); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + QCOMPARE (session.submit (Request::reuse (*source, samples)).status, Status::StaleSamples); + auto third = session.submit (Request::snapshot (*source)); + QVERIFY (third); + QCOMPARE (third.generation.value (), 4); + QCOMPARE (shared.payload.d2[0], short {99}); + session.shutdown (); +} + +void TestDecoderSession::compactSnapshotAndContextRefresh () +{ + using namespace DecoderIpc; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + auto compact = std::make_unique (); + compact->params.nmode = 8; + compact->params.ntrperiod = 15; + compact->params.kin = 150000; + compact->params.lmultift8 = true; + compact->metadata = {21, 22, 3, 150000}; + compact->samples.front () = 31; + compact->samples.back () = 47; + shared.payload.ss[0] = 5.5F; + auto first = session.submit (Request::ft8 (*compact)); + QVERIFY (first); + QCOMPARE (shared.metadata.input_id, compact->metadata.input_id); + QCOMPARE (shared.metadata.analysis_id, compact->metadata.analysis_id); + QCOMPARE (shared.metadata.attempt_no, compact->metadata.attempt_no); + QCOMPARE (shared.metadata.valid_samples, compact->metadata.valid_samples); + QCOMPARE (shared.payload.d2[0], short {31}); + QCOMPARE (shared.payload.d2[Ft8SampleCount - 1], short {47}); + QCOMPARE (shared.payload.ss[0], 5.5F); + qint32 generation {0}; + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + QCOMPARE (session.completedSnapshot ().metadata.input_id, compact->metadata.input_id); + QCOMPARE (session.completedSnapshot ().metadata.valid_samples, compact->metadata.valid_samples); + QCOMPARE (session.completedSnapshot ().lastAttempt, compact->metadata.attempt_no); + + auto source = std::make_unique (); + source->params.nmode = 65; + source->params.ntrperiod = 60; + source->params.kin = 60 * RX_SAMPLE_RATE; + source->params.nagain = true; + source->d2[0] = 73; + InputState inputs; + auto const refreshed = session.prepareRequest (*source, false, inputs); + QVERIFY (refreshed.options ().newdat); + QVERIFY (!refreshed.options ().nagain); + QCOMPARE (refreshed.metadata ().valid_samples, source->params.kin); + QVERIFY (session.submit (refreshed)); + QCOMPARE (shared.payload.d2[0], short {73}); + QVERIFY (shared.payload.params.newdat); + QVERIFY (!shared.payload.params.nagain); + session.shutdown (); +} + +void TestDecoderSession::incompatibleSnapshotLeavesNextReceptionUntouched_data () +{ + QTest::addColumn ("previousMode"); + QTest::addColumn ("previousPeriod"); + QTest::addColumn ("requestedMode"); + QTest::addColumn ("requestedPeriod"); + QTest::newRow ("no-snapshot") << 0 << 0 << 66 << 60; + QTest::newRow ("different-mode") << 65 << 60 << 66 << 60; + QTest::newRow ("different-period") << 66 << 30 << 66 << 60; + QTest::newRow ("fst4-mode") << 241 << 120 << 240 << 15; + QTest::newRow ("fst4-period") << 240 << 30 << 240 << 15; + QTest::newRow ("fst4w-mode") << 240 << 15 << 241 << 120; + QTest::newRow ("fst4w-period") << 241 << 300 << 241 << 120; +} + +void TestDecoderSession::incompatibleSnapshotLeavesNextReceptionUntouched () +{ + using namespace DecoderIpc; + QFETCH (int, previousMode); + QFETCH (int, previousPeriod); + QFETCH (int, requestedMode); + QFETCH (int, requestedPeriod); + int const validSamples = (requestedPeriod - 4) * RX_SAMPLE_RATE; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + auto source = std::make_unique (); + qint32 generation {0}; + if (previousMode) + { + source->params.nmode = previousMode; + source->params.ntrperiod = previousPeriod; + source->params.kin = previousPeriod * RX_SAMPLE_RATE; + source->params.newdat = true; + decoder_input_metadata_t metadata {7, 9, 1, source->params.kin}; + QVERIFY (session.submit (Request::snapshot (*source, metadata))); + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + QVERIFY (session.canReuseSamples (previousMode, previousPeriod)); + } + + InputState inputs; + inputs.beginInput (); + auto const input = inputs.inputId (); + auto const analysis = inputs.analysisId (); + source->params.nmode = requestedMode; + source->params.ntrperiod = requestedPeriod; + source->params.kin = 10 * RX_SAMPLE_RATE; + source->params.newdat = false; + source->params.nagain = true; + QVERIFY (!session.canReuseSamples (requestedMode, requestedPeriod)); + + source->params.kin = validSamples; + source->params.newdat = true; + source->params.nagain = false; + auto const scheduled = session.prepareRequest (*source, true, inputs); + QCOMPARE (scheduled.metadata ().input_id, input); + QCOMPARE (scheduled.metadata ().analysis_id, analysis); + QCOMPARE (scheduled.metadata ().attempt_no, int32_t {1}); + QCOMPARE (scheduled.metadata ().valid_samples, source->params.kin); + QVERIFY (session.submit (scheduled)); + QCOMPARE (shared.metadata.valid_samples, validSamples); + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + QVERIFY (session.canReuseSamples (requestedMode, requestedPeriod)); + + source->params.kin = (requestedPeriod - 1) * RX_SAMPLE_RATE; + source->params.newdat = false; + source->params.nagain = true; + auto const repeat = session.prepareRequest (*source, false, inputs); + QCOMPARE (repeat.metadata ().input_id, input); + QCOMPARE (repeat.metadata ().valid_samples, validSamples); + QCOMPARE (repeat.options ().kin, validSamples); + QVERIFY (!repeat.options ().newdat); + session.shutdown (); +} + +void TestDecoderSession::preparedReuseRetainsCompletedInput_data () +{ + QTest::addColumn ("mode"); + QTest::addColumn ("rollover"); + QTest::addColumn ("again"); + for (auto mode : {8, 5, 66, 240, 241}) + for (auto rollover : {false, true}) + for (auto again : {false, true}) + QTest::newRow (qPrintable (QString {"mode-%1-rollover-%2-again-%3"} + .arg (mode).arg (rollover).arg (again))) << mode << rollover << again; +} + +void TestDecoderSession::preparedReuseRetainsCompletedInput () +{ + using namespace DecoderIpc; + QFETCH (int, mode); + QFETCH (bool, rollover); + QFETCH (bool, again); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + InputState inputs; + auto source = std::make_unique (); + source->params.nmode = mode; + source->params.ntrperiod = mode == 5 ? 7 : mode == 8 || mode == 240 ? 15 : mode == 241 ? 120 : 60; + source->params.kin = mode == 5 ? 72000 : 150000; + source->params.newdat = true; + source->d2[0] = 17; + auto const initial = session.prepareRequest (*source, true, inputs); + auto const first = session.submit (initial); + QVERIFY (first); + qint32 generation {0}; + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + auto const retained = session.completedSnapshot (); + + if (rollover) inputs.beginInput (); + auto const liveInput = inputs.inputId (); + auto const liveAnalysis = inputs.analysisId (); + source->params.kin = rollover ? 4096 : source->params.kin + 2048; + source->params.newdat = false; + source->params.nagain = again; + source->params.nfqso = 1234; + source->d2[0] = 99; + auto const liveSamples = source->params.kin; + auto candidate = inputs; + auto const repeat = session.prepareRequest (*source, false, candidate); + QCOMPARE (repeat.metadata ().input_id, retained.metadata.input_id); + QCOMPARE (repeat.metadata ().valid_samples, retained.metadata.valid_samples); + QCOMPARE (repeat.options ().kin, retained.metadata.valid_samples); + QCOMPARE (source->params.kin, liveSamples); + QVERIFY (!repeat.options ().newdat); + QCOMPARE (repeat.options ().nagain, again); + if (again) + { + QVERIFY (repeat.metadata ().analysis_id != retained.metadata.analysis_id); + QCOMPARE (repeat.metadata ().attempt_no, int32_t {1}); + } + else + { + QCOMPARE (repeat.metadata ().analysis_id, retained.metadata.analysis_id); + QCOMPARE (repeat.metadata ().attempt_no, retained.lastAttempt + 1); + } + auto const repeated = session.submit (repeat); + QVERIFY (repeated); + inputs = candidate; + QVERIFY (repeated.samples == retained.samples); + QCOMPARE (shared.payload.d2[0], short {17}); + QCOMPARE (shared.payload.params.nfqso, 1234); + QCOMPARE (shared.payload.params.kin, retained.metadata.valid_samples); + QCOMPARE (shared.metadata.valid_samples, retained.metadata.valid_samples); + QCOMPARE (shared.metadata.input_id, retained.metadata.input_id); + QVERIFY (!shared.payload.params.newdat); + QCOMPARE (shared.payload.params.nagain, again); + QCOMPARE (source->params.kin, liveSamples); + QCOMPARE (inputs.inputId (), liveInput); + QCOMPARE (inputs.analysisId (), rollover ? liveAnalysis : repeat.metadata ().analysis_id); + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + + source->params.nagain = false; + auto const continued = session.prepareRequest (*source, false, inputs); + QCOMPARE (continued.metadata ().input_id, repeat.metadata ().input_id); + QCOMPARE (continued.metadata ().analysis_id, repeat.metadata ().analysis_id); + QCOMPARE (continued.metadata ().attempt_no, repeat.metadata ().attempt_no + 1); + QVERIFY (session.submit (continued)); + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + + source->params.newdat = true; + auto const nextLive = session.prepareRequest (*source, true, inputs); + QCOMPARE (nextLive.metadata ().input_id, liveInput); + QCOMPARE (nextLive.metadata ().analysis_id, + rollover ? liveAnalysis : continued.metadata ().analysis_id); + QCOMPARE (nextLive.metadata ().attempt_no, + rollover ? 1 : continued.metadata ().attempt_no + 1); + QCOMPARE (nextLive.metadata ().valid_samples, liveSamples); + auto const fresh = session.submit (nextLive); + QVERIFY (fresh); + QVERIFY (fresh.samples != retained.samples); + QCOMPARE (shared.payload.d2[0], short {99}); + session.shutdown (); +} + +void TestDecoderSession::diskPassesReserveAttemptNumbers () +{ + using namespace DecoderIpc; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + InputState inputs; + auto source = std::make_unique (); + source->params.nmode = 8; + source->params.ntrperiod = 15; + source->params.kin = 180000; + source->params.ndiskdat = true; + source->params.newdat = true; + for (auto firstAttempt : {1, 4}) + { + auto const request = session.prepareRequest (*source, source->params.newdat, inputs); + QCOMPARE (request.metadata ().attempt_no, firstAttempt); + QVERIFY (session.submit (request)); + qint32 generation {0}; + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + QCOMPARE (session.completedSnapshot ().lastAttempt, firstAttempt + 2); + source->params.newdat = false; + source->params.lmultift8 = true; + source->params.ndecoderstart = 1; + } + source->params.nagain = true; + auto const manual = session.prepareRequest (*source, false, inputs); + QCOMPARE (manual.metadata ().attempt_no, int32_t {1}); + QVERIFY (manual.metadata ().analysis_id != session.completedSnapshot ().metadata.analysis_id); + QVERIFY (session.submit (manual)); + qint32 generation {0}; + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + QCOMPARE (session.completedSnapshot ().lastAttempt, qint32 {1}); + source->params.nagain = false; + auto const continued = session.prepareRequest (*source, false, inputs); + QCOMPARE (continued.metadata ().analysis_id, manual.metadata ().analysis_id); + QCOMPARE (continued.metadata ().attempt_no, int32_t {2}); + session.shutdown (); +} + +void TestDecoderSession::deferredSnapshotKeepsItsInputAfterRollover () +{ + using namespace DecoderIpc; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + InputState inputs; + auto source = std::make_unique (); + source->params.nmode = 8; + source->params.ntrperiod = 15; + source->params.kin = 141696; + source->params.newdat = true; + QVERIFY (session.submit (session.prepareRequest (*source, true, inputs))); + + auto pending = std::make_unique (); + pending->params = source->params; + pending->params.lmultift8 = true; + pending->params.kin = 170000; + pending->metadata = inputs.nextMetadata (pending->params); + pending->samples[0] = 23; + QCOMPARE (pending->metadata.attempt_no, int32_t {2}); + inputs.beginInput (); + auto const liveInput = inputs.inputId (); + auto const liveAnalysis = inputs.analysisId (); + qint32 generation {0}; + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + QVERIFY (session.submit (Request::ft8 (*pending))); + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + + source->params.kin = 4096; + source->params.newdat = false; + auto const repeat = session.prepareRequest (*source, false, inputs); + QCOMPARE (repeat.metadata ().input_id, pending->metadata.input_id); + QCOMPARE (repeat.metadata ().analysis_id, pending->metadata.analysis_id); + QCOMPARE (repeat.metadata ().attempt_no, int32_t {3}); + QCOMPARE (repeat.options ().kin, 170000); + QVERIFY (session.submit (repeat)); + QCOMPARE (shared.payload.d2[0], short {23}); + QCOMPARE (source->params.kin, 4096); + QCOMPARE (inputs.inputId (), liveInput); + QCOMPARE (inputs.analysisId (), liveAnalysis); + session.shutdown (); +} + +void TestDecoderSession::reuseStartsNewAnalysisBeforeAttemptOverflow () +{ + using namespace DecoderIpc; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + InputState inputs; + inputs.beginInput (); + auto source = std::make_unique (); + source->params.nmode = 8; + source->params.ntrperiod = 15; + source->params.kin = 150000; + decoder_input_metadata_t metadata { + inputs.inputId (), inputs.analysisId (), std::numeric_limits::max (), 150000}; + QVERIFY (session.submit (Request::snapshot (*source, metadata))); + qint32 generation {0}; + QVERIFY (claim (shared, generation)); + QVERIFY (finish (shared, generation)); + QCOMPARE (session.complete ({0, 0, 0, generation}), Status::Ok); + + auto const request = session.prepareRequest (*source, false, inputs); + QCOMPARE (request.metadata ().input_id, metadata.input_id); + QVERIFY (request.metadata ().analysis_id != metadata.analysis_id); + QCOMPARE (request.metadata ().attempt_no, int32_t {1}); + QVERIFY (session.submit (request)); + session.shutdown (); +} + +void TestDecoderSession::resetRejectsCorruption () +{ + using namespace DecoderIpc; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Session session; + auto const key = memoryName (QUuid::createUuid ().toString ()); + QCOMPARE (session.open (key, directory.filePath ("worker.lock")), Status::Ok); + QCOMPARE (session.acceptReady (DECODER_IPC_VERSION), Status::Ok); + NativeSharedMemory peer; + QVERIFY2 (peer.attach (key.toStdString ()), peer.errorString ().c_str ()); + auto& shared = *static_cast (peer.data ()); + --shared.layout.payload_bytes; + QByteArray const before {static_cast (peer.data ()), static_cast (peer.size ())}; + QVERIFY (!session.reset ()); + session.shutdown (); + QCOMPARE (QByteArray (static_cast (peer.data ()), static_cast (peer.size ())), before); +} + +QTEST_GUILESS_MAIN (TestDecoderSession) +#include "test_decoder_session.moc" diff --git a/tests/unit/fst4/test_fst4_osd_depth.f90 b/tests/unit/fst4/test_fst4_osd_depth.f90 index dc41ccdf..00a0fe5f 100644 --- a/tests/unit/fst4/test_fst4_osd_depth.f90 +++ b/tests/unit/fst4/test_fst4_osd_depth.f90 @@ -1,5 +1,9 @@ program test_fst4_osd_depth + use fst4_bitmetrics, only: fst4_bitmetrics_workspace,get_fst4_bitmetrics_owned + use fst4_osd_workspace, only: fst4_osd_workspace_type + use fastosd240_74_module, only: fastosd240_74_owned + use ieee_arithmetic, only: ieee_is_finite implicit none integer, parameter :: n = 240 @@ -61,10 +65,80 @@ program test_fst4_osd_depth dmin128_zero == dmin128_negative, & 'negative (128,90) OSD depth preserves metrics') - print '(a)', 'FST4 OSD depth tests passed' + call check_osd_cache() + call check_bitmetric_cache() + + print '(a)', 'FST4 OSD depth and cache tests passed' contains + subroutine check_osd_cache() + type(fst4_osd_workspace_type), target :: reused,fresh + integer, parameter :: effective_bits(3)=[66,50,66] + integer :: pass,bits + do pass=1,size(effective_bits) + bits=effective_bits(pass) + call fastosd240_74_owned(reused,llr,bits,apmask,3,message_zero,cw_zero,nhard_zero,dmin_zero) + call fastosd240_74_owned(fresh,llr,bits,apmask,3,message_negative,cw_negative,nhard_negative,dmin_negative) + call require(all(message_zero==message_negative).and.all(cw_zero==cw_negative), & + 'reused FST4W OSD workspace matches a fresh workspace') + call require(nhard_zero==nhard_negative.and.dmin_zero==dmin_negative, & + 'reused FST4W OSD workspace preserves decode metrics') + call fresh%destroy() + enddo + call require(allocated(reused%generator(66)%matrix).and.allocated(reused%generator(50)%matrix), & + 'FST4W retains both effective-length generator caches') + call reused%destroy() + call require(.not.allocated(reused%matrix).and..not.allocated(reused%generator(66)%matrix), & + 'OSD destruction releases reusable storage') + end subroutine check_osd_cache + + subroutine check_bitmetric_cache() + type(fst4_bitmetrics_workspace), target :: reused,fresh + complex, allocatable :: frame(:),saved_wave(:,:) + real :: metrics(320,4),reference(320,4),power(0:3,160),reference_power(0:3,160) + integer :: tones(160),nss,pass,symbol,sample,quality,reference_quality + integer, parameter :: periods(3)=[12,24,12] + integer, parameter :: sync1(8)=[0,1,3,2,1,0,2,3],sync2(8)=[2,3,1,0,3,2,0,1] + real :: phase,twopi + logical :: bad,reference_bad + twopi=8*atan(1.0) + do symbol=1,160 + tones(symbol)=mod(3*symbol+symbol/7,4) + enddo + tones(1:8)=sync1 + tones(39:46)=sync2 + tones(77:84)=sync1 + tones(115:122)=sync2 + tones(153:160)=sync1 + do pass=1,size(periods) + nss=periods(pass) + allocate(frame(0:160*nss-1)) + do symbol=1,160 + do sample=0,nss-1 + phase=twopi*(tones(symbol)-1.5)*sample/nss + frame((symbol-1)*nss+sample)=cmplx(cos(phase),sin(phase)) + & + 0.03*cmplx(cos(real(17*symbol+3*sample)),sin(real(11*symbol+7*sample))) + enddo + enddo + call get_fst4_bitmetrics_owned(reused,frame,nss,metrics,power,quality,bad) + call require(.not.bad.and.quality==80,'ideal frame reaches complete sync-bit processing') + call require(reused%nss==nss.and.size(reused%ci,1)>=nss,'cache key follows symbol-size changes') + if(pass==3) call require(size(reused%ci,1)==24,'smaller symbols retain workspace capacity') + call require(all(ieee_is_finite(metrics)),'finite ideal-frame bit metrics') + if(allocated(fresh%ci)) deallocate(fresh%ci,fresh%one,fresh%zero,fresh%s2) + fresh%nss=0 + call get_fst4_bitmetrics_owned(fresh,frame,nss,reference,reference_power,reference_quality,reference_bad) + call require(.not.reference_bad.and.reference_quality==quality,'fresh and reused cache sync quality') + call require(all(metrics==reference).and.all(power==reference_power),'cache invalidation matches fresh workspace') + saved_wave=reused%ci(1:nss,:) + call get_fst4_bitmetrics_owned(reused,frame,nss,metrics,power,quality,bad) + call require(all(reused%ci(1:nss,:)==saved_wave),'same symbol size retains ideal waveforms') + call require(all(metrics==reference),'same symbol size retains bit metrics') + deallocate(frame) + enddo + end subroutine check_bitmetric_cache + subroutine require(condition, description) logical, intent(in) :: condition character(len=*), intent(in) :: description diff --git a/tests/unit/ft8/CMakeLists.txt b/tests/unit/ft8/CMakeLists.txt index 18eb4557..9e2c95ec 100644 --- a/tests/unit/ft8/CMakeLists.txt +++ b/tests/unit/ft8/CMakeLists.txt @@ -11,13 +11,12 @@ add_executable (test_ft8_mtd_decode_coordinator ${CMAKE_SOURCE_DIR}/Ft8MtdDecodeCoordinator.cpp ${CMAKE_SOURCE_DIR}/Ft8MtdDecodeScheduler.cpp ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp - ${CMAKE_SOURCE_DIR}/lib/decoder_ipc_control.cpp ) target_include_directories (test_ft8_mtd_decode_coordinator PRIVATE ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/lib ) -target_link_libraries (test_ft8_mtd_decode_coordinator Qt5::Test) +target_link_libraries (test_ft8_mtd_decode_coordinator wsjt_cxx Qt5::Test) add_test (NAME test_ft8_mtd_decode_coordinator COMMAND test_ft8_mtd_decode_coordinator) add_executable (test_ft8_decode_ranges diff --git a/tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp b/tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp index 2debacb3..51d79a11 100644 --- a/tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp +++ b/tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp @@ -20,6 +20,7 @@ namespace pending->payload.params.nmode = 8; pending->payload.params.lmultift8 = true; pending->payload.params.nutc = nutc; + pending->payload.metadata = {period, period + 1000, 2, 170000}; pending->payload.samples[0] = firstSample; pending->context.mode = "FT8"; pending->context.periodFrequency = 14074000; @@ -27,6 +28,8 @@ namespace pending->context.multithreadFt8 = true; pending->context.ft8ThreadCount = 4; pending->context.decodeDepth = 3; + pending->context.inputId = pending->payload.metadata.input_id; + pending->context.analysisId = pending->payload.metadata.analysis_id; return pending; } @@ -62,8 +65,9 @@ namespace return decision.action; } - return coordinator.deferFinal ( - pendingDecode (period, nutc, firstSample)); + auto pending = pendingDecode (period, nutc, firstSample); + currentContext = pending->context; + return coordinator.deferFinal (std::move (pending)); } void completeAndDrain () @@ -76,7 +80,9 @@ namespace if (!coordinator.hasPending ()) return; auto const outcome = coordinator.drainPending ( - [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return true;}, + [this] (Ft8MtdDecodeCoordinator::PendingMtdDecode const& pending) { + return pending.context.hasSameFt8PendingIdentity (currentContext); + }, [this] (Ft8MtdDecodeCoordinator::PendingMtdDecode const& pending) { active = true; activeStage = Stage::Final; @@ -85,6 +91,7 @@ namespace publishedNutcs.push_back (pending.payload.params.nutc); publishedFirstSamples.push_back (pending.payload.samples[0]); publishedContext = pending.context; + publishedMetadata = pending.payload.metadata; return PendingPublishResult::Published; }); QCOMPARE (outcome.result, DrainResult::Published); @@ -103,6 +110,8 @@ namespace std::vector publishedNutcs; std::vector publishedFirstSamples; DecodeOperatingContext publishedContext; + DecodeOperatingContext currentContext; + decoder_input_metadata_t publishedMetadata {}; }; } @@ -112,6 +121,7 @@ class TestFt8MtdDecodeCoordinator final : public QObject private Q_SLOTS: void slowEarlyDecodeRetainsAndPublishesFinalOnce (); + void receiveRolloverRetainsPendingFinal (); void unrelatedCompletionDoesNotPublishPendingFinal (); void multiPeriodOverrunPublishesOnlyNewestFinal (); void pendingSnapshotIsImmutable (); @@ -141,6 +151,27 @@ void TestFt8MtdDecodeCoordinator::slowEarlyDecodeRetainsAndPublishesFinalOnce () QVERIFY (!backend.coordinator.hasPending ()); } +void TestFt8MtdDecodeCoordinator::receiveRolloverRetainsPendingFinal () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 100, 1); + QCOMPARE (backend.submitFinal (100, 120000, 17), Action::DeferFinal); + ++backend.currentContext.inputId; + ++backend.currentContext.analysisId; + backend.currentContext.sequenceStart = QDateTime::fromMSecsSinceEpoch (1515000); + + backend.completeAndDrain (); + + QVERIFY (backend.publishedPeriods == std::vector ({100, 100})); + QCOMPARE (backend.publishedNutcs.back (), 120000); + QCOMPARE (backend.publishedFirstSamples.back (), short {17}); + QCOMPARE (backend.publishedMetadata.input_id, int64_t {100}); + QCOMPARE (backend.publishedMetadata.analysis_id, int64_t {1100}); + QCOMPARE (backend.publishedMetadata.attempt_no, int32_t {2}); + QCOMPARE (backend.publishedMetadata.valid_samples, int32_t {170000}); + QVERIFY (!backend.coordinator.hasPending ()); +} + void TestFt8MtdDecodeCoordinator::unrelatedCompletionDoesNotPublishPendingFinal () { FakeBackend backend; @@ -292,11 +323,16 @@ void TestFt8MtdDecodeCoordinator::changedContextDropsPendingWithoutPublishing () { Ft8MtdDecodeCoordinator coordinator; coordinator.request (Stage::Final, 520, 1, true); - coordinator.deferFinal (pendingDecode (520, 160030, 53)); + auto pending = pendingDecode (520, 160030, 53); + auto current = pending->context; + ++current.ft8ThreadCount; + coordinator.deferFinal (std::move (pending)); int publishCalls {0}; auto const outcome = coordinator.drainPending ( - [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return false;}, + [¤t] (Ft8MtdDecodeCoordinator::PendingMtdDecode const& pending) { + return pending.context.hasSameFt8PendingIdentity (current); + }, [&] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) { ++publishCalls; return PendingPublishResult::Published; diff --git a/tests/unit/jpl/test_jpl_resilience.f90 b/tests/unit/jpl/test_jpl_resilience.f90 index b37cd470..797fa87f 100644 --- a/tests/unit/jpl/test_jpl_resilience.f90 +++ b/tests/unit/jpl/test_jpl_resilience.f90 @@ -386,8 +386,39 @@ contains call require(all(blank_dx_sub_values([5,6,11,14]).eq. & 0.0_real64) .and. blank_dx_sub_integers(2).eq.0, & 'blank grids preserve astrosub DX clearing') + + call test_home_coordinate_path(path) end subroutine test_blank_grid_compatibility + subroutine test_home_coordinate_path(path) + character(len=*), intent(in) :: path + character(len=6) :: home_grid='FN20qi',dx_grid='JN18du' + real(c_double), parameter :: centre_lat=40.354166666666664_c_double + real(c_double), parameter :: centre_lon=-74.625_c_double + real(c_double) :: grid_values(14),centre_values(14),offset_values(14) + integer(c_int) :: grid_integers(3),centre_integers(3),offset_integers(3) + integer(c_int) :: grid_result,centre_result,offset_result + + call astrosub_coordinate_values(home_grid,dx_grid,path,.false._c_bool, & + 0.0_c_double,0.0_c_double,grid_values,grid_integers,grid_result) + call astrosub_coordinate_values(home_grid,dx_grid,path,.true._c_bool, & + centre_lat,centre_lon,centre_values,centre_integers,centre_result) + call astrosub_coordinate_values(home_grid,dx_grid,path,.true._c_bool, & + centre_lat+0.01_c_double,centre_lon,offset_values,offset_integers,& + offset_result) + + call require(grid_result.eq.centre_result, & + 'grid-centre coordinates preserve ephemeris result') + call require(all(grid_integers.eq.centre_integers), & + 'grid-centre coordinates reproduce grid-path integer outputs') + call require(maxval(abs(grid_values-centre_values)).lt.1.0e-9_c_double, & + 'grid-centre coordinates reproduce grid-path values') + call require(offset_result.eq.grid_result, & + 'offset coordinates preserve ephemeris result') + call require(offset_integers(3).ne.grid_integers(3), & + 'offset coordinates change ndop00') + end subroutine test_home_coordinate_path + subroutine test_optional_sections(path) character(len=*), intent(in) :: path real(real64) :: vector(6) @@ -490,7 +521,7 @@ contains outputs(5),outputs(6),outputs(7),outputs(8),outputs(9), & outputs(10),outputs(11),outputs(12),outputs(13), & outputs(14),outputs(15),outputs(16),outputs(17), & - outputs(18),outputs(19),result) + outputs(18),outputs(19),result,.false.,0.d0,0.d0) end subroutine direct_astro_values subroutine astro_values(uth,dfdt,dfdt0,result) @@ -502,6 +533,7 @@ contains character(len=6) :: mygrid='FN20qi',hisgrid='JN18du' call astro0(2024,1,1,uth,144000000.0_real64,mygrid,hisgrid, & + .false.,0.d0,0.d0, & output(1),output(2),output(3),output(4),output(5), & output(6),ntsky,ndop,ndop00,output(7),output(8),output(9), & output(10),output(11),output(12),output(13),output(14), & @@ -515,7 +547,8 @@ contains integer, intent(out) :: integer_values(3),result call astro0(2024,1,1,12.0_real64,144000000.0_real64,mygrid, & - hisgrid,values(1),values(2),values(3),values(4),values(5), & + hisgrid,.false.,0.d0,0.d0, & + values(1),values(2),values(3),values(4),values(5), & values(6),integer_values(1),integer_values(2), & integer_values(3),values(7),values(8),values(9),values(10),& values(11),values(12),values(13),values(14),values(15), & @@ -523,6 +556,31 @@ contains result) end subroutine grid_astro_values + subroutine astrosub_coordinate_values(mygrid,hisgrid,jpl_path, & + use_home_coordinates,home_latitude,home_longitude,values, & + integer_values,result) + character(len=*), intent(in) :: mygrid,hisgrid,jpl_path + logical(c_bool), intent(in) :: use_home_coordinates + real(c_double), intent(in) :: home_latitude,home_longitude + real(c_double), intent(out) :: values(14) + integer(c_int), intent(out) :: integer_values(3),result + character(kind=c_char), target :: mygrid_c(7),hisgrid_c(7) + character(kind=c_char), target :: azel_file_c(64),jpl_path_c(1025) + + call assign_c_string(mygrid,mygrid_c) + call assign_c_string(hisgrid,hisgrid_c) + call assign_c_string('home-coordinate-azel.dat',azel_file_c) + call assign_c_string(jpl_path,jpl_path_c) + call astrosub(2024_c_int,1_c_int,1_c_int,12.0_c_double, & + 10368200000.0_c_double,c_loc(mygrid_c),c_loc(hisgrid_c), & + use_home_coordinates,home_latitude,home_longitude, & + values(1),values(2),values(3),values(4),values(5), & + values(6),integer_values(1),integer_values(2), & + integer_values(3),values(7),values(8),values(9),values(10),& + values(11),.false._c_bool,values(12),values(13),values(14), & + .false._c_bool,c_loc(azel_file_c),c_loc(jpl_path_c),result) + end subroutine astrosub_coordinate_values + subroutine astrosub_values(mygrid,hisgrid,jpl_path,values, & integer_values,result) character(len=*), intent(in) :: mygrid,hisgrid,jpl_path @@ -537,6 +595,7 @@ contains call assign_c_string(jpl_path,jpl_path_c) call astrosub(2024_c_int,1_c_int,1_c_int,12.0_c_double, & 144000000.0_c_double,c_loc(mygrid_c),c_loc(hisgrid_c), & + .false._c_bool,0.0_c_double,0.0_c_double, & values(1),values(2),values(3),values(4),values(5), & values(6),integer_values(1),integer_values(2), & integer_values(3),values(7),values(8),values(9),values(10),& diff --git a/tests/unit/jt65/test_jt65_decode_pipeline.f90 b/tests/unit/jt65/test_jt65_decode_pipeline.f90 index 414b6f80..89d011f0 100644 --- a/tests/unit/jt65/test_jt65_decode_pipeline.f90 +++ b/tests/unit/jt65/test_jt65_decode_pipeline.f90 @@ -54,12 +54,13 @@ program test_jt65_decode_pipeline type(jt65_decoder) :: decoder real(real32), allocatable :: samples(:) allocate(samples(jt65_sample_count)) - call test_clean_modes(samples) + call test_clean_modes_and_reuse(samples) call test_ooo_signal(samples) - call test_silence_and_frequency_rejection(samples) - call test_decoder_reuse(samples, decoder) + call test_frequency_rejection(samples) call test_auto_clear_average(samples, decoder) call test_duplicate_average_cursor + call decoder%destroy() + deallocate(samples) print '(a)', 'JT65 decoder pipeline tests passed' contains @@ -155,12 +156,22 @@ contains call require(ieee_is_finite(callback_width), description//' finite width metric') end subroutine require_decode - subroutine test_clean_modes(waveform) + subroutine test_clean_modes_and_reuse(waveform) real(real32), intent(inout) :: waveform(:) call reset_capture() call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64) call decode_signal(decoder, waveform, 0, .true.) - call require_decode('K1ABC W9XYZ FN42', 'JT65A clean signal') + call require_decode('K1ABC W9XYZ FN42', 'first JT65A reused-decoder signal') + + waveform = 0.0_real32 + call reset_capture() + call decode_signal(decoder, waveform, 0, .true.) + call require(callback_count == 0, 'reused decoder silence produces no callback') + + call reset_capture() + call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64) + call decode_signal(decoder, waveform, 0, .true.) + call require_decode('K1ABC W9XYZ FN42', 'second JT65A reused-decoder signal') call reset_capture() call make_jt65_wave(waveform, standard_tones, 4, 1500.0_real64) @@ -171,7 +182,7 @@ contains call make_jt65_wave(waveform, standard_tones, 2, 1500.0_real64) call decode_signal(decoder, waveform, 1, .true.) call require_decode('K1ABC W9XYZ FN42', 'JT65B clean signal') - end subroutine test_clean_modes + end subroutine test_clean_modes_and_reuse subroutine test_ooo_signal(waveform) real(real32), intent(inout) :: waveform(:) @@ -188,39 +199,14 @@ contains call require(callback_count == 0, 'JT65A HF OOO signal is rejected') end subroutine test_ooo_signal - subroutine test_silence_and_frequency_rejection(waveform) + subroutine test_frequency_rejection(waveform) real(real32), intent(inout) :: waveform(:) - waveform = 0.0_real32 - call reset_capture() - call decode_signal(decoder, waveform, 0, .true.) - call require(callback_count == 0, 'silence produces no callback') - call make_jt65_wave(waveform, standard_tones, 1, 3000.0_real64) call reset_capture() call decode_signal(decoder, waveform, 0, .true.) call require(callback_count == 0, 'out-of-window signal produces no callback') - end subroutine test_silence_and_frequency_rejection - - subroutine test_decoder_reuse(waveform, decoder_to_use) - real(real32), intent(inout) :: waveform(:) - type(jt65_decoder), intent(inout) :: decoder_to_use - - call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64) - call reset_capture() - call decode_signal(decoder_to_use, waveform, 0, .true.) - call require_decode('K1ABC W9XYZ FN42', 'first reused-decoder signal') - - waveform = 0.0_real32 - call reset_capture() - call decode_signal(decoder_to_use, waveform, 0, .true.) - call require(callback_count == 0, 'reused decoder silence produces no callback') - - call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64) - call reset_capture() - call decode_signal(decoder_to_use, waveform, 0, .true.) - call require_decode('K1ABC W9XYZ FN42', 'second reused-decoder signal') - end subroutine test_decoder_reuse + end subroutine test_frequency_rejection subroutine test_auto_clear_average(waveform, decoder_to_use) real(real32), intent(inout) :: waveform(:) diff --git a/tests/unit/jt65/test_jt65_xcor_silence.f90 b/tests/unit/jt65/test_jt65_xcor_silence.f90 index d43049b2..27fbadfb 100644 --- a/tests/unit/jt65/test_jt65_xcor_silence.f90 +++ b/tests/unit/jt65/test_jt65_xcor_silence.f90 @@ -1,15 +1,17 @@ program test_jt65_xcor_silence + use jt65_mod, only: jt65_work, ensure_jt65_workspace implicit none integer, parameter :: lag1 = -32, lag2 = 82, nhmax = 3413, nsmax = 552 - real :: ss(nsmax,nhmax), ccf(lag1:lag2), ccf0, flip + real :: ccf(lag1:lag2), ccf0, flip integer :: lagpk - common /sync/ ss call setup65 - ss = 0.0 + call ensure_jt65_workspace() + allocate(jt65_work%spectra(nsmax,nhmax)) + jt65_work%spectra = 0.0 lagpk = huge(0) call xcor(1,nsmax,126,lag1,lag2,ccf,ccf0,lagpk,flip,0.0,0) diff --git a/tests/unit/jt65/test_map65_jt65_handoff.f90 b/tests/unit/jt65/test_map65_jt65_handoff.f90 index d263bccd..71321300 100644 --- a/tests/unit/jt65/test_map65_jt65_handoff.f90 +++ b/tests/unit/jt65/test_map65_jt65_handoff.f90 @@ -3,7 +3,8 @@ program test_map65_jt65_handoff use iso_fortran_env, only: real32, real64 use, intrinsic :: ieee_arithmetic, only: ieee_get_flag, ieee_invalid, ieee_is_finite, & ieee_quiet_nan, ieee_set_flag, ieee_value - use decode1a_mod + use decode1a_mod, only: decode1a, jt65_demod_bin, jt65_demod_sample_rate, & + jt65_fft_size, jt65c_center_offset use filbig_mod use afc65b_mod, only: afc65b use jt65_test_fixture @@ -11,21 +12,56 @@ program test_map65_jt65_handoff use npar_ptrs_mod, only: nsmax_active implicit none - real(real32), allocatable :: dd(:,:) + real(real32), allocatable :: dd(:,:), mode_b_wave(:,:) real(real64), parameter :: map65_base_frequency = 118.0_real64 * 11025.0_real64 / 1024.0_real64 allocate(dd(4, nsmax_active)) + allocate(mode_b_wave(2, nsmax_active)) + call make_map65_wave(mode_b_wave, standard_tones, 2, map65_base_frequency) + dd(1:2,:) = mode_b_wave call test_mono_filter_output(dd) call test_afc_zero_signal() - call test_mode(dd, standard_tones, 1, 1, 'JT65A MAP65 handoff') - call test_mode(dd, standard_tones, 2, 1, 'JT65B MAP65 handoff') - call test_mode(dd, standard_tones, 4, 1, 'JT65C MAP65 handoff') - call test_mode(dd, ooo_tones, 1, -1, 'JT65A OOO MAP65 handoff') - call test_mode(dd, standard_tones, 2, 1, 'JT65B xpol MAP65 handoff', .true.) + call test_demodulation_bins() + call make_map65_wave(dd, standard_tones, 1, map65_base_frequency) + call test_mode(dd, 1, 1, 'JT65A MAP65 handoff') + dd(1:2,:) = mode_b_wave + call test_mode(dd, 2, 1, 'JT65B MAP65 handoff') + call make_map65_wave(dd, standard_tones, 4, map65_base_frequency) + call test_mode(dd, 4, 1, 'JT65C MAP65 handoff') + call make_map65_wave(dd, ooo_tones, 1, map65_base_frequency) + call test_mode(dd, 1, -1, 'JT65A OOO MAP65 handoff') + dd(1:2,:) = mode_b_wave + call test_mode(dd, 2, 1, 'JT65B xpol MAP65 handoff', .true.) print '(a)', 'MAP65 JT65 handoff tests passed' contains + subroutine test_demodulation_bins() + real(real64) :: frequency, mapped_frequency + integer :: bin, mode65, signed_bin, tone + + do mode65=1,4 + if(mode65.eq.3) cycle + do tone=1,66 + bin=jt65_demod_bin(mode65,tone) + call require(bin.ge.1 .and. bin.le.jt65_fft_size, & + 'JT65 demodulation bin is in range') + frequency=real((tone-1)*mode65,real64)*jt65_demod_sample_rate/ & + jt65_fft_size + if(mode65.eq.4) frequency=frequency-jt65c_center_offset + signed_bin=bin-1 + if(signed_bin.gt.jt65_fft_size/2) signed_bin=signed_bin-jt65_fft_size + mapped_frequency=real(signed_bin,real64)*jt65_demod_sample_rate/ & + jt65_fft_size + call require(abs(mapped_frequency-frequency).lt. & + jt65_demod_sample_rate/jt65_fft_size, & + 'JT65 tone frequency maps to the selected FFT bin') + call require(abs(frequency).lt.0.5_real64*jt65_demod_sample_rate, & + 'JT65 data tone fits the demodulation passband') + enddo + enddo + end subroutine test_demodulation_bins + subroutine require(condition, description) logical, intent(in) :: condition character(len=*), intent(in) :: description @@ -43,7 +79,6 @@ contains logical :: invalid_raised allocate(cx(nsmax_active/64), cy(nsmax_active/64)) - call make_map65_wave(waveform, standard_tones, 2, map65_base_frequency) waveform(3:4,:) = ieee_value(0.0_real32, ieee_quiet_nan) newdat = 1 call ieee_set_flag(ieee_invalid, .false.) @@ -82,9 +117,8 @@ contains 'flat AFC objective has explicit detection defaults') end subroutine test_afc_zero_signal - subroutine test_mode(waveform, tones, mode65, polarity, description, cross_polarized) + subroutine test_mode(waveform, mode65, polarity, description, cross_polarized) real(real32), intent(inout) :: waveform(:,:) - integer, intent(in) :: tones(:) integer, intent(in) :: mode65 integer, intent(in) :: polarity character(len=*), intent(in) :: description @@ -97,7 +131,6 @@ contains character(len=22) :: decoded real :: dphi, sync2, a(5), dt, pol, qual - call make_map65_wave(waveform, tones, mode65, map65_base_frequency) xpol = .false. if (present(cross_polarized)) xpol = cross_polarized if (xpol) then diff --git a/tests/unit/jt9/test_jt9_cli_validation.cmake b/tests/unit/jt9/test_jt9_cli_validation.cmake index 16f2499e..da5ec292 100644 --- a/tests/unit/jt9/test_jt9_cli_validation.cmake +++ b/tests/unit/jt9/test_jt9_cli_validation.cmake @@ -15,3 +15,16 @@ require_rejection (-Q 6) require_rejection (-Q invalid) require_rejection (-p invalid) require_rejection (-m invalid) + +foreach (option --patience -w) + execute_process ( + COMMAND "${JT9}" "${option}" 0 --version + RESULT_VARIABLE result + OUTPUT_VARIABLE stdout + ERROR_VARIABLE stderr) + if (NOT result EQUAL 0 OR NOT stdout MATCHES "^jt9 [0-9]" OR NOT stderr STREQUAL "") + message (FATAL_ERROR "${option} did not consume exactly one argument: ${stdout}${stderr}") + endif () +endforeach () + +require_rejection (--tr-period invalid) diff --git a/tests/unit/jt9/test_jt9_input_validation.f90 b/tests/unit/jt9/test_jt9_input_validation.f90 index c9c88370..4a0cc918 100644 --- a/tests/unit/jt9/test_jt9_input_validation.f90 +++ b/tests/unit/jt9/test_jt9_input_validation.f90 @@ -4,7 +4,7 @@ program test_jt9_input_validation integer :: integer_value, nutc real(kind=8) :: real_value - logical :: ok + logical :: ok, includes_seconds call parse_integer('42', integer_value, ok) call assert_true(ok .and. integer_value == 42, 'integer parsing accepts integers') @@ -39,6 +39,12 @@ program test_jt9_input_validation call parse_wav_filename_nutc('240101_123456.WAV', nutc) call assert_true(nutc == 123456, 'six-digit timestamp is read') + call parse_wav_filename_nutc('240101_001500.wav', nutc, includes_seconds) + call assert_true(nutc == 1500 .and. includes_seconds, 'midnight HHMMSS keeps its format') + + call parse_wav_filename_nutc('240101_1500.wav', nutc, includes_seconds) + call assert_true(nutc == 1500 .and. .not. includes_seconds, 'HHMM remains distinguishable from HHMMSS') + call parse_wav_filename_nutc('recording2026.wav', nutc) call assert_true(nutc == 0, 'four-digit suffix without separator defaults to midnight') diff --git a/tests/unit/jtty/CMakeLists.txt b/tests/unit/jtty/CMakeLists.txt index 8dd698d0..2ba22568 100644 --- a/tests/unit/jtty/CMakeLists.txt +++ b/tests/unit/jtty/CMakeLists.txt @@ -151,9 +151,64 @@ add_executable (test_jtty_messages test_jtty_messages.cpp) target_link_libraries (test_jtty_messages Qt5::Test) add_test (NAME test_jtty_messages COMMAND test_jtty_messages) -add_executable (test_jtty_draft_acceptance test_jtty_draft_acceptance.cpp) -target_link_libraries (test_jtty_draft_acceptance Qt5::Test) -add_test (NAME test_jtty_draft_acceptance COMMAND test_jtty_draft_acceptance) +add_executable (test_jtty_continuous_decode test_jtty_continuous_decode.f90) +target_include_directories (test_jtty_continuous_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_continuous_decode) +add_test (NAME test_jtty_continuous_decode COMMAND test_jtty_continuous_decode) +set_tests_properties (test_jtty_continuous_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_continuous_decode: all checks passed" + TIMEOUT 300 +) + +add_executable (test_jtty_spectrum + test_jtty_spectrum.cpp + ${CMAKE_SOURCE_DIR}/widgets/JttySpectrum.cpp) +target_link_libraries (test_jtty_spectrum PRIVATE Qt5::Test) +wsjt_link_common_fortran (test_jtty_spectrum) +add_test (NAME test_jtty_spectrum COMMAND test_jtty_spectrum) + +add_executable (test_jtty_waterfall + test_jtty_waterfall.cpp + ${CMAKE_SOURCE_DIR}/widgets/plotter.cpp) +target_link_libraries (test_jtty_waterfall PRIVATE wsjt_qt Qt5::Test) +wsjt_link_common_fortran (test_jtty_waterfall) +add_test (NAME test_jtty_waterfall COMMAND test_jtty_waterfall) +set_tests_properties (test_jtty_waterfall PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_executable (test_jtty_recording + test_jtty_recording.cpp + ${CMAKE_SOURCE_DIR}/JttyRecording.cpp) +target_link_libraries (test_jtty_recording wsjt_qt wsjt_qtmm Qt5::Test Qt5::Multimedia) +add_test (NAME test_jtty_recording COMMAND test_jtty_recording) + +add_executable (test_jtty_receive_history test_jtty_receive_history.cpp) +target_link_libraries (test_jtty_receive_history Qt5::Test) +add_test (NAME test_jtty_receive_history COMMAND test_jtty_receive_history) + +add_executable (test_jtty_receive_line test_jtty_receive_line.cpp) +target_link_libraries (test_jtty_receive_line Qt5::Test Qt5::Gui) +add_test (NAME test_jtty_receive_line COMMAND test_jtty_receive_line) +set_tests_properties (test_jtty_receive_line PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_executable (test_jtty_receive_results + test_jtty_receive_results.cpp + ${CMAKE_SOURCE_DIR}/JttyReceiveResultController.cpp + ${CMAKE_SOURCE_DIR}/Radio.cpp) +target_link_libraries (test_jtty_receive_results Qt5::Test Qt5::Gui) +add_test (NAME test_jtty_receive_results COMMAND test_jtty_receive_results) +set_tests_properties (test_jtty_receive_results PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_executable (test_jtty_tx_lifecycle test_jtty_tx_lifecycle.cpp) +target_link_libraries (test_jtty_tx_lifecycle Qt5::Test) +add_test (NAME test_jtty_tx_lifecycle COMMAND test_jtty_tx_lifecycle) + +add_executable (test_jtty_transmit_queue test_jtty_transmit_queue.cpp) +target_link_libraries (test_jtty_transmit_queue Qt5::Test) +add_test (NAME test_jtty_transmit_queue COMMAND test_jtty_transmit_queue) + +add_executable (test_jtty_live_entry test_jtty_live_entry.cpp) +target_link_libraries (test_jtty_live_entry Qt5::Test) +add_test (NAME test_jtty_live_entry COMMAND test_jtty_live_entry) add_executable (test_jtty_n1mm test_jtty_n1mm.cpp) target_link_libraries (test_jtty_n1mm Qt5::Test) diff --git a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp index 1d666113..c2b3b45b 100644 --- a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp +++ b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp @@ -6,7 +6,7 @@ extern "C" void genjtty_atoms_c (Jtty::NativeAtomDescriptor const atoms[], int natoms, int tones[], int* nsym, int* status); -extern "C" void genjtty_profile_ (char*, int const*, int*, int*, fortran_charlen_t); +extern "C" void genjtty_profile_ (char*, int const*, int*, int*, int*, int const*, fortran_charlen_t); extern "C" int jtty_cpp_n1mm_smoke (int tones[], int* nsym) { @@ -22,7 +22,7 @@ extern "C" int jtty_cpp_n1mm_smoke (int tones[], int* nsym) return status; } -extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[], int chained) +extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[]) { Jtty::NativeMacroContext const context {QStringLiteral ("K1ABC"), {}, 0}; auto const compiled = Jtty::compileNativeMacro ( @@ -30,7 +30,7 @@ extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[], int chain *nsym = 0; int status = static_cast (Jtty::NativeEncodeStatus::InvalidDescriptor); if (compiled.isNative ()) { - auto const frame = Jtty::transmitFrame (compiled.text, chained != 0).toLatin1 (); + auto const frame = Jtty::transmitFrame (compiled.text).toLatin1 (); std::copy (frame.cbegin (), frame.cend (), text); genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), tones, nsym, &status); @@ -59,18 +59,22 @@ extern "C" int jtty_cpp_rtty_smoke (int tones[], int* nsym) } genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), tones, nsym, &status); if (status != static_cast (Jtty::NativeEncodeStatus::Ok) || *nsym <= 0) return status; - auto text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + auto text = Jtty::transmitFrame (example.raw).toLatin1 (); int packedSymbols {}; + std::array frameStarts {}; + int const isFinal = 1; auto profile = static_cast (context.exchangeProfile); - genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, text.size ()); + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, + frameStarts.data (), &isFinal, text.size ()); if (packedSymbols != *nsym || !std::equal (tones, tones + *nsym, packedTones.cbegin ()) || - text != Jtty::transmitFrame (example.canonical, false).toLatin1 ()) { + text != Jtty::transmitFrame (example.canonical).toLatin1 ()) { return static_cast (Jtty::NativeEncodeStatus::InvalidDescriptor); } - text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + text = Jtty::transmitFrame (example.raw).toLatin1 (); profile = static_cast (Jtty::NativeExchangeProfile::None); - genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, text.size ()); - if (packedSymbols != 2 * *nsym || text != Jtty::transmitFrame (example.raw, false).toLatin1 ()) { + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, + frameStarts.data (), &isFinal, text.size ()); + if (packedSymbols != 2 * *nsym || text != Jtty::transmitFrame (example.raw).toLatin1 ()) { return static_cast (Jtty::NativeEncodeStatus::InvalidDescriptor); } } diff --git a/tests/unit/jtty/test_jtty_continuous_decode.f90 b/tests/unit/jtty/test_jtty_continuous_decode.f90 new file mode 100644 index 00000000..38de8224 --- /dev/null +++ b/tests/unit/jtty/test_jtty_continuous_decode.f90 @@ -0,0 +1,316 @@ +program test_jtty_continuous_decode + use iso_c_binding, only: c_int, c_int16_t, c_int64_t, c_float, c_double, c_char + use jtty_receive_context + use jtty_mdec, only: UPDATE_GROWING, UPDATE_COMPLETE, UPDATE_EXPIRED, UPDATE_RECEPTION_ENDED + use jtty_fec, only: is13, TOTAL_K + use jtty_mod, only: MAX_FRAMES + implicit none + + integer, parameter :: nsps=384, rate=12000, step=59*nsps/4, block=3456 + integer, parameter :: max_events=256 + integer, parameter :: review_interval=16*rate + integer(c_int64_t), parameter :: high_origin=2_c_int64_t**40 + character(len=*), parameter :: wanted='WB9XYZ 599 0123' + character(len=*), parameter :: overlap_strong='MAYBE YOU SHOULD HELP' + character(len=*), parameter :: overlap_weak='CLAUDE CO 3 MIN TRANSITION' + type :: update_event + integer(c_int64_t) :: id=0 + character(len=80) :: text='' + real(c_double) :: start=0,latest=0 + real(c_float) :: frequency=0 + integer(c_int) :: terminal=0 + end type update_event + type(update_event) :: reference(max_events),rotated(max_events),interleaved(max_events) + integer(c_int16_t), allocatable :: pcm(:),partial(:) + integer :: nreference,nrotated,ninterleaved + + allocate(pcm(200*rate)) + pcm=0 + call add_message(pcm,2401,.false.) + call add_message(pcm,374*step+1,.true.) + + call run_stream(pcm,0_c_int64_t,0,.false.,reference,nreference) + call run_stream(pcm,0_c_int64_t,180*rate,.false.,rotated,nrotated) + call compare_events(reference,nreference,rotated,nrotated,0.0_c_double) + call run_stream(pcm,high_origin,7*rate,.true.,interleaved,ninterleaved) + call compare_events(reference,nreference,interleaved,ninterleaved,real(high_origin,c_double)/rate) + call expect(count_complete(reference,nreference).eq.2, & + 'strong and damaged-sync messages complete inside and across the 180-second boundary') + call expect(count_growth(reference,nreference).ge.2,'multi-frame messages publish growing updates') + + allocate(partial(15*rate)) + partial=0 + partial(1:3*rate)=pcm(1:3*rate) + call check_terminal(partial,3*rate,UPDATE_RECEPTION_ENDED) + call check_terminal(partial,size(partial),UPDATE_EXPIRED) + + pcm=0 + call mix_message(pcm,2401,overlap_strong,1500.0,14000.0) + call mix_message(pcm,7201,overlap_weak,1504.0,12000.0) + call mix_message(pcm,374*step+2401,overlap_strong,1500.0,14000.0) + call mix_message(pcm,374*step+7201,overlap_weak,1504.0,12000.0) + call run_stream(pcm,0_c_int64_t,0,.false.,reference,nreference,2800) + call expect_overlap(reference,nreference) + call run_stream(pcm,0_c_int64_t,180*rate,.false.,rotated,nrotated,2800) + call compare_events(reference,nreference,rotated,nrotated,0.0_c_double) + call run_stream(pcm,high_origin,7*rate,.true.,interleaved,ninterleaved,2800) + call compare_events(reference,nreference,interleaved,ninterleaved,real(high_origin,c_double)/rate) + + print *, 'test_jtty_continuous_decode: all checks passed' + +contains + + subroutine add_message(samples,start,damaged_sync) + integer(c_int16_t), intent(inout) :: samples(:) + integer, intent(in) :: start + logical, intent(in) :: damaged_sync + integer :: tones(MAX_FRAMES*(size(is13)+TOTAL_K)),qrm_tones(size(is13)+TOTAL_K) + integer :: symbols,n,qrm_symbols,i,offset,span,value + real, allocatable :: wave(:),qrm(:),combined(:) + complex, allocatable :: analytic(:) + character(len=80) :: message + + message=wanted + call genjtty(message,tones,symbols) + call expect(symbols.eq.3*59,'fixture retains its three-frame encoding') + if(damaged_sync) tones(60:60+size(is13)-1)=mod(is13+2,4) + n=symbols*nsps + allocate(wave(n),analytic(n+59*nsps),combined(n+59*nsps)) + call gen_jttywave(tones,symbols,nsps,2.0,12000.0,1500.0,analytic,wave,0,n) + combined=0 + combined(1:n)=wave + if(damaged_sync) then + message='N2PPI' + call genjtty(message,qrm_tones,qrm_symbols) + allocate(qrm(qrm_symbols*nsps)) + call gen_jttywave(qrm_tones,qrm_symbols,nsps,2.0,12000.0,1540.0,analytic,qrm,0,size(qrm)) + offset=1 + do while(offset.le.size(combined)) + span=min(size(qrm),size(combined)-offset+1) + combined(offset:offset+span-1)=combined(offset:offset+span-1)+0.3*qrm(1:span) + offset=offset+span + enddo + endif + do i=1,size(combined) + value=nint(30000.0*combined(i)) + samples(start+i-1)=int(max(-32767,min(32767,value)),c_int16_t) + enddo + end subroutine add_message + + subroutine mix_message(samples,start,text,frequency,amplitude) + integer(c_int16_t), intent(inout) :: samples(:) + integer, intent(in) :: start + character(len=*), intent(in) :: text + real, intent(in) :: frequency,amplitude + integer :: tones(MAX_FRAMES*(size(is13)+TOTAL_K)),symbols,n,i,mixed + real, allocatable :: wave(:) + complex, allocatable :: analytic(:) + character(len=80) :: message + + message=text + call genjtty(message,tones,symbols) + n=symbols*nsps + allocate(wave(n),analytic(n)) + call gen_jttywave(tones,symbols,nsps,2.0,12000.0,frequency,analytic,wave,0,n) + call expect(start+n-1+59*nsps.le.size(samples), & + 'the overlapping transmission and final search/retro padding fit the fixture') + do i=1,n + mixed=int(samples(start+i-1))+nint(amplitude*wave(i)) + samples(start+i-1)=int(max(-32767,min(32767,mixed)),c_int16_t) + enddo + end subroutine mix_message + + subroutine run_stream(samples,origin,storage_size,review,events,event_count,high_frequency) + integer(c_int16_t), intent(in) :: samples(:) + integer(c_int64_t), intent(in) :: origin + integer, intent(in) :: storage_size + logical, intent(in) :: review + type(update_event), intent(out) :: events(:) + integer, intent(out) :: event_count + integer, optional, intent(in) :: high_frequency + integer(c_int) :: live,manual,processed,ignored + integer :: available,first,rotations,discard_count,nfb,review_restarts + integer :: next_review_sample,last_review_restart + integer(c_int64_t) :: required + type(update_event) :: discarded(max_events) + + event_count=0 + nfb=1499 + if(present(high_frequency)) nfb=high_frequency + rotations=0 + review_restarts=0 + next_review_sample=0 + last_review_restart=0 + first=1 + live=jtty_rx_create() + call expect(live.ne.0,'live decoder context is available') + call jtty_rx_begin(live,1_c_int64_t,origin,origin,nsps) + manual=0 + if(review) then + manual=jtty_rx_create() + call expect(manual.ne.0,'review has independent decoder state') + call jtty_rx_begin(manual,2_c_int64_t,0_c_int64_t,0_c_int64_t,nsps) + endif + available=0 + do while(available.lt.size(samples)) + available=min(available+block,size(samples)) + do + processed=jtty_rx_process(live,samples(first:),available-first+1, & + origin+int(first-1,c_int64_t),origin+int(available,c_int64_t),1,200,nfb,1500.0,50.0) + call expect(processed.ge.0,'retained audio covers the forward and retro search windows') + call collect(live,events,event_count) + if(processed.eq.0) exit + if(review .and. available.ge.next_review_sample) then + ignored=jtty_rx_process(manual,samples,9*rate,0_c_int64_t,int(9*rate,c_int64_t), & + 1,200,nfb,1500.0,50.0) + call expect(ignored.ge.0,'review decoding remains independently valid') + discard_count=0 + call collect(manual,discarded,discard_count) + if(ignored.eq.0) then + call jtty_rx_end(manual,UPDATE_RECEPTION_ENDED) + discard_count=0 + call collect(manual,discarded,discard_count) + call jtty_rx_begin(manual,2_c_int64_t,0_c_int64_t,0_c_int64_t,nsps) + review_restarts=review_restarts+1 + last_review_restart=available + next_review_sample=next_review_sample+review_interval + endif + endif + enddo + if(storage_size.gt.0 .and. available-first+1.ge.storage_size) then + required=jtty_rx_next_required_sample(live)-origin + if(required.gt.int(first-1,c_int64_t)) then + first=int(required)+1 + rotations=rotations+1 + endif + endif + enddo + if(storage_size.gt.0) call expect(rotations.gt.0,'the fixture actually rotates storage') + if(storage_size.eq.7*rate) call expect(rotations.gt.20,'short storage repeats many rotations') + if(review) call expect(review_restarts.gt.10,'review decoding remains active through later storage boundaries') + if(review) call expect(last_review_restart.ge.180*rate,'review decoding continues past the 180-second boundary') + call jtty_rx_end(live,UPDATE_RECEPTION_ENDED) + call collect(live,events,event_count) + call jtty_rx_destroy(live) + if(manual.ne.0) call jtty_rx_destroy(manual) + end subroutine run_stream + + subroutine collect(handle,events,event_count) + integer(c_int), intent(in) :: handle + type(update_event), intent(inout) :: events(:) + integer, intent(inout) :: event_count + character(kind=c_char) :: text(80*30) + integer(c_int64_t) :: ids(30) + real(c_float) :: frequencies(30) + real(c_double) :: starts(30),latest(30) + integer(c_int) :: terminals(30),snrs(30),n + integer :: i,j + + do + n=jtty_rx_take_updates(handle,30,text,ids,frequencies,starts,latest,terminals,snrs) + do i=1,n + call expect(event_count.lt.size(events),'update collection remains bounded') + event_count=event_count+1 + do j=1,80 + events(event_count)%text(j:j)=text((i-1)*80+j) + enddo + events(event_count)%id=ids(i) + events(event_count)%frequency=frequencies(i) + events(event_count)%start=starts(i) + events(event_count)%latest=latest(i) + events(event_count)%terminal=terminals(i) + enddo + if(n.lt.30) exit + enddo + end subroutine collect + + subroutine compare_events(expected,nexpected,actual,nactual,time_offset) + type(update_event), intent(in) :: expected(:),actual(:) + integer, intent(in) :: nexpected,nactual + real(c_double), intent(in) :: time_offset + integer :: i,j + + call expect(nexpected.eq.nactual,'storage and context changes preserve every message update') + do i=1,nexpected + call expect(expected(i)%text.eq.actual(i)%text,'storage and context changes preserve exact text') + call expect(expected(i)%terminal.eq.actual(i)%terminal,'terminal reasons remain unchanged') + call expect(abs(expected(i)%frequency-actual(i)%frequency).lt.0.001,'frequency estimates remain unchanged') + call expect(abs(expected(i)%start-(actual(i)%start-time_offset)).lt.0.000001_c_double, & + 'message start timestamps remain stable at large sample origins') + call expect(abs(expected(i)%latest-(actual(i)%latest-time_offset)).lt.0.000001_c_double, & + 'latest-frame timestamps remain stable at large sample origins') + do j=1,i + call expect((expected(i)%id.eq.expected(j)%id).eqv.(actual(i)%id.eq.actual(j)%id), & + 'growing updates preserve logical identity without merging separate messages') + enddo + enddo + end subroutine compare_events + + subroutine expect_overlap(events,n) + type(update_event), intent(in) :: events(:) + integer, intent(in) :: n + integer :: i + logical :: complete + + complete=count_complete(events,n,overlap_strong).eq.2 .and. count_complete(events,n,overlap_weak).eq.2 + if(.not.complete) then + do i=1,n + write(*,'(i0,1x,f8.3,1x,f8.3,1x,a)') events(i)%terminal,events(i)%start,events(i)%frequency,trim(events(i)%text) + enddo + endif + call expect(complete,'both stronger and weaker overlapping messages complete inside and across the boundary') + end subroutine expect_overlap + + integer function count_complete(events,n,message) + type(update_event), intent(in) :: events(:) + integer, intent(in) :: n + character(len=*), optional, intent(in) :: message + integer :: i + character(len=80) :: expected + + count_complete=0 + expected=wanted + if(present(message)) expected=message + do i=1,n + if(trim(events(i)%text).eq.trim(expected) .and. events(i)%terminal.eq.UPDATE_COMPLETE) & + count_complete=count_complete+1 + enddo + end function count_complete + + integer function count_growth(events,n) + type(update_event), intent(in) :: events(:) + integer, intent(in) :: n + + count_growth=count(events(1:n)%terminal.eq.UPDATE_GROWING) + end function count_growth + + subroutine check_terminal(samples,stop,reason) + integer(c_int16_t), intent(in) :: samples(:) + integer, intent(in) :: stop,reason + integer(c_int) :: handle,processed + type(update_event) :: events(max_events) + integer :: n + + handle=jtty_rx_create() + call jtty_rx_begin(handle,3_c_int64_t,0_c_int64_t,0_c_int64_t,nsps) + processed=jtty_rx_process(handle,samples,stop,0_c_int64_t,int(stop,c_int64_t),1000,200,1499,1500.0,50.0) + call expect(processed.gt.0,'partial-message fixture is decoded') + if(reason.eq.UPDATE_RECEPTION_ENDED) call jtty_rx_end(handle,reason) + n=0 + call collect(handle,events,n) + call expect(n.gt.0,'partial messages remain deliverable') + call expect(any(events(1:n)%terminal.eq.reason),'partial message reports its actual terminal reason') + call expect(.not.any(events(1:n)%terminal.eq.UPDATE_COMPLETE),'interruption is not a completed transmission') + call jtty_rx_destroy(handle) + end subroutine check_terminal + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(condition) return + write(*,'(a)') message + error stop 1 + end subroutine expect + +end program test_jtty_continuous_decode diff --git a/tests/unit/jtty/test_jtty_draft_acceptance.cpp b/tests/unit/jtty/test_jtty_draft_acceptance.cpp deleted file mode 100644 index f321aaf5..00000000 --- a/tests/unit/jtty/test_jtty_draft_acceptance.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include - -#include "widgets/JttyDraftAcceptanceTracker.hpp" - -class TestJttyDraftAcceptance final - : public QObject -{ - Q_OBJECT - -private slots: - void acceptedCurrentSubmissionClearsDraft () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - - QVERIFY (tracker.accept (1)); - } - - void rejectedSubmissionPreservesDraft () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - tracker.reject (1); - - QVERIFY (!tracker.accept (1)); - } - - void delayedAcceptancePreservesNewerDraft () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - tracker.noteDraftChanged (); - - QVERIFY (!tracker.accept (1)); - } - - void identicalRetypedDraftHasNewIdentity () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - tracker.noteDraftChanged (); - tracker.noteDraftChanged (); - - QVERIFY (!tracker.accept (1)); - } - - void unrelatedAcceptancePreservesDraft () - { - JttyDraftAcceptanceTracker tracker; - - QVERIFY (!tracker.accept (1)); - } - - void currentDraftReportsPendingSubmission () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - - QVERIFY (tracker.hasPendingSubmissionForCurrentDraft ()); - QVERIFY (tracker.isPending (1)); - QVERIFY (!tracker.isPending (2)); - } - - void rejectedCurrentDraftCanBeRetried () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - tracker.reject (1); - - QVERIFY (!tracker.hasPendingSubmissionForCurrentDraft ()); - QVERIFY (!tracker.isPending (1)); - - tracker.trackSubmission (2); - QVERIFY (tracker.hasPendingSubmissionForCurrentDraft ()); - QVERIFY (tracker.isPending (2)); - } - - void newerDraftCanBeSubmittedWhileOlderDraftIsPending () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - tracker.noteDraftChanged (); - - QVERIFY (!tracker.hasPendingSubmissionForCurrentDraft ()); - - tracker.trackSubmission (2); - QVERIFY (tracker.hasPendingSubmissionForCurrentDraft ()); - QVERIFY (tracker.isPending (1)); - QVERIFY (tracker.isPending (2)); - } - - void acceptedRequestIsNoLongerPending () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - - QVERIFY (tracker.accept (1)); - QVERIFY (!tracker.hasPendingSubmissionForCurrentDraft ()); - QVERIFY (!tracker.isPending (1)); - } - - void successiveAcceptedDraftsCanClear () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - QVERIFY (tracker.accept (1)); - - tracker.noteDraftChanged (); - tracker.noteDraftChanged (); - tracker.trackSubmission (2); - QVERIFY (tracker.accept (2)); - } - - void olderAcceptanceDoesNotClearSuccessiveDraft () - { - JttyDraftAcceptanceTracker tracker; - tracker.trackSubmission (1); - tracker.noteDraftChanged (); - tracker.trackSubmission (2); - - QVERIFY (!tracker.accept (1)); - QVERIFY (tracker.accept (2)); - } -}; - -QTEST_GUILESS_MAIN (TestJttyDraftAcceptance) - -#include "test_jtty_draft_acceptance.moc" diff --git a/tests/unit/jtty/test_jtty_get_updates.f90 b/tests/unit/jtty/test_jtty_get_updates.f90 index 0ecf61dc..7baaae6c 100644 --- a/tests/unit/jtty/test_jtty_get_updates.f90 +++ b/tests/unit/jtty/test_jtty_get_updates.f90 @@ -9,19 +9,20 @@ program test_jtty_get_updates integer(int64) :: message_ids(BATCH_SIZE) real :: frequencies(BATCH_SIZE),start_tsync(BATCH_SIZE) logical*1 :: eom(BATCH_SIZE) + integer :: snr(BATCH_SIZE) type(message_assembly) :: message integer :: i,count call discard_pending_updates() - message=make_message(41_int64,1500.4,1.25,'CQ K1ABC') + message=make_message(41_int64,1500.4,1.25,'CQ K1ABC',snr=-7.3) call queue_message_update(message,.false.) message%decoded='CQ K1ABC FN20' call queue_message_update(message,.true.) call expect(npending.eq.1, & 'updates for one logical message coalesce before delivery') - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.1 .and. npending.eq.0, & 'retrieving an update drains it exactly once') call expect(message_ids(1).eq.41_int64 .and. & @@ -30,13 +31,15 @@ program test_jtty_get_updates call expect(abs(frequencies(1)-1500.4).lt.0.001 .and. & abs(start_tsync(1)-1.25).lt.0.001 .and. eom(1), & 'the batch preserves structured message metadata') - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(snr(1).eq.-7, & + 'the batch reports the rounded start_snrdb carried by message_assembly') + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.0, 'a drained update is not returned again') message=make_message(42_int64,1501.0,2.5,'UNCHANGED TEXT') call queue_message_update(message,.false.) call queue_message_update(message,.true.) - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.1 .and. eom(1) .and. & trim(block_text(text_blocks,1)).eq.'UNCHANGED TEXT', & 'completion metadata coalesces when message text is unchanged') @@ -51,7 +54,7 @@ program test_jtty_get_updates call expect(npending.eq.35, & 'the pending store retains more than one ABI batch') - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.BATCH_SIZE .and. npending.eq.5, & 'the first batch drains the oldest thirty updates') do i=1,BATCH_SIZE @@ -64,7 +67,7 @@ program test_jtty_get_updates 'the first batch preserves completion state') enddo - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.5 .and. npending.eq.0, & 'a second batch drains every remaining update') do i=1,5 @@ -76,16 +79,18 @@ program test_jtty_get_updates contains - function make_message(id,frequency,tsync,text) result(value) + function make_message(id,frequency,tsync,text,snr) result(value) integer(int64), intent(in) :: id real, intent(in) :: frequency,tsync character(len=*), intent(in) :: text + real, intent(in), optional :: snr type(message_assembly) :: value value%message_id=id value%f1=frequency value%tsync=tsync value%start_tsync=tsync + if(present(snr)) value%start_snrdb=snr value%decoded=text value%k=len_trim(value%decoded) end function make_message diff --git a/tests/unit/jtty/test_jtty_live_entry.cpp b/tests/unit/jtty/test_jtty_live_entry.cpp new file mode 100644 index 00000000..9f9f7d2f --- /dev/null +++ b/tests/unit/jtty/test_jtty_live_entry.cpp @@ -0,0 +1,86 @@ +#include + +#include "widgets/JttyLiveEntry.hpp" + +class TestJttyLiveEntry final + : public QObject +{ + Q_OBJECT + +private slots: + + void emptyTextCommitsNothing () + { + auto const plan = Jtty::planIncrementalCommit (QString {}); + QVERIFY (plan.text.isEmpty ()); + QCOMPARE (plan.length, 0); + } + + void fewerThanHoldbackWordsCommitsNothing () + { + // Exactly maxCompactAtomWords complete words: still all held back. + auto const plan = Jtty::planIncrementalCommit (QStringLiteral ("CQ K1ABC CQ ")); + QVERIFY (plan.text.isEmpty ()); + QCOMPARE (plan.length, 0); + } + + void callSplitAcrossHoldbackNeverCommitsPartway () + { + // The motivating case: TEXT5's fixed 5-char windows would slice "CQ K1ABC" mid-callsign if released early. + for (auto const& text : {QStringLiteral ("CQ "), QStringLiteral ("CQ K1ABC ")}) { + auto const plan = Jtty::planIncrementalCommit (text); + QVERIFY2 (plan.text.isEmpty (), qPrintable (text)); + } + } + + void wordBeyondHoldbackReleasesOnlyTheEarlierWords () + { + // A 4th word pushes the first word out past the 3-word holdback. + auto const plan = Jtty::planIncrementalCommit ( + QStringLiteral ("CQ K1ABC CQ DE ")); + QCOMPARE (plan.text, QStringLiteral ("CQ ")); + QCOMPARE (plan.length, 3); + } + + void releasedPrefixExactlyMatchesOriginalText () + { + QString const text = QStringLiteral ("FIRST SECOND THIRD FOURTH FIFTH "); + auto const plan = Jtty::planIncrementalCommit (text); + QCOMPARE (text.left (plan.length), plan.text); + // 5 complete words, holdback 3: releases the first 2. + QCOMPARE (plan.text, QStringLiteral ("FIRST SECOND ")); + } + + void trailingPartialWordIsNeverReleased () + { + // Same words as the previous case, but the 5th is still mid-typing (no trailing space), so only 4 are complete. + auto const plan = Jtty::planIncrementalCommit ( + QStringLiteral ("FIRST SECOND THIRD FOURTH FIF")); + QCOMPARE (plan.text, QStringLiteral ("FIRST ")); + } + + void forceFlushReleasesEverythingRegardlessOfHoldback () + { + QString const text = QStringLiteral ("CQ K1ABC"); + auto const plan = Jtty::planIncrementalCommit (text, true); + QCOMPARE (plan.text, text); + QCOMPARE (plan.length, text.size ()); + } + + void forceFlushOnEmptyTextCommitsNothing () + { + auto const plan = Jtty::planIncrementalCommit (QString {}, true); + QVERIFY (plan.text.isEmpty ()); + QCOMPARE (plan.length, 0); + } + + void customHoldbackIsHonoured () + { + auto const plan = Jtty::planIncrementalCommit ( + QStringLiteral ("ONE TWO THREE "), false, 1); + QCOMPARE (plan.text, QStringLiteral ("ONE TWO ")); + } +}; + +QTEST_GUILESS_MAIN (TestJttyLiveEntry) +#include "test_jtty_live_entry.moc" diff --git a/tests/unit/jtty/test_jtty_messages.cpp b/tests/unit/jtty/test_jtty_messages.cpp index 7c38dfa4..033966e4 100644 --- a/tests/unit/jtty/test_jtty_messages.cpp +++ b/tests/unit/jtty/test_jtty_messages.cpp @@ -86,10 +86,10 @@ private slots: QCOMPARE (int {movedDefault.atoms.at (0).subtype}, static_cast (Jtty::CallAction::Call)); - auto const unknownPlaceholder = Jtty::compileNativeMacro ( + auto const knownSnrPlaceholder = Jtty::compileNativeMacro ( 8, QString {"599 %R"}, context); - QCOMPARE (unknownPlaceholder.status, Jtty::NativeMacroStatus::LiteralFallback); - QCOMPARE (unknownPlaceholder.text, QString {"599 %R"}); + QCOMPARE (knownSnrPlaceholder.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (knownSnrPlaceholder.text, QString {"599 -10"}); auto const editedLegacyCase = Jtty::compileNativeMacro ( 2, QString {"%h 599 %n"}, context); @@ -480,7 +480,7 @@ private slots: static_cast (Jtty::ExchangeRole::FieldOnly)); } - void configuredSubsquareProducesGrid4WithoutChangingLiteralExpansion () + void configuredSubsquareProducesGrid4InBothNativeAndLiteralExpansion () { Jtty::NativeMacroContext const context { QString {"K1ABC"}, QString {"W9XYZ"}, 1, @@ -492,7 +492,7 @@ private slots: auto const literal = Jtty::compileNativeMacro (QString {"GRID %G"}, context); QCOMPARE (literal.status, Jtty::NativeMacroStatus::LiteralFallback); - QCOMPARE (literal.text, QString {"GRID fn42ab"}); + QCOMPARE (literal.text, QString {"GRID FN42"}); } void invalidGridIsRejected_data () @@ -537,7 +537,7 @@ private slots: Jtty::NativeExchangeProfile::RttyRoundup, QString {" dx "}, QString {"fn42"}}; auto const compiled = Jtty::compileNativeMacro (QString {"TEST %E %G"}, context); QCOMPARE (compiled.status, Jtty::NativeMacroStatus::LiteralFallback); - QCOMPARE (compiled.text, QString {"TEST 007 fn42"}); + QCOMPARE (compiled.text, QString {"TEST 007 FN42"}); QVERIFY (compiled.error.isEmpty ()); } @@ -546,34 +546,34 @@ private slots: QTest::addColumn ("message"); QTest::addColumn ("expected"); QTest::addColumn ("substituted"); - QTest::addColumn ("truncated"); QTest::newRow ("empty") << QString {} << QString {} - << false << false; + << false; QTest::newRow ("supported") << QString {"CQ KA1ABC CQ"} << QString {"CQ KA1ABC CQ"} - << false << false; + << false; QTest::newRow ("lowercase-preserved") << QString {"cq ka1abc cq"} << QString {"cq ka1abc cq"} - << false << false; + << false; QTest::newRow ("tab") << QString {"HELLO\tWORLD"} << QString {"HELLO#WORLD"} - << true << false; - QTest::newRow ("cr-lf") << QString {"HELLO\r\nWORLD"} << QString {"HELLO##WORLD"} - << true << false; + << true; + // '\n'/'\r' are now forced segment boundaries, not unsupported characters. + QTest::newRow ("cr-lf") << QString {"HELLO\r\nWORLD"} << QString {"HELLO\n\nWORLD"} + << false; QTest::newRow ("nul") << (QString {"A"} + QChar::Null + QString {"B"}) << QString {"A B"} - << true << false; + << true; QTest::newRow ("display-space-marker") << QString {"A~B"} << QString {"A B"} - << true << false; + << true; QTest::newRow ("exactly-80") << QString (80, QLatin1Char {'A'}) << QString (80, QLatin1Char {'A'}) - << false << false; - QTest::newRow ("truncated") << QString (81, QLatin1Char {'A'}) << QString (80, QLatin1Char {'A'}) - << false << true; + << false; + QTest::newRow ("long-input-preserved") << QString (81, QLatin1Char {'A'}) << QString (81, QLatin1Char {'A'}) + << false; QTest::newRow ("unsupported-past-limit") << (QString (80, QLatin1Char {'A'}) + QString {"\t"}) - << QString (80, QLatin1Char {'A'}) - << false << true; - QTest::newRow ("substitution-and-truncation") + << (QString (80, QLatin1Char {'A'}) + QString {"#"}) + << true; + QTest::newRow ("substitution-preserves-suffix") << (QString (79, QLatin1Char {'A'}) + QString {"\tB"}) - << (QString (79, QLatin1Char {'A'}) + QString {"#"}) - << true << true; + << (QString (79, QLatin1Char {'A'}) + QString {"#B"}) + << true; } void prepareTransmitText () @@ -581,72 +581,113 @@ private slots: QFETCH (QString, message); QFETCH (QString, expected); QFETCH (bool, substituted); - QFETCH (bool, truncated); auto const prepared = Jtty::prepareTransmitText (message); QCOMPARE (prepared.text, expected); QCOMPARE (prepared.substituted, substituted); - QCOMPARE (prepared.truncated, truncated); - QCOMPARE (prepared.changed (), substituted || truncated); - } - - void withChainedSpacing_data () - { - QTest::addColumn ("message"); - QTest::addColumn ("isChained"); - QTest::addColumn ("expected"); - - QTest::newRow ("not-chained-unchanged") << QString {"CQ KA1ABC CQ"} << false - << QString {"CQ KA1ABC CQ"}; - QTest::newRow ("chained-gets-leading-space") << QString {"TU DE KA1ABC"} << true - << QString {" TU DE KA1ABC"}; - QTest::newRow ("not-chained-empty-stays-empty") << QString {} << false << QString {}; - QTest::newRow ("chained-at-max-length-drops-last-char") - << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}) << true - << (QString {" "} + QString (Jtty::maxTransmitLength - 1, QLatin1Char {'A'})); - } - - void withChainedSpacing () - { - QFETCH (QString, message); - QFETCH (bool, isChained); - QFETCH (QString, expected); - - QCOMPARE (Jtty::withChainedSpacing (message, isChained), expected); } void transmitFrame_data () { QTest::addColumn ("message"); - QTest::addColumn ("isChained"); QTest::addColumn ("expected"); auto const padded = [] (QString const& text) { return text + QString (Jtty::maxTransmitLength - text.size (), QLatin1Char {' '}); }; - QTest::newRow ("not-chained-padded-to-width") - << QString {"CQ KA1ABC CQ"} << false << padded (QString {"CQ KA1ABC CQ"}); - QTest::newRow ("chained-prefixed-and-padded") - << QString {"TU K1ABC CQ"} << true << padded (QString {" TU K1ABC CQ"}); - QTest::newRow ("chained-at-max-length-stays-exact") - << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}) << true - << (QString {" "} + QString (Jtty::maxTransmitLength - 1, QLatin1Char {'A'})); - QTest::newRow ("empty-not-chained-all-spaces") - << QString {} << false << QString (Jtty::maxTransmitLength, QLatin1Char {' '}); + QTest::newRow ("padded-to-width") + << QString {"CQ KA1ABC CQ"} << padded (QString {"CQ KA1ABC CQ"}); + QTest::newRow ("at-max-length-stays-exact") + << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}) + << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}); + QTest::newRow ("empty-all-spaces") + << QString {} << QString (Jtty::maxTransmitLength, QLatin1Char {' '}); + QTest::newRow ("oversized-rejected") + << QString (Jtty::maxTransmitLength + 1, QLatin1Char {'A'}) << QString {}; } void transmitFrame () { QFETCH (QString, message); - QFETCH (bool, isChained); QFETCH (QString, expected); - QString const frame = Jtty::transmitFrame (message, isChained); + QString const frame = Jtty::transmitFrame (message); QCOMPARE (frame, expected); - QCOMPARE (frame.size (), Jtty::maxTransmitLength); + QCOMPARE (frame.size (), message.size () > Jtty::maxTransmitLength + ? 0 : Jtty::maxTransmitLength); + } + + void transmitSegmentsCoverCompleteInput_data () + { + QTest::addColumn ("source"); + QTest::addColumn ("firstLength"); + QTest::addColumn ("segmentCount"); + + QTest::newRow ("79-characters") << QString (79, QLatin1Char {'A'}) << 79 << 1; + QTest::newRow ("80-characters") << QString (80, QLatin1Char {'A'}) << 80 << 1; + QTest::newRow ("81-characters") << QString (81, QLatin1Char {'A'}) << 80 << 2; + QTest::newRow ("word-boundary") + << (QString (70, QLatin1Char {'A'}) + QString {" WORDS CONTINUE"}) << 77 << 2; + QTest::newRow ("space-at-capacity") + << (QString (79, QLatin1Char {'A'}) + QString {" SUFFIX"}) << 80 << 2; + QTest::newRow ("space-after-capacity") + << (QString {"FIRST "} + QString (74, QLatin1Char {'A'}) + QString {" SUFFIX"}) + << 80 << 2; + QTest::newRow ("leading-space-before-long-token") + << (QString {" "} + QString (160, QLatin1Char {'A'})) << 80 << 3; + QTest::newRow ("many-spaces") << QString (200, QLatin1Char {' '}) << 80 << 3; + QTest::newRow ("substitution-after-first-segment") + << (QString (80, QLatin1Char {'A'}) + QString {"\tSUFFIX"}) << 80 << 2; + } + + void transmitSegmentsCoverCompleteInput () + { + QFETCH (QString, source); + QFETCH (int, firstLength); + QFETCH (int, segmentCount); + + QString const prepared = Jtty::prepareTransmitText (source).text; + QString reconstructed; + int offset {0}; + int count {0}; + while (offset < prepared.size ()) { + auto const segment = Jtty::nextTransmitTextSegment (prepared, offset); + QCOMPARE (segment.offset, offset); + QVERIFY (segment.length > 0); + QVERIFY (segment.length <= Jtty::maxTransmitLength); + QCOMPARE (segment.text, prepared.mid (offset, segment.length)); + if (count == 0) QCOMPARE (segment.length, firstLength); + reconstructed += segment.text; + offset += segment.length; + ++count; + } + QCOMPARE (count, segmentCount); + QCOMPARE (reconstructed, prepared); + } + + void transmitSegmentRetryRetainsSourceOffset () + { + QString const source {"PREFIX FIRST SECOND THIRD SUFFIX"}; + auto const initial = Jtty::nextTransmitTextSegment (source, 7, 19); + QCOMPARE (initial.text, QString {"FIRST SECOND THIRD "}); + auto const retry = Jtty::nextTransmitTextSegment (source, initial.offset, 12); + QCOMPARE (retry.offset, initial.offset); + QCOMPARE (retry.text, QString {"FIRST SECOND"}); + auto const next = Jtty::nextTransmitTextSegment (source, retry.offset + retry.length); + QCOMPARE (retry.text + next.text, source.mid (7)); + } + + void transmitSegmentEmptyAndInvalidRanges () + { + QVERIFY (Jtty::nextTransmitTextSegment (QString {}, 0).text.isEmpty ()); + QVERIFY (Jtty::nextTransmitTextSegment (QString {"ABC"}, -1).text.isEmpty ()); + QVERIFY (Jtty::nextTransmitTextSegment (QString {"ABC"}, 3).text.isEmpty ()); + QVERIFY (Jtty::nextTransmitTextSegment (QString {"ABC"}, 0, 0).text.isEmpty ()); + QCOMPARE (Jtty::nextTransmitTextSegment (QString (100, QLatin1Char {'A'}), 0, 100).length, + Jtty::maxTransmitLength); } void wavCaptureValid_data () @@ -746,6 +787,13 @@ private slots: QCOMPARE (Jtty::jttyLineTimeLabel (QDateTime {}), QString {}); } + void formatJttyTxLineLeavesSnrColumnBlank () + { + QCOMPARE (Jtty::formatJttyTxLine (1500.f, QString {"CQ K1ABC CQ"}), + QString {"1500 CQ K1ABC CQ"}); + QCOMPARE (Jtty::formatJttyTxLine (1500.4f, QString {}), QString {"1500 "}); + } + void parseDecodeLine_data () { QTest::addColumn ("line"); @@ -816,6 +864,39 @@ private slots: QCOMPARE (Jtty::wrapMessage (text), expected); } + void formatJttyDecodeLine_data () + { + QTest::addColumn ("frequency"); + QTest::addColumn ("snr"); + QTest::addColumn ("message"); + QTest::addColumn ("expected"); + + QTest::newRow ("negative-two-digit-snr") + << 1513.f << -10 << QString {"CQ VA7TTO CQ"} + << QString {"1513 -10 CQ VA7TTO CQ"}; + QTest::newRow ("positive-snr-no-forced-sign") + << 1500.f << 5 << QString {"K1ABC W9XYZ"} + << QString {"1500 5 K1ABC W9XYZ"}; + QTest::newRow ("three-digit-frequency-padded") + << 500.f << 0 << QString {"HELLO"} + << QString {" 500 0 HELLO"}; + QTest::newRow ("multi-digit-snr") + << 1500.f << -100 << QString {"WEAK"} + << QString {"1500 -100 WEAK"}; + QTest::newRow ("empty-message-omits-snr") + << 1500.f << -10 << QString {} << QString {"1500"}; + } + + void formatJttyDecodeLine () + { + QFETCH (float, frequency); + QFETCH (int, snr); + QFETCH (QString, message); + QFETCH (QString, expected); + + QCOMPARE (Jtty::formatJttyDecodeLine (frequency, snr, message), expected); + } + void compareMessagesTracksMessageSemantics () { auto const unchanged = Jtty::compareMessages ( @@ -932,6 +1013,91 @@ private slots: QVERIFY (!Jtty::shouldApplyToQsoHistory (false, 1505.f, 1500.f, 5.f)); QVERIFY (Jtty::shouldApplyToQsoHistory (true, 1510.f, 1500.f, 5.f)); } + + void snrFormattingHasLeadingSignAndZeroPad () + { + QCOMPARE (Jtty::formatSnr (-10), QString {"-10"}); + QCOMPARE (Jtty::formatSnr (5), QString {"+05"}); + QCOMPARE (Jtty::formatSnr (-5), QString {"-05"}); + QCOMPARE (Jtty::formatSnr (0), QString {"+00"}); + QCOMPARE (Jtty::formatSnr (100), QString {"+100"}); + } + + void ft8StyleTemplatesMatchSpec () + { + QCOMPARE (Jtty::ft8StyleMacroTemplate (1), QString {"%H %M %G"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (2), QString {"%H %M %R"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (3), QString {"%H %M R%R"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (4), QString {"%H %M RRR"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (5), QString {"%H %M 73"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (6), QString {"CQ %M %G"}); + QVERIFY (Jtty::ft8StyleMacroTemplate (7).isEmpty ()); + QVERIFY (Jtty::ft8StyleMacroTemplate (8).isEmpty ()); + } + + void ft8StyleLiteralExpansionSubstitutesGridAndSnr () + { + // %G's own truncate-to-4 behavior for extended subsquare grids is covered + // separately by configuredSubsquareProducesGrid4InBothNativeAndLiteralExpansion; + // a plain 4-char grid here keeps this test focused on the %R substitution. + Jtty::NativeMacroContext context {QString {"K1ABC"}, QString {"W9XYZ"}, 0}; + context.grid = QStringLiteral ("FN20"); + context.snr = -7; + + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (1), context), + QString {"W9XYZ K1ABC FN20"}); + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (2), context), + QString {"W9XYZ K1ABC -07"}); + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (3), context), + QString {"W9XYZ K1ABC R-07"}); + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (6), context), + QString {"CQ K1ABC FN20"}); + } + + void messageStyleHelpersDistinguishContestAndFt8 () + { + QCOMPARE (Jtty::messageStyleSettingsKey (Jtty::MessageStyle::Contest, 3), + QString {"JTTY_msg3"}); + QCOMPARE (Jtty::messageStyleSettingsKey (Jtty::MessageStyle::Ft8, 3), + QString {"JTTY_FT8_msg3"}); + QCOMPARE (Jtty::messageStyleDefaultTemplate (Jtty::MessageStyle::Contest, 1), + Jtty::nativeMacroTemplate (1)); + QCOMPARE (Jtty::messageStyleDefaultTemplate (Jtty::MessageStyle::Ft8, 1), + Jtty::ft8StyleMacroTemplate (1)); + } + + void fillerTextIsRecognizedStandalone () + { + QVERIFY (Jtty::isJttyFillerText (Jtty::jttyFillerText)); + QVERIFY (Jtty::isJttyFillerText (QStringLiteral ("<<<<<"))); + QVERIFY (!Jtty::isJttyFillerText (QString {})); + QVERIFY (!Jtty::isJttyFillerText (QStringLiteral ("FOX"))); + QVERIFY (!Jtty::isJttyFillerText (QStringLiteral ("FOX <<<<<"))); + } + + void fillerStripLeavesRealTextUnaffected () + { + QCOMPARE (Jtty::stripJttyFillerText (QStringLiteral ("FOX JUMPED OVER")), + QStringLiteral ("FOX JUMPED OVER")); + } + + void fillerStripRemovesEmbeddedRunRegardlessOfSpacing () + { + // Squished with no separator, as a receiver could decode if neither side's own packing added a boundary space. + QCOMPARE (Jtty::stripJttyFillerText (QStringLiteral ("OVER<<<<< <<<< {11}); + QVERIFY (handoff.stopCompleted ()); + QVERIFY (!handoff.active ()); + QCOMPARE (handoff.requestIds (), QVector {11}); + } + + void mmttyHandoffPreservesOrderAndAbort () + { + Jtty::MmttyHandoff handoff; + handoff.queue (21); + handoff.queue (22); + handoff.waitForStop (); + QCOMPARE (handoff.requestIds (), QVector ({21, 22})); + + handoff.abort (); + QVERIFY (handoff.empty ()); + QVERIFY (!handoff.stopCompleted ()); + } + + void mmttyHandoffBoundsPendingRequests () + { + Jtty::MmttyHandoff handoff; + handoff.waitForStop (); + for (qint64 id = 1; id <= 64; ++id) QVERIFY (handoff.queue (id)); + QVERIFY (!handoff.queue (65)); + QCOMPARE (handoff.requestIds ().last (), qint64 (64)); + + handoff.submitted (1); + QVERIFY (handoff.queue (65)); + QVERIFY (!handoff.queue (66)); + handoff.abort (); + QVERIFY (handoff.queue (66)); + } + + void mmttyHandoffTimeoutRejectsAllQueuedRequests () + { + Jtty::MmttyHandoff handoff; + handoff.queue (31); + handoff.queue (32); + handoff.waitForStop (); + + QCOMPARE (handoff.expire (), QVector ({31, 32})); + QVERIFY (handoff.empty ()); + QVERIFY (!handoff.active ()); + } + + void activeFt8ValidTextStopsBeforeSubmission () + { + using Action = Jtty::MmttyHandoff::SubmitAction; + QCOMPARE (Jtty::MmttyHandoff::planSubmission (true, false, true), + Action::StopThenSubmit); + + Jtty::MmttyHandoff handoff; + handoff.queue (41); + handoff.waitForStop (); + QVERIFY (handoff.active ()); + QVERIFY (handoff.stopCompleted ()); + QCOMPARE (handoff.requestIds (), QVector {41}); + } + + void xmitOnRemainsDeferredAcrossHandoff () + { + Jtty::N1mmOutput output; + Jtty::MmttyHandoff handoff; + output.start (); + handoff.waitForStop (); + + QVERIFY (handoff.stopCompleted ()); + QVERIFY (output.startRequested ()); + output.submit (42); + QVERIFY (output.accept (42)); + output.started (); + QVERIFY (!output.startRequested ()); + } + + void invalidTextDoesNotDisturbActiveFt8 () + { + using Action = Jtty::MmttyHandoff::SubmitAction; + auto const compiled = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:UNKNOWN]] TEST")); + QCOMPARE (compiled.status, Jtty::N1mmCompileStatus::Error); + QCOMPARE (Jtty::MmttyHandoff::planSubmission (false, false, true), + Action::Reject); + + Jtty::MmttyHandoff handoff; + QVERIFY (!handoff.active ()); + QVERIFY (handoff.empty ()); + } + + void multipleTextsSubmitInOrderAfterStop () + { + Jtty::MmttyHandoff handoff; + handoff.queue (51); + handoff.queue (52); + handoff.waitForStop (); + QVERIFY (handoff.stopCompleted ()); + QCOMPARE (handoff.requestIds (), QVector ({51, 52})); + + handoff.submitted (51); + handoff.submitted (52); + QVERIFY (handoff.empty ()); + } + + void abortDuringHandoffSilentlyDiscardsOutput () + { + Jtty::N1mmOutput output; + Jtty::MmttyHandoff handoff; + output.submit (61); + output.start (); + handoff.queue (61); + handoff.waitForStop (); + + handoff.abort (); + output.abort (); + QVERIFY (handoff.empty ()); + QVERIFY (!output.takeCompletion (false, true)); + } + void everyActionCompiles () { struct Example diff --git a/tests/unit/jtty/test_jtty_overlap_decode.f90 b/tests/unit/jtty/test_jtty_overlap_decode.f90 index b440d1f3..97777859 100644 --- a/tests/unit/jtty/test_jtty_overlap_decode.f90 +++ b/tests/unit/jtty/test_jtty_overlap_decode.f90 @@ -5,8 +5,8 @@ program test_jtty_overlap_decode ! ! The 4 Hz case reproduces leftover extra-slot fragments: a real next ! frame lands just outside the 3 Hz continuation gate and opens a new - ! message instead of staying on its assembly. Isolated and 2 Hz cases are - ! controls that already pass. + ! message instead of staying on its assembly. The 2 Hz case is a control + ! for assembly with closer overlap. Both cases require two complete messages. use iso_fortran_env, only: int16 use jtty_fec, only: is13, TOTAL_K @@ -25,10 +25,6 @@ program test_jtty_overlap_decode if(len_trim(rate_arg).gt.0) read(rate_arg,*) nsps failures=0 - call expect_complete_pair('isolated first message',msg_a,1500.0,0.2, & - '',1500.0,0.6,1,failures) - call expect_complete_pair('isolated second message','',1500.0,0.2, & - msg_b,1504.0,0.6,1,failures) call expect_complete_pair('2 Hz overlap stays two complete messages', & msg_a,1500.0,0.2,msg_b,1502.0,0.6,2,failures) @@ -148,11 +144,13 @@ contains found_b=len_trim(second_message).eq.0 do i=1,npending if(len_trim(first_message).gt.0) then - if(trim(normalized(pending_updates(i)%decoded)).eq.trim(first_message)) & + if(pending_updates(i)%complete .and. & + trim(normalized(pending_updates(i)%decoded)).eq.trim(first_message)) & found_a=.true. endif if(len_trim(second_message).gt.0) then - if(trim(normalized(pending_updates(i)%decoded)).eq.trim(second_message)) & + if(pending_updates(i)%complete .and. & + trim(normalized(pending_updates(i)%decoded)).eq.trim(second_message)) & found_b=.true. endif enddo diff --git a/tests/unit/jtty/test_jtty_pack.f90 b/tests/unit/jtty/test_jtty_pack.f90 index 31541cfb..2ffd23ab 100644 --- a/tests/unit/jtty/test_jtty_pack.f90 +++ b/tests/unit/jtty/test_jtty_pack.f90 @@ -2,6 +2,7 @@ program test_jtty_pack use jtty_mod use packjt77, only: pack28 + use packjt77_grammar, only: pack77_arrl_section_index character*80 msg0,msg,expected character*34 c32(MAX_FRAMES) character*17 cparms @@ -71,6 +72,10 @@ program test_jtty_pack call expect_pack('FN42',1,2,-1,-1,-1) call expect_pack('1D EMA',1,2,-1,-1,-1) call expect_pack('32F EMA',1,2,-1,-1,-1) + call expect_pack('1F DX',1,2,-1,-1,-1) + call expect_pack('2A CT',1,2,-1,-1,-1) + call expect_pack('10A CT',1,2,-1,-1,-1) + call expect_pack('32F DX',1,2,-1,-1,-1) call expect_pack('0',1,2,-1,-1,-1) call expect_pack('131071',1,2,-1,-1,-1) call expect_pack('599 131071',1,2,-1,-1,-1) @@ -83,6 +88,9 @@ program test_jtty_pack call expect_pack('33D EMA',2,3,-1,3,-1) call expect_pack('1G EMA',2,3,-1,3,-1) call expect_pack('1D ZZZ',2,3,-1,3,-1) + call expect_pack('1D EMAX',2,3,-1,3,-1) + call expect_pack('K1ABC 1D EMAX QSL TU',4,0,1,3,-1) + call expect_pack('K1ABC 1D EMAX X QSL TU',4,0,1,3,-1) call expect_pack('599 SA00',2,-1,-1,-1,-1) call expect_pack('599 A!',2,-1,-1,-1,-1) call expect_pack('599 XYZ',1,2,-1,-1,-1) @@ -107,6 +115,8 @@ program test_jtty_pack call expect_pack('PSE AGN NR',2,-1,-1,-1,-1) call expect_pack('AGN NR PSE',2,2,-1,3,-1) call expect_control_phrase_literals() + call expect_atom('1F DX',jtty_class_section_atom(1,'F',pack77_arrl_section_index('DX '))) + call expect_atom('2A CT',jtty_class_section_atom(2,'A',pack77_arrl_section_index('CT '))) call expect_atom('599 123',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_GENERIC,123)) call expect_atom('123',jtty_exch_num_atom(JTTY_ROLE_FIELD_ONLY,JTTY_NUM_GENERIC,123)) call expect_atom('599 MA',jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_QTH,'MA')) @@ -150,7 +160,7 @@ contains subroutine expect_exchange_profiles() character(len=80), parameter :: examples(*)=[character(len=80) :: & '599 001','K1ABC 599 001','599 05','599 0123','001','599 123', & - '599 MA','599 131071','599 0AB','1D EMA','CQ K1ABC CQ','K1A A'] + '599 MA','599 131071','599 0AB','1D EMA','1F DX','10A CT','32F DX','CQ K1ABC CQ','K1A A'] character(len=80) :: input,decoded character(len=34) :: baseline(MAX_FRAMES),frames(MAX_FRAMES) integer :: i,profile,baseline_nf,nframes diff --git a/tests/unit/jtty/test_jtty_receive_history.cpp b/tests/unit/jtty/test_jtty_receive_history.cpp new file mode 100644 index 00000000..1f5dad36 --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_history.cpp @@ -0,0 +1,87 @@ +#include +#include +#include + +#include "JttyReceiveHistory.hpp" + +class TestJttyReceiveHistory final : public QObject +{ + Q_OBJECT +private slots: + void rotationsRetainExactSuffixAcrossPacketBoundaries () + { + Jtty::ReceiveHistory history {17}; + qint64 const origin = qint64 (1) << 35; + std::vector received; + for (int packet = 0; packet < 200; ++packet) { + int const count = 1 + packet % 7; + std::vector incoming (count); + for (int i = 0; i < count; ++i) incoming[i] = short (received.size () + i); + auto const first = origin + qint64 (received.size ()); + received.insert (received.end (), incoming.begin (), incoming.end ()); + QVERIFY (history.append (12, first, incoming.data (), count)); + auto const retained = std::min (17, received.size ()); + auto const end = origin + qint64 (received.size ()); + QCOMPARE (history.size (), retained); + QCOMPARE (history.first (12), end - retained); + QCOMPARE (history.end (12), end); + std::vector expected (received.end () - retained, received.end ()); + QVERIFY (history.snapshot (12, end - retained, end) == expected); + QVERIFY (history.snapshot (12, end - retained - 1, end).empty ()); + QVERIFY (history.snapshot (12, end - retained, end + 1).empty ()); + } + } + + void snapshotsNeverJoinReceptionsWithMatchingCoordinates () + { + Jtty::ReceiveHistory history {12}; + short const first[] = {1, 2, 3, 4}; + short const second[] = {5, 6, 7, 8}; + short const third[] = {9, 10, 11, 12}; + QVERIFY (history.append (1, 0, first, 4)); + QVERIFY (history.append (2, 4, second, 4)); + QVERIFY (history.snapshot (1, 0, 8).empty ()); + QVERIFY (history.snapshot (2, 0, 8).empty ()); + QVERIFY (history.append (3, 0, third, 4)); + QVERIFY (history.snapshot (1, 0, 4) == std::vector ({1, 2, 3, 4})); + QVERIFY (history.snapshot (3, 0, 4) == std::vector ({9, 10, 11, 12})); + QVERIFY (history.append (3, 4, third, 4)); + QCOMPARE (history.first (1), qint64 (-1)); + QCOMPARE (history.end (1), qint64 (-1)); + QCOMPARE (history.first (2), qint64 (4)); + QCOMPARE (history.first (3), qint64 (0)); + } + + void gapsAndDuplicatesFailWithoutChangingRetainedAudio () + { + Jtty::ReceiveHistory history {10}; + short const samples[] = {1, 2, 3, 4}; + QVERIFY (history.append (3, 7, samples, 4)); + QVERIFY (!history.append (3, 12, samples, 4)); + QVERIFY (!history.append (3, 7, samples, 4)); + QCOMPARE (history.size (), qint64 (4)); + QCOMPARE (history.end (3), qint64 (11)); + QVERIFY (history.snapshot (3, 7, 11) == std::vector ({1, 2, 3, 4})); + QVERIFY (history.append (3, 11, samples, 4)); + QVERIFY (history.snapshot (3, 9, 13) == std::vector ({3, 4, 1, 2})); + } + + void snapshotsOwnAudioBeyondInputReuseAndEviction () + { + Jtty::ReceiveHistory history {6}; + short samples[] = {1, 2, 3, 4}; + QVERIFY (history.append (4, 0, samples, 4)); + std::fill (std::begin (samples), std::end (samples), 9); + auto const saved = history.snapshot (4, 1, 4); + QVERIFY (saved == std::vector ({2, 3, 4})); + QVERIFY (history.append (4, 4, samples, 4)); + QVERIFY (history.snapshot (4, 0, 4).empty ()); + history.clear (); + QCOMPARE (history.size (), qint64 (0)); + QVERIFY (history.snapshot (4, 1, 4).empty ()); + QVERIFY (saved == std::vector ({2, 3, 4})); + } +}; + +QTEST_APPLESS_MAIN (TestJttyReceiveHistory) +#include "test_jtty_receive_history.moc" diff --git a/tests/unit/jtty/test_jtty_receive_line.cpp b/tests/unit/jtty/test_jtty_receive_line.cpp new file mode 100644 index 00000000..b25c7cfc --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_line.cpp @@ -0,0 +1,209 @@ +#include +#include +#include "JttyReceiveLine.hpp" + +class TestJttyReceiveLine final : public QObject +{ + Q_OBJECT + + static JttyReceiveLine::Presentation message (qint64 id, QString const& text, + double seconds = 0, quint64 group = 1) + { + return {group, id, QDateTime {QDate {2026, 9, 11}, QTime {12, 34, 56}, Qt::UTC}, + seconds, 1500, text}; + } + +private slots: + void growingWrappedLinePreservesOtherMessagesAndTransmitText () + { + QTextDocument document; + JttyReceiveLine first, second; + QFont const font {"Monospace", 10}; + QVERIFY (!first.render (document, message (11, "CQ TEST\nCONTINUATION"), {}, font).isNull ()); + QVERIFY (!second.render (document, message (12, "ANOTHER MESSAGE"), {}, font).isNull ()); + QTextCursor tx (&document); + tx.movePosition (QTextCursor::End); + tx.insertBlock (); + QTextBlockFormat txBlock; + txBlock.setBackground (Qt::yellow); + tx.setBlockFormat (txBlock); + QTextCharFormat txText; + txText.setForeground (Qt::red); + tx.insertText ("Tx: MY RESPONSE", txText); + QVERIFY (!first.render (document, message (11, "CQ TEST\nCONTINUATION COMPLETE"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 CQ TEST\nCONTINUATION COMPLETE\n1500 -10 ANOTHER MESSAGE\nTx: MY RESPONSE"}); + JttyReceiveLine::refresh (document, {true, true}, font); + QCOMPARE (document.toPlainText (), QString { + "123456 1500 -10 cq test\ncontinuation complete\n123456 1500 -10 another message\nTx: MY RESPONSE"}); + QCOMPARE (document.lastBlock ().blockFormat (), txBlock); + QTextCursor check (document.lastBlock ()); + check.movePosition (QTextCursor::NextCharacter, QTextCursor::KeepAnchor); + QCOMPARE (check.charFormat ().foreground (), txText.foreground ()); + QVERIFY (!second.render (document, message (12, "ANOTHER MESSAGE COMPLETE"), {true, true}, font).isNull ()); + QCOMPARE (document.lastBlock ().text (), QString {"Tx: MY RESPONSE"}); + QVERIFY (second.render (document, message (12, "ANOTHER MESSAGE COMPLETE"), {true, true}, font).isNull ()); + } + + void completedRecordsRefreshAndRestoreCanonicalCase () + { + QTextDocument document; + QFont const font {"Monospace", 10}; + { + JttyReceiveLine completed; + QVERIFY (!completed.render (document, message (1, "CQ MiXeD CASE"), {}, font).isNull ()); + } + QFont const larger {"Monospace", 14}; + JttyReceiveLine::refresh (document, {true, true}, larger); + QCOMPARE (document.toPlainText (), QString {"123456 1500 -10 cq mixed case"}); + QTextCursor check (document.begin ()); + check.movePosition (QTextCursor::NextCharacter, QTextCursor::KeepAnchor); + QCOMPARE (check.charFormat ().font ().pointSize (), 14); + JttyReceiveLine::refresh (document, {false, false}, font); + QCOMPARE (document.toPlainText (), QString {"1500 -10 CQ MiXeD CASE"}); + } + + void lateEarlierMessagesAndEqualTimeIdsAreOrdered () + { + QTextDocument document; + QFont const font; + { + JttyReceiveLine completed; + QVERIFY (!completed.render (document, message (30, "LATE", 30), {}, font, true).isNull ()); + } + JttyReceiveLine earlier, equal, middle; + QVERIFY (!earlier.render (document, message (20, "EARLIER", 10), {}, font, true).isNull ()); + QVERIFY (!equal.render (document, message (10, "EQUAL TIME LOWER ID", 10), {}, font, true).isNull ()); + QVERIFY (!middle.render (document, message (25, "MIDDLE", 20), {}, font, true).isNull ()); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 EQUAL TIME LOWER ID\n1500 -10 EARLIER\n1500 -10 MIDDLE\n1500 -10 LATE"}); + JttyReceiveLine::refresh (document, {true, false}, font); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 equal time lower id\n1500 -10 earlier\n1500 -10 middle\n1500 -10 late"}); + QVERIFY (!earlier.render (document, message (20, "EARLIER COMPLETE", 10), {true, false}, font, true).isNull ()); + QCOMPARE (document.findBlockByNumber (1).text (), QString {"1500 -10 earlier complete"}); + } + + void chronologyStaysWithinItsGroupAndQsoAppends () + { + QTextDocument document; + QFont const font; + JttyReceiveLine first, second, late, early, qso; + QVERIFY (!first.render (document, message (1, "GROUP ONE", 20, 1), {}, font, true).isNull ()); + QTextCursor heading (&document); + heading.movePosition (QTextCursor::End); + heading.insertBlock (); + QTextBlockFormat headingFormat; + headingFormat.setAlignment (Qt::AlignRight); + heading.setBlockFormat (headingFormat); + heading.insertText ("FILE HEADING"); + QVERIFY (!second.render (document, message (1, "GROUP TWO", 5, 2), {}, font, true).isNull ()); + QVERIFY (!late.render (document, message (2, "GROUP ONE LATER", 30, 1), {}, font, true).isNull ()); + QVERIFY (!early.render (document, message (0, "GROUP TWO EARLIER", 1, 2), {}, font, true).isNull ()); + QVERIFY (!qso.render (document, message (0, "QSO APPENDED", 0, 1), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 GROUP ONE\n1500 -10 GROUP ONE LATER\nFILE HEADING\n1500 -10 GROUP TWO EARLIER\n1500 -10 GROUP TWO\n1500 -10 QSO APPENDED"}); + QCOMPARE (document.findBlockByNumber (2).blockFormat (), headingFormat); + } + + void eraseAndReplacementCannotReuseOldOwnership () + { + QTextDocument document; + JttyReceiveLine old, replacement; + QFont const font; + QVERIFY (!old.render (document, message (1, "OLD PARTIAL"), {}, font).isNull ()); + document.clear (); + QVERIFY (!replacement.render (document, message (2, "NEW MESSAGE"), {}, font).isNull ()); + QVERIFY (old.render (document, message (1, "OLD PARTIAL COMPLETED"), {}, font).isNull ()); + JttyReceiveLine::refresh (document, {true, false}, font); + QCOMPARE (document.toPlainText (), QString {"1500 -10 new message"}); + QVERIFY (!replacement.render (document, message (2, "NEW MESSAGE COMPLETED"), {}, font).isNull ()); + QVERIFY (old.render (document, message (1, "OLD PARTIAL COMPLETED"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 NEW MESSAGE COMPLETED"}); + } + + void prunedBlocksCannotEraseReusedBlocksOrReappear () + { + QTextDocument document; + document.setMaximumBlockCount (3); + JttyReceiveLine old; + QFont const font; + QVERIFY (!old.render (document, message (1, "OLD PARTIAL\nOLD CONTINUATION"), {}, font).isNull ()); + for (int i = 0; i < 20; ++i) { + JttyReceiveLine archived; + QVERIFY (!archived.render (document, message (i + 2, QString::number (i)), {}, font).isNull ()); + } + auto const retained = document.toPlainText (); + QVERIFY (old.render (document, message (1, "OLD PARTIAL COMPLETE"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), retained); + QCOMPARE (document.blockCount (), 3); + } + + void partiallyPrunedWrappedRecordIsNotRefreshed () + { + QTextDocument document; + document.setMaximumBlockCount (3); + QFont const font; + JttyReceiveLine wrapped; + QString const longMessage (90, QLatin1Char {'A'}); + QVERIFY (!wrapped.render (document, message (1, longMessage), {}, font).isNull ()); + QCOMPARE (document.blockCount (), 3); + { + JttyReceiveLine completed; + QVERIFY (!completed.render (document, message (2, "RETAINED"), {}, font).isNull ()); + } + auto const first = document.begin ().text (); + auto const second = document.begin ().next ().text (); + JttyReceiveLine::refresh (document, {true, true}, font); + QCOMPARE (document.begin ().text (), first); + QCOMPARE (document.begin ().next ().text (), second); + QCOMPARE (document.lastBlock ().text (), QString {"123456 1500 -10 retained"}); + QVERIFY (wrapped.render (document, message (1, longMessage + " COMPLETE"), {}, font).isNull ()); + document.clear (); + JttyReceiveLine::refresh (document, {}, font); + QVERIFY (document.toPlainText ().isEmpty ()); + } + + void earlierInsertAtHistoryLimitCannotTakeExistingOwnership () + { + QTextDocument document; + document.setMaximumBlockCount (1); + QFont const font; + JttyReceiveLine retained, earlier; + QVERIFY (!retained.render (document, message (2, "RETAINED", 20), {}, font, true).isNull ()); + QVERIFY (earlier.render (document, message (1, "EARLIER", 10), {}, font, true).isNull ()); + JttyReceiveLine::refresh (document, {true, false}, font); + QCOMPARE (document.toPlainText (), QString {"1500 -10 retained"}); + QVERIFY (!retained.render (document, message (2, "RETAINED COMPLETE", 20), {}, font, true).isNull ()); + QVERIFY (earlier.render (document, message (1, "EARLIER COMPLETE", 10), {}, font, true).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 RETAINED COMPLETE"}); + } + + void foreignTextInsideOwnedRangeIsNeverDeleted () + { + QTextDocument document; + JttyReceiveLine old; + QFont const font; + QVERIFY (!old.render (document, message (1, "PARTIAL"), {}, font).isNull ()); + QTextCursor external (&document); + external.movePosition (QTextCursor::End); + external.insertText (" UNRELATED TEXT"); + JttyReceiveLine::refresh (document, {true, true}, font); + QVERIFY (old.render (document, message (1, "PARTIAL COMPLETED"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 PARTIAL UNRELATED TEXT"}); + } + + void movedActiveHandleStillOwnsItsMessage () + { + QTextDocument document; + JttyReceiveLine line; + QFont const font; + QVERIFY (!line.render (document, message (9, "PARTIAL"), {}, font).isNull ()); + auto moved = std::move (line); + QVERIFY (!moved.render (document, message (9, "PARTIAL COMPLETE"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 PARTIAL COMPLETE"}); + } +}; + +QTEST_MAIN (TestJttyReceiveLine) +#include "test_jtty_receive_line.moc" diff --git a/tests/unit/jtty/test_jtty_receive_results.cpp b/tests/unit/jtty/test_jtty_receive_results.cpp new file mode 100644 index 00000000..af88d9e6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_results.cpp @@ -0,0 +1,396 @@ +#include +#include + +#include "JttyReceiveResultController.hpp" + +namespace { +using Controller = Jtty::ReceiveResultController; +using Source = Controller::Source; +using Pane = Controller::Pane; +using Terminal = Jtty::ReceiveTerminal; + +Jtty::ReceiveUpdate update (qint64 id, QString const& text, + Terminal terminal = Terminal::Growing, + float frequency = 1500, int snr = -7) +{ + return {id, frequency, text, 2.25, 4.5, terminal, snr}; +} + +struct Harness +{ + Controller controller; + QTextDocument all, qso; + QFont font {"Monospace", 10}; + Controller::Reception reception; + Controller::Selection selection {true, 1, 1500, 50}; + JttyReceiveLine::Options display; + Controller::EchoOptions echo {true, false}; + bool reporting {true}; + QStringList trace, echoes, logs; + QVector logContexts; + QVector spots; + QVector> intervals; + QVector presentations; + std::function after; + Controller::Inputs inputs; + Controller::Effects effects; + + void event (QString const& name) + { + trace.append (name); + if (after) after (name); + } + + Harness () + { + reception.contextId = 1; + reception.displayGroup = 1; + reception.anchor = QDateTime {QDate {2026, 9, 11}, QTime {12, 34, 56}, Qt::UTC}; + reception.displayAnchor = reception.anchor; + reception.context.mode = "JTTY"; + reception.context.myCall = "N0ME"; + reception.context.periodFrequency = 14078000; + reception.context.band = "20m"; + inputs.display = [this] { event ("display"); return display; }; + inputs.selection = [this] { event ("selection"); return selection; }; + inputs.echo = [this] { event ("echo-options"); return echo; }; + inputs.reporting = [this] { event ("reporting"); return reporting; }; + effects.reviewHeading = [this] (Pane pane) { + auto& document = pane == Pane::All ? all : qso; + QTextCursor cursor {&document}; + cursor.movePosition (QTextCursor::End); + if (cursor.position ()) cursor.insertBlock (); + cursor.insertText ("REVIEW"); + event (pane == Pane::All ? "heading-all" : "heading-qso"); + }; + effects.render = [this] (Pane pane, JttyReceiveLine& line, + JttyReceiveLine::Presentation const& presentation, + JttyReceiveLine::Options const& options) { + line.render (pane == Pane::All ? all : qso, presentation, options, + font, pane == Pane::All); + presentations.append (presentation); + event (pane == Pane::All ? "all" : "qso"); + }; + effects.echo = [this] (QString const& text) { echoes.append (text); event ("echo"); }; + effects.noteDecoded = [this] (qint64 first, qint64 last) { + intervals.append (qMakePair (first, last)); event ("recording"); + }; + effects.log = [this] (QString const& text, DecodeOperatingContext const& context) { + logs.append (text); logContexts.append (context); event ("log"); + }; + effects.spot = [this] (Controller::Spot const& spot) { spots.append (spot); event ("spot"); }; + } + + void apply (QVector const& updates) + { + controller.apply (updates, reception, inputs, effects); + } +}; +} + +class TestJttyReceiveResults final : public QObject +{ + Q_OBJECT + +private slots: + void interleavedGrowthAndTerminalOnlyDelivery () + { + Harness h; + h.apply ({update (1, "CQ K1ABC"), update (2, "OTHER")}); + auto const firstBlock = h.all.begin (); + auto const firstQsoBlock = h.qso.begin (); + h.apply ({update (1, "CQ K1ABC FN42"), update (1, "CQ K1ABC FN42", Terminal::Complete), + update (3, "CQ K1ABC FN42", Terminal::Complete)}); + QCOMPARE (h.all.blockCount (), 3); + QCOMPARE (h.qso.blockCount (), 3); + QCOMPARE (h.all.begin (), firstBlock); + QCOMPARE (h.qso.begin (), firstQsoBlock); + QCOMPARE (h.all.toPlainText (), QString {"1500 -7 CQ K1ABC FN42\n1500 -7 OTHER\n1500 -7 CQ K1ABC FN42"}); + QCOMPARE (h.logs.size (), 2); + QCOMPARE (h.logs.front (), QString {"1500 -7 CQ K1ABC FN42"}); + QCOMPARE (h.spots.size (), 2); + QCOMPARE (h.intervals.size (), 5); + QCOMPARE (h.intervals.front (), qMakePair (qint64 {54000}, qint64 {76656})); + h.apply ({update (1, "CQ K1ABC FN42", Terminal::Complete)}); + QCOMPARE (h.logs.size (), 3); + QCOMPARE (h.spots.size (), 3); + QCOMPARE (h.all.blockCount (), 4); + } + + void sourceAndTerminalPolicy_data () + { + QTest::addColumn ("source"); + QTest::addColumn ("terminal"); + QTest::addColumn ("empty"); + for (int source = 0; source < 3; ++source) + for (int terminal = 0; terminal < 4; ++terminal) + for (bool empty : {false, true}) { + auto const name = QString {"source-%1-terminal-%2-empty-%3"}.arg (source).arg (terminal).arg (empty); + QTest::newRow (qPrintable (name)) << source << terminal << empty; + } + } + + void sourceAndTerminalPolicy () + { + QFETCH (int, source); + QFETCH (int, terminal); + QFETCH (bool, empty); + Harness h; + h.reception.source = static_cast (source); + auto const review = h.reception.source == Source::Review; + auto const live = h.reception.source == Source::Live; + h.apply ({update (1, empty ? QString {} : QString {"CQ K1ABC FN42"}, static_cast (terminal))}); + QCOMPARE (h.logs.size (), int (!empty && !review && terminal != 0)); + QCOMPARE (h.spots.size (), int (!empty && live && terminal == 1)); + QCOMPARE (h.intervals.size (), int (!empty && live)); + QCOMPARE (h.echoes.size (), int (!empty && !review)); + QCOMPARE (h.trace.count ("heading-all"), int (!empty && review)); + QCOMPARE (h.trace.count ("heading-qso"), int (!empty && review)); + QCOMPARE (h.presentations.size (), empty ? 0 : 2); + if (empty) QVERIFY (h.trace.isEmpty ()); + } + + void tuningAdmissionIsStickyAndUsesCurrentLiveContext () + { + Harness h; + h.selection.center = 1600; + h.apply ({update (1, "EXCLUDED")}); + QVERIFY (h.qso.isEmpty ()); + h.selection.center = 1500; + QVERIFY (h.qso.isEmpty ()); + h.apply ({update (1, "EXCLUDED")}); + QVERIFY (h.qso.toPlainText ().contains ("EXCLUDED")); + QCOMPARE (h.echoes, QStringList {"\r\nEXCLUDED"}); + h.selection.center = 1700; + h.apply ({update (1, "EXCLUDED NOW INCLUDED")}); + QVERIFY (h.qso.toPlainText ().contains ("EXCLUDED NOW INCLUDED")); + QCOMPARE (h.echoes.last (), QString {" NOW INCLUDED"}); + + for (Source source : {Source::Live, Source::Review, Source::Wav}) { + Harness captured; + captured.reception.source = source; + captured.selection.contextId = 2; + captured.selection.center = 1700; + captured.apply ({update (1, "CAPTURED")}); + QVERIFY (captured.qso.toPlainText ().contains ("CAPTURED")); + } + Harness inactive; + inactive.selection.jttyActive = false; + inactive.selection.center = 1700; + inactive.apply ({update (1, "INACTIVE")}); + QVERIFY (inactive.qso.toPlainText ().contains ("INACTIVE")); + } + + void retainedContextAndPresentationHaveSeparateAnchors () + { + Harness h; + auto const firstAnchor = h.reception.anchor; + h.reception.displayAnchor = firstAnchor.addDays (1); + h.display = {true, true}; + h.apply ({update (1, "CQ K1ABC")}); + auto const trace = h.trace; + h.apply ({update (1, {}, Terminal::Complete)}); + QCOMPARE (h.trace, trace); + h.reception.context.myCall = "K1ABC"; + h.reception.context.periodFrequency = 7000000; + h.reception.context.band = "40m"; + h.reception.anchor = firstAnchor.addDays (2); + h.reception.displayAnchor = firstAnchor.addDays (3); + auto complete = update (1, "CQ K1ABC FN42", Terminal::Complete, 1500.6f, -3); + complete.startSeconds = 9; + h.apply ({complete}); + QCOMPARE (h.logContexts.size (), 1); + QCOMPARE (h.logContexts.front ().sequenceStart, firstAnchor.addMSecs (2250)); + QCOMPARE (h.logContexts.front ().band, QString {"20m"}); + QCOMPARE (h.logContexts.front ().myCall, QString {"N0ME"}); + QCOMPARE (h.logs.front (), QString {"1501 -3 CQ K1ABC FN42"}); + QCOMPARE (h.presentations.last ().startUtc, h.reception.displayAnchor.addSecs (9)); + QCOMPARE (h.spots.size (), 1); + auto const& spot = h.spots.front (); + QCOMPARE (spot.sender, QString {"K1ABC"}); + QCOMPARE (spot.grid, QString {"FN42"}); + QCOMPARE (spot.frequency, Radio::Frequency {14079501}); + QCOMPARE (spot.mode, QString {"JTTY"}); + QCOMPARE (spot.snr, -3); + QCOMPARE (spot.time, firstAnchor.addMSecs (2250)); + QCOMPARE (spot.time.timeSpec (), Qt::UTC); + QVERIFY (h.all.toPlainText ().contains ("cq k1abc fn42")); + } + + void reportSyntax_data () + { + QTest::addColumn ("text"); + QTest::addColumn ("eligible"); + QTest::addColumn ("grid"); + QTest::newRow ("cq") << QString {"cq k1abc fn42ab"} << true << QString {"fn42ab"}; + QTest::newRow ("de") << QString {"De K1ABC"} << true << QString {}; + QTest::newRow ("call pair") << QString {"W9XYZ K1ABC FN42"} << true << QString {"FN42"}; + QTest::newRow ("portable") << QString {"CQ K1ABC/P FN42"} << true << QString {"FN42"}; + QTest::newRow ("invalid grid") << QString {"CQ K1ABC ZZ99"} << true << QString {}; + QTest::newRow ("rr73") << QString {"CQ K1ABC RR73"} << true << QString {}; + QTest::newRow ("free text") << QString {"HELLO K1ABC FN42"} << false << QString {}; + QTest::newRow ("invalid sender") << QString {"CQ EA8/K1ABC FN42"} << false << QString {}; + QTest::newRow ("self") << QString {"CQ n0me FN42"} << false << QString {}; + QTest::newRow ("missing sender") << QString {"CQ"} << false << QString {}; + } + + void reportSyntax () + { + QFETCH (QString, text); + QFETCH (bool, eligible); + QFETCH (QString, grid); + Harness h; + h.apply ({update (1, text, Terminal::Complete)}); + QCOMPARE (h.spots.size (), int (eligible)); + if (eligible) QCOMPARE (h.spots.front ().grid, grid); + h.reporting = false; + h.apply ({update (2, text, Terminal::Complete)}); + QCOMPARE (h.spots.size (), int (eligible)); + h.reporting = true; + h.reception.anchor = {}; + h.apply ({update (3, text, Terminal::Complete)}); + QCOMPARE (h.spots.size (), int (eligible)); + } + + void snapshotsAndEffectsFollowSynchronousPhases () + { + Harness h; + h.selection.center = 1700; + h.reporting = false; + h.after = [&h] (QString const& event) { + if (event == "all") { h.selection.center = 1500; h.display.lowerCase = true; } + if (event == "qso") h.echo.lowerCase = true; + if (event == "log") h.reporting = true; + if (event == "spot") + QCOMPARE (h.controller.snrForSelectedWord ("K1ABC", Pane::All), -10); + }; + h.apply ({update (1, "CQ K1ABC FN42", Terminal::Complete)}); + QCOMPARE (h.trace, QStringList ({"display", "all", "selection", "qso", "echo-options", + "echo", "recording", "log", "reporting", "spot"})); + QVERIFY (h.qso.toPlainText ().contains ("CQ K1ABC FN42")); + QCOMPARE (h.echoes, QStringList {"\r\ncq k1abc fn42"}); + QCOMPARE (h.spots.size (), 1); + QCOMPARE (h.controller.snrForSelectedWord ("K1ABC", Pane::All), -7); + } + + void echoDeltaPolicy () + { + Harness h; + h.apply ({update (1, "FIRST"), update (1, "FIRST LONGER"), update (1, "FIRST LONGER"), + update (1, "REPLACED")}); + QCOMPARE (h.echoes, QStringList ({"\r\nFIRST", " LONGER", "\r\nREPLACED"})); + h.echo.enabled = false; + h.apply ({update (1, "REPLACED SILENT")}); + QCOMPARE (h.echoes.size (), 3); + h.echo = {true, true}; + h.apply ({update (1, "REPLACED SILENT END", Terminal::Complete)}); + QCOMPARE (h.echoes.last (), QString {" end"}); + } + + void replayResetAndRefreshPreserveLiveHistory () + { + Harness h; + h.apply ({update (1, "LIVE")}); + h.reception.source = Source::Review; + h.reception.displayGroup = 2; + h.apply ({update (2, {})}); + QCOMPARE (h.trace.count ("heading-all"), 0); + h.apply ({update (2, "REVIEW MESSAGE", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 1); + QVERIFY (h.trace.indexOf ("heading-all") < h.trace.indexOf ("heading-qso")); + h.reception.displayGroup = 3; + h.apply ({update (3, "LATER REVIEW", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 1); + h.controller.resetReplay (); + h.reception.displayGroup = 4; + h.apply ({update (4, "RESET REVIEW", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 2); + h.reception.source = Source::Wav; + h.reception.displayGroup = 5; + h.apply ({update (5, "WAV", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 2); + h.reception.source = Source::Live; + h.reception.displayGroup = 1; + h.apply ({update (1, "LIVE COMPLETE", Terminal::Complete)}); + QCOMPARE (h.all.toPlainText ().count ("LIVE"), 1); + QCOMPARE (h.logs.size (), 2); + QCOMPARE (h.intervals.size (), 2); + auto const trace = h.trace; + auto const original = h.all.toPlainText (); + JttyReceiveLine::refresh (h.all, {true, true}, h.font); + JttyReceiveLine::refresh (h.qso, {true, true}, h.font); + QVERIFY (h.all.toPlainText ().contains ("live complete")); + JttyReceiveLine::refresh (h.all, {}, h.font); + QCOMPARE (h.all.toPlainText (), original); + QCOMPARE (h.trace, trace); + QCOMPARE (h.controller.snrForSelectedWord ("MESSAGE", Pane::All), -7); + } + + void clearedActiveHandlesDoNotResurrectMessages () + { + Harness h; + h.apply ({update (1, "REMOVED")}); + h.all.clear (); + h.qso.clear (); + h.apply ({update (2, "RETAINED"), update (1, "REMOVED COMPLETE", Terminal::Complete)}); + QCOMPARE (h.all.toPlainText (), QString {"1500 -7 RETAINED"}); + QCOMPARE (h.qso.toPlainText (), h.all.toPlainText ()); + QCOMPARE (h.logs.size (), 1); + QVERIFY (h.logs.front ().contains ("REMOVED COMPLETE")); + } + + void replayResetRetiresOnlyReplayActiveRecords () + { + Harness h; + h.apply ({update (1, "LIVE")}); + h.reception.source = Source::Review; + h.reception.displayGroup = 2; + h.apply ({update (1, "REPLAY")}); + QCOMPARE (h.all.toPlainText ().count ("LIVE"), 1); + QCOMPARE (h.all.toPlainText ().count ("REPLAY"), 1); + h.controller.resetReplay (); + h.reception.source = Source::Wav; + h.reception.displayGroup = 3; + h.reception.context.band = "40m"; + h.apply ({update (1, "WAV", Terminal::Complete)}); + QCOMPARE (h.logContexts.front ().band, QString {"40m"}); + QVERIFY (h.all.toPlainText ().contains ("REPLAY")); + QVERIFY (h.all.toPlainText ().contains ("WAV")); + h.reception.source = Source::Live; + h.reception.displayGroup = 1; + h.apply ({update (1, "LIVE COMPLETE", Terminal::Complete)}); + QCOMPARE (h.logContexts.last ().band, QString {"20m"}); + QCOMPARE (h.all.toPlainText ().count ("LIVE"), 1); + QVERIFY (h.all.toPlainText ().contains ("LIVE COMPLETE")); + } + + void snrLookupTracksEveryUpdateAndEvictsOldEntries () + { + Harness h; + h.apply ({update (1, "CQ TOKEN", Terminal::Growing, 1500, -2)}); + h.apply ({update (1, "CQ TOKEN", Terminal::Complete, 1500, -3)}); + h.selection.center = 1700; + h.apply ({update (2, "CQ TOKEN", Terminal::Complete, 1500, -4)}); + QCOMPARE (h.controller.snrForSelectedWord ("TOKEN", Pane::All), -4); + QCOMPARE (h.controller.snrForSelectedWord ("TOKEN", Pane::Qso), -3); + QCOMPARE (h.controller.snrForSelectedWord ("token", Pane::All), -10); + QCOMPARE (h.controller.snrForSelectedWord ("TOK", Pane::All), -10); + h.reception.source = Source::Review; + h.apply ({update (3, "REVIEWTOKEN", Terminal::Complete, 1500, -5)}); + h.controller.resetReplay (); + h.reception.source = Source::Wav; + h.apply ({update (4, "WAVTOKEN", Terminal::Complete, 1500, -6)}); + QCOMPARE (h.controller.snrForSelectedWord ("REVIEWTOKEN", Pane::Qso), -5); + QCOMPARE (h.controller.snrForSelectedWord ("WAVTOKEN", Pane::All), -6); + h.apply ({update (5, "EVICT", Terminal::Complete, 1500, -8)}); + for (int i = 0; i < 499; ++i) + h.apply ({update (6, "FILLER", Terminal::Growing, 1500, i)}); + QCOMPARE (h.controller.snrForSelectedWord ("EVICT", Pane::All), -8); + h.apply ({update (6, "FILLER", Terminal::Complete, 1500, 499)}); + QCOMPARE (h.controller.snrForSelectedWord ("EVICT", Pane::All), -10); + QCOMPARE (h.controller.snrForSelectedWord ("FILLER", Pane::All), 499); + } +}; + +QTEST_MAIN (TestJttyReceiveResults) +#include "test_jtty_receive_results.moc" diff --git a/tests/unit/jtty/test_jtty_recording.cpp b/tests/unit/jtty/test_jtty_recording.cpp new file mode 100644 index 00000000..0e903e3a --- /dev/null +++ b/tests/unit/jtty/test_jtty_recording.cpp @@ -0,0 +1,274 @@ +#include +#include +#include +#include +#include + +#include "Audio/BWFFile.hpp" +#include "JttyRecording.hpp" + +namespace +{ +using Recording = JttyRecording; + +Recording::Settings settings (Recording::SavePolicy policy) +{ + Recording::Settings result; + result.policy = policy; + result.directory = QStringLiteral ("/unused-recording-test-path"); + result.myCall = QStringLiteral ("K1ABC"); + result.myGrid = QStringLiteral ("FN42"); + result.frequency = 14074000; + return result; +} + +QDateTime origin () +{ + return QDateTime {QDate {2026, 9, 11}, QTime {23, 58, 42, 123}, Qt::UTC}; +} + +std::vector audio (qint64 count) +{ + std::vector result (std::size_t (count), 0); + for (qint64 i = 0; i < count; ++i) result[std::size_t (i)] = short (i % 30001); + return result; +} +} + +class TestJttyRecording final : public QObject +{ + Q_OBJECT +private slots: + void overlappingSegmentsRetainExactAudioAndOrigin () + { + std::vector saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (17, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (Recording::segmentSamples + 123); + recorder.feed (0, pcm.data (), int (pcm.size ())); + QCOMPARE (saved.size (), std::size_t {1}); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {2}); + QCOMPARE (saved[0]->firstSample, qint64 {0}); + QCOMPARE (saved[0]->endSample (), Recording::segmentSamples); + QCOMPARE (saved[1]->firstSample, Recording::hopSamples); + QCOMPARE (saved[1]->endSample (), qint64 (pcm.size ())); + QVERIFY (saved[0]->id != saved[1]->id); + QVERIFY (saved[0]->fileName != saved[1]->fileName); + for (auto const& segment : saved) { + QCOMPARE (segment->reception, quint64 {17}); + QCOMPARE (segment->firstSampleUtc, origin ().addMSecs (segment->firstSample / 12)); + QVERIFY (std::equal (segment->samples.begin (), segment->samples.end (), + pcm.begin () + segment->firstSample)); + } + QCOMPARE (saved[1]->firstSampleUtc.date (), QDate (2026, 9, 12)); + } + + void partialDecodeQualifiesBothOverlappingSegmentsAfterClosure () + { + std::vector saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::Decoded)); + auto const pcm = audio (Recording::segmentSamples + 100); + recorder.feed (0, pcm.data (), int (pcm.size ())); + QVERIFY (saved.empty ()); + recorder.noteDecoded (Recording::segmentSamples - 1000, Recording::segmentSamples + 10); + recorder.advanceDecoderWatermark (Recording::segmentSamples - 1); + QVERIFY (saved.empty ()); + recorder.advanceDecoderWatermark (Recording::segmentSamples); + QCOMPARE (saved.size (), std::size_t {1}); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {2}); + QVERIFY (saved[0]->decoded); + QVERIFY (saved[1]->decoded); + } + + void noiseAndNonoverlappingEvidenceDoNotQualify () + { + int writes = 0; + Recording recorder {nullptr, [&writes] (Recording::Snapshot, Recording::Completion done) { + ++writes; + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::Decoded)); + auto const pcm = audio (1000); + recorder.feed (0, pcm.data (), int (pcm.size ())); + recorder.noteDecoded (1000, 2000); + recorder.noteDecoded (20, 20); + recorder.endReception (); + QCOMPARE (writes, 0); + } + + void savePolicyIsFrozenAndOffIntervalsAreNotJoined () + { + std::vector saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (8000); + recorder.feed (0, pcm.data (), 1000); + recorder.updateSavePolicy (Recording::SavePolicy::Off); + QCOMPARE (saved.size (), std::size_t {1}); + QCOMPARE (saved[0]->settings.policy, Recording::SavePolicy::All); + recorder.feed (1000, pcm.data (), 1000); + recorder.updateSavePolicy (Recording::SavePolicy::Decoded); + recorder.feed (2000, pcm.data () + 2000, 6000); + recorder.noteDecoded (5700, 5800); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {2}); + QCOMPARE (QFileInfo {saved[0]->fileName}.fileName (), QStringLiteral ("260911_235842_123.wav")); + QCOMPARE (QFileInfo {saved[1]->fileName}.fileName (), QStringLiteral ("260911_235842_595.wav")); + QCOMPARE (saved[1]->firstSample, Recording::searchStepSamples); + QCOMPARE (saved[1]->samples.size (), std::size_t (8000 - Recording::searchStepSamples)); + QVERIFY (std::equal (saved[1]->samples.begin (), saved[1]->samples.end (), + pcm.begin () + Recording::searchStepSamples)); + QCOMPARE (saved[1]->settings.policy, Recording::SavePolicy::Decoded); + } + + void metadataUpdatesApplyOnlyToNewSegments () + { + std::vector saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + auto initial = settings (Recording::SavePolicy::All); + initial.hisCall = QStringLiteral ("K1OLD"); + recorder.beginReception (1, origin (), initial); + auto const pcm = audio (Recording::segmentSamples + 1); + recorder.feed (0, pcm.data (), int (Recording::hopSamples)); + + auto updated = initial; + updated.directory = QStringLiteral ("/updated-recording-test-path"); + updated.hisCall = QStringLiteral ("K1NEW"); + updated.policy = Recording::SavePolicy::Off; + recorder.updateMetadata (updated); + recorder.feed (Recording::hopSamples, pcm.data () + Recording::hopSamples, + int (pcm.size () - Recording::hopSamples)); + recorder.endReception (); + + QCOMPARE (saved.size (), std::size_t {2}); + QCOMPARE (saved[0]->settings.hisCall, QStringLiteral ("K1OLD")); + QCOMPARE (saved[0]->settings.directory, initial.directory); + QCOMPARE (saved[1]->settings.hisCall, QStringLiteral ("K1NEW")); + QCOMPARE (saved[1]->settings.directory, updated.directory); + QCOMPARE (saved[1]->settings.policy, Recording::SavePolicy::All); + } + + void delayedFailureStopsSavingUntilExplicitRearm () + { + std::vector completions; + int errors = 0; + Recording recorder {nullptr, [&completions] (Recording::Snapshot, Recording::Completion done) { + completions.push_back (done); + }}; + recorder.setErrorHandler ([&errors] (QString const&) {++errors;}); + auto const pcm = audio (7000); + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + recorder.feed (0, pcm.data (), 1000); + recorder.endReception (); + QCOMPARE (recorder.snapshotsInFlight (), 1); + completions[0] (QStringLiteral ("disk full")); + QVERIFY (recorder.suspendedAfterError ()); + QCOMPARE (errors, 1); + recorder.beginReception (2, origin (), settings (Recording::SavePolicy::All)); + recorder.feed (0, pcm.data (), 1000); + QCOMPARE (completions.size (), std::size_t {1}); + recorder.updateSavePolicy (Recording::SavePolicy::All); + recorder.feed (1000, pcm.data () + 1000, 6000); + recorder.endReception (); + QCOMPARE (completions.size (), std::size_t {2}); + completions[1] ({}); + QVERIFY (!recorder.suspendedAfterError ()); + } + + void delayedStartPreservesSearchPhaseAcrossInputBlocks () + { + std::vector saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (8000); + recorder.feed (3456, pcm.data () + 3456, 1000); + recorder.feed (4456, pcm.data () + 4456, 1000); + recorder.feed (5456, pcm.data () + 5456, 2544); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {1}); + QCOMPARE (saved[0]->firstSample, Recording::searchStepSamples); + QCOMPARE (saved[0]->endSample (), qint64 {8000}); + QCOMPARE (saved[0]->firstSampleUtc, origin ().addMSecs (Recording::searchStepSamples / 12)); + QVERIFY (std::equal (saved[0]->samples.begin (), saved[0]->samples.end (), + pcm.begin () + Recording::searchStepSamples)); + } + + void slowWriterCannotRetainUnboundedAudio () + { + std::vector completions; + int errors = 0; + Recording recorder {nullptr, [&completions] (Recording::Snapshot, Recording::Completion done) { + completions.push_back (done); + }}; + recorder.setErrorHandler ([&errors] (QString const&) {++errors;}); + auto const pcm = audio (1000); + for (quint64 reception = 1; reception <= 3; ++reception) { + recorder.beginReception (reception, origin (), settings (Recording::SavePolicy::All)); + recorder.feed (0, pcm.data (), 1000); + recorder.endReception (); + } + QCOMPARE (completions.size (), std::size_t {Recording::maximumSnapshots}); + QCOMPARE (recorder.snapshotsInFlight (), Recording::maximumSnapshots); + QVERIFY (recorder.suspendedAfterError ()); + QCOMPARE (errors, 1); + for (auto const& done : completions) done ({}); + QCOMPARE (recorder.snapshotsInFlight (), 0); + } + + void discontinuityRequiresANewReception () + { + int errors = 0; + Recording recorder {nullptr, [] (Recording::Snapshot, Recording::Completion done) {done ({});}}; + recorder.setErrorHandler ([&errors] (QString const&) {++errors;}); + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (1000); + recorder.feed (0, pcm.data (), 1000); + recorder.feed (1001, pcm.data (), 1000); + QVERIFY (recorder.suspendedAfterError ()); + QCOMPARE (errors, 1); + } + + void writerPreservesCaptureTimeAndNeverOverwrites () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Recording::Segment segment; + segment.settings = settings (Recording::SavePolicy::All); + segment.fileName = directory.filePath (QStringLiteral ("260911_235842_test.wav")); + segment.firstSampleUtc = origin (); + segment.samplesSinceMidnight = quint64 (origin ().time ().msecsSinceStartOfDay ()) * 12 + 7; + segment.samples = audio (1000); + QVERIFY2 (Recording::writeSegment (segment).isEmpty (), "initial write failed"); + BWFFile wav {QAudioFormat {}, segment.fileName}; + QVERIFY (wav.open (QIODevice::ReadOnly)); + QCOMPARE (wav.bext_time_reference (), segment.samplesSinceMidnight); + QCOMPARE (wav.bext_origination_date_time (), origin ().addMSecs (-origin ().time ().msec ())); + QCOMPARE (wav.size (), qint64 {2000}); + wav.close (); + segment.samples.resize (10); + QVERIFY (!Recording::writeSegment (segment).isEmpty ()); + QVERIFY (wav.open (QIODevice::ReadOnly)); + QCOMPARE (wav.size (), qint64 {2000}); + } +}; + +QTEST_GUILESS_MAIN (TestJttyRecording) +#include "test_jtty_recording.moc" diff --git a/tests/unit/jtty/test_jtty_source_codec.f90 b/tests/unit/jtty/test_jtty_source_codec.f90 index dead01d8..3d1ee9b0 100644 --- a/tests/unit/jtty/test_jtty_source_codec.f90 +++ b/tests/unit/jtty/test_jtty_source_codec.f90 @@ -1,5 +1,6 @@ program test_jtty_source_codec use jtty_mod + use packjt77_grammar, only: pack77_arrl_section_index implicit none type(jtty_source_atom) :: atom,decoded,atoms(2) character(len=34) :: frame,frames(MAX_FRAMES) @@ -30,6 +31,24 @@ program test_jtty_source_codec '0000000111000000000000000001001001','0000000111100000000000000001001001', & '0000001000000000000000000001001001','0000001000100000000000000001001001'] + ! Section IDs are transmitted on the wire; preserve their assigned names. + character(len=3), parameter :: SECTION_NAMES(86)=[character(len=3) :: & + 'AB','AK','AL','AR','AZ','BC','CO','CT','DE','EB', & + 'EMA','ENY','EPA','EWA','GA','GH','IA','ID','IL','IN', & + 'KS','KY','LA','LAX','NS','MB','MDC','ME','MI','MN', & + 'MO','MS','MT','NC','ND','NE','NFL','NH','NL','NLI', & + 'NM','NNJ','NNY','TER','NTX','NV','OH','OK','ONE','ONN', & + 'ONS','OR','ORG','PAC','PR','QC','RI','SB','SC','SCV', & + 'SD','SDG','SF','SFL','SJV','SK','SNJ','STX','SV','TN', & + 'UT','VA','VI','VT','WCF','WI','WMA','WNY','WPA','WTX', & + 'WV','WWA','WY','DX','PE','NB'] + + if(PACK77_NSEC.ne.size(SECTION_NAMES)) error stop 'Section registry size changed' + do i=1,size(SECTION_NAMES) + if(pack77_arrl_section_index(SECTION_NAMES(i)).ne.i) error stop 'Section wire ID changed' + call expect_render(jtty_class_section_atom(1,'A',i),'1A '//trim(SECTION_NAMES(i))) + enddo + do i=0,5 call expect_vector(jtty_call_atom(i,'K1ABC'),CALL_VECTORS(i)) enddo diff --git a/tests/unit/jtty/test_jtty_spectrum.cpp b/tests/unit/jtty/test_jtty_spectrum.cpp new file mode 100644 index 00000000..e1d1556e --- /dev/null +++ b/tests/unit/jtty/test_jtty_spectrum.cpp @@ -0,0 +1,192 @@ +#include +#include +#include +#include +#include + +#include "commons.h" +#include "widgets/JttySpectrum.hpp" + +extern "C" { + void symspec_ (struct dec_data *, int *, int *, int *, bool *, int *, + float *, float *, float *, int *, int *, float *, int *); +} + +namespace { +std::vector fixture (int count) +{ + std::vector result (count); + quint32 random = 17; + for (int i = 0; i < count; ++i) { + random = 1664525u * random + 1013904223u; + result[i] = 1000 * std::sin (2 * 3.141592653589793 * 1234 * i / 12000) + + int (random >> 24) - 128; + } + return result; +} + +QByteArray fingerprint (JttySpectrumFrame const& frame) +{ + QCryptographicHash hash {QCryptographicHash::Sha256}; + for (auto const * values : {&frame.bins, &frame.cumulative, &frame.linearAverage}) { + hash.addData (reinterpret_cast (values->data ()), sizeof (*values)); + } + return hash.result (); +} + +constexpr float spectrumToleranceScale = 5.e-4f; + +float spectrumTolerance (float actual, float expected) +{ + auto const magnitude = std::max ({1.f, std::abs (actual), std::abs (expected)}); + return spectrumToleranceScale * magnitude; +} + +bool spectrumNearlyEqual (float actual, float expected) +{ + return std::abs (actual - expected) <= spectrumTolerance (actual, expected); +} + +QString spectrumMismatch (char const * series, int bin, float actual, float expected) +{ + return QStringLiteral ("%1[%2]: actual=%3 expected=%4 difference=%5 tolerance=%6") + .arg (QString::fromLatin1 (series)).arg (bin) + .arg (actual, 0, 'g', 9).arg (expected, 0, 'g', 9) + .arg (std::abs (actual - expected), 0, 'g', 9) + .arg (spectrumTolerance (actual, expected), 0, 'g', 9); +} +} + +class TestJttySpectrum final : public QObject +{ + Q_OBJECT +private slots: + void agreesWithTimedSpectrumMath_data () + { + QTest::addColumn ("windowed"); + QTest::newRow ("rectangular") << false; + QTest::newRow ("low-sidelobes") << true; + } + + void agreesWithTimedSpectrumMath () + { + QFETCH (bool, windowed); + auto shared = std::make_unique (); + auto const pcm = fixture (24 * JttySpectrum::Hop); + std::copy (pcm.begin (), pcm.end (), shared->d2); + JttySpectrum spectrum; + spectrum.begin (1, 0, 0); + int nsps = 6912; + int gain = 3; + int smoothing = 2; + int symbols = 0; + int eighths = 0; + int percentile = 0; + for (int end = JttySpectrum::Hop; end <= int (pcm.size ()); end += JttySpectrum::Hop) { + std::array bins {}; + float db = 0, peak = 0, width = 0; + symspec_ (shared.get (), &end, &nsps, &gain, &windowed, &smoothing, + &db, bins.data (), &width, &symbols, &eighths, &peak, &percentile); + bool emitted = false; + QVERIFY (spectrum.process (end - JttySpectrum::Hop, pcm.data () + end - JttySpectrum::Hop, + JttySpectrum::Hop, gain, windowed, smoothing, [&] (JttySpectrumFrame const& frame) { + emitted = true; + QCOMPARE (frame.row.endSample, qint64 (end)); + QCOMPARE (frame.row.utcEndMs, qint64 (end / 12)); + QVERIFY (std::abs (frame.powerDb - db) < 0.002f); + QVERIFY (std::abs (frame.maxPowerDb - peak) < 0.002f); + for (int i = 0; i < NSMAX; ++i) { + QVERIFY2 (spectrumNearlyEqual (frame.bins[i], bins[i]), + qPrintable (spectrumMismatch ("bins", i, frame.bins[i], bins[i]))); + QVERIFY2 (spectrumNearlyEqual (frame.cumulative[i], shared->savg[i]), + qPrintable (spectrumMismatch ("cumulative", i, frame.cumulative[i], + shared->savg[i]))); + } + })); + QVERIFY (emitted); + } + } + + void packetizationAndLargeCoordinatesPreserveSpectrum () + { + auto const pcm = fixture (181 * 12000); + qint64 const origin = (qint64 (1) << 33) + 117; + qint64 const utc = 179000; + JttySpectrum whole; + JttySpectrum packets; + whole.begin (7, origin, utc); + packets.begin (7, origin, utc); + QVector expected; + QVERIFY (whole.process (origin, pcm.data (), int (pcm.size ()), 0, true, 1, + [&] (JttySpectrumFrame const& frame) { expected.append (fingerprint (frame)); })); + int frameIndex = 0; + int offset = 0; + while (offset < int (pcm.size ())) { + int const size = std::min (1 + (offset * 17LL % 4001), qint64 (pcm.size () - offset)); + QVERIFY (packets.process (origin + offset, pcm.data () + offset, size, 0, true, 1, + [&] (JttySpectrumFrame const& frame) { + QCOMPARE (fingerprint (frame), expected.at (frameIndex)); + QCOMPARE (frame.row.reception, quint64 (7)); + QCOMPARE (frame.row.beginSample, origin + qint64 (frameIndex) * JttySpectrum::Hop); + QCOMPARE (frame.row.utcEndMs, utc + qint64 (frameIndex + 1) * JttySpectrum::Hop / 12); + ++frameIndex; + })); + offset += size; + } + QCOMPARE (frameIndex, expected.size ()); + QVERIFY (!packets.process (origin, pcm.data (), 100, 0, true, 1, [] (JttySpectrumFrame const&) {})); + } + + void explicitReceptionResetsTailAndAverage () + { + auto const pcm = fixture (12 * JttySpectrum::Hop); + JttySpectrum reused; + reused.begin (1, 0, 0); + QVERIFY (reused.process (0, pcm.data (), int (pcm.size ()) - 13, 0, true, 1, + [] (JttySpectrumFrame const&) {})); + reused.begin (2, 999, 15000); + JttySpectrum fresh; + fresh.begin (2, 999, 15000); + QVector expected; + QVERIFY (fresh.process (999, pcm.data (), int (pcm.size ()), 0, true, 1, + [&] (JttySpectrumFrame const& frame) { expected.append (fingerprint (frame)); })); + int index = 0; + QVERIFY (reused.process (999, pcm.data (), int (pcm.size ()), 0, true, 1, + [&] (JttySpectrumFrame const& frame) { QCOMPARE (fingerprint (frame), expected.at (index++)); })); + QCOMPARE (index, expected.size ()); + } + + void averagesFollowNewSignalsAfterLongReception () + { + JttySpectrum spectrum; + spectrum.begin (3, 0, 0); + std::array pcm; + JttySpectrumFrame latest; + qint64 nextSample = 0; + auto receiveTone = [&] (int frequency, int frames) { + for (int i = 0; i < int (pcm.size ()); ++i) { + pcm[i] = 1000 * std::sin (2 * 3.141592653589793 * frequency * i / 12000); + } + for (int i = 0; i < frames; ++i) { + QVERIFY (spectrum.process (nextSample, pcm.data (), int (pcm.size ()), 0, true, 0, + [&] (JttySpectrumFrame const& frame) { latest = frame; })); + nextSample += pcm.size (); + } + }; + int const oldBin = int (1500 / JttySpectrumFrame::BinWidth); + int const newBin = int (2250 / JttySpectrumFrame::BinWidth); + receiveTone (1500, 720 * 12000 / JttySpectrum::Hop); + float const oldPower = latest.cumulative[oldBin]; + QVERIFY (oldPower > 0); + receiveTone (2250, 180 * 12000 / JttySpectrum::Hop); + QVERIFY (latest.cumulative[oldBin] < 0.5f * oldPower); + QVERIFY (latest.cumulative[newBin] > 1.5f * latest.cumulative[oldBin]); + QVERIFY (latest.linearAverage[newBin] > latest.linearAverage[oldBin]); + QCOMPARE (latest.row.reception, quint64 (3)); + QCOMPARE (latest.row.endSample, nextSample); + QCOMPARE (latest.row.utcEndMs, nextSample / 12); + } +}; + +QTEST_APPLESS_MAIN (TestJttySpectrum) +#include "test_jtty_spectrum.moc" diff --git a/tests/unit/jtty/test_jtty_structured_decode.f90 b/tests/unit/jtty/test_jtty_structured_decode.f90 index e74b9c2a..6a55a816 100644 --- a/tests/unit/jtty/test_jtty_structured_decode.f90 +++ b/tests/unit/jtty/test_jtty_structured_decode.f90 @@ -1,9 +1,10 @@ program test_jtty_structured_decode use iso_c_binding, only: c_int,c_char,c_null_char,c_sizeof - use iso_fortran_env, only: int16,int32 + use iso_fortran_env, only: int16,int32,real32 use jtty_fec, only: is13,PAYLOAD_BITS,TOTAL_K,tbcc_encode use jtty_tbcc_code_profiles + use jtty_tbcc_decoder, only: jtty_tbcc_decode use jtty_mdec, only: npending,pending_updates,nactive,discard_pending_updates,display_message_text use jtty_mod, only: jtty_source_atom,jtty_source_atom_c,jtty_call_atom, & jtty_exch_num_atom,unpack_jtty,MAX_FRAMES,JTTY_CALL_CALL,JTTY_ROLE_FULL, & @@ -25,11 +26,10 @@ program test_jtty_structured_decode integer(c_int), intent(out) :: tones(*),nsym integer(c_int) :: status end function jtty_cpp_n1mm_smoke - function jtty_cpp_cq_smoke(tones,nsym,text,chained) result(status) bind(C) + function jtty_cpp_cq_smoke(tones,nsym,text) result(status) bind(C) import :: c_int,c_char integer(c_int), intent(out) :: tones(*),nsym character(kind=c_char), intent(out) :: text(*) - integer(c_int), value :: chained integer(c_int) :: status end function jtty_cpp_cq_smoke function jtty_cpp_rtty_smoke(tones,nsym) result(status) bind(C) @@ -59,6 +59,7 @@ program test_jtty_structured_decode call decode_native_call_and_serial(failures) call decode_c_adapter_atoms(failures) call reject_invalid_c_descriptors(failures) + call reject_invalid_c_batch(failures) call decode_cpp_compiled_n1mm(failures) call decode_compact_text(failures) call decode_profile_text(failures) @@ -79,13 +80,7 @@ contains call expect(status.eq.JTTY_ENCODE_OK .and. nsymbols.eq.frame_symbols, & 'C++ RTTY profile text matches native F8 while unknown text uses two frames',count) if(status.ne.JTTY_ENCODE_OK .or. nsymbols.ne.frame_symbols) return - call decode_waveform(tones,int(nsymbols)) - call expect(npending.eq.1,'RTTY serial text produces one update',count) - if(npending.eq.1) then - call expect(trim(normalized(pending_updates(1)%decoded)).eq.'599 123' .and. & - pending_updates(1)%complete .and. nactive.eq.0, & - 'RTTY serial text uses canonical rendering and completes',count) - endif + call expect_noiseless_message(tones,int(nsymbols),'599 123','RTTY serial text',count) end subroutine decode_profile_text subroutine decode_compact_text(count) @@ -93,29 +88,21 @@ contains integer(c_int) :: native_tones(MAX_FRAMES*frame_symbols),native_nsymbols,status character(kind=c_char) :: c_text(80) character(len=80) :: text - integer :: tones(MAX_FRAMES*frame_symbols),nsymbols,chained,i - - do chained=0,1 - status=jtty_cpp_cq_smoke(native_tones,native_nsymbols,c_text,int(chained,c_int)) - call expect(status.eq.JTTY_ENCODE_OK .and. native_nsymbols.eq.frame_symbols, & - 'native F1 generates one frame',count) - if(status.ne.JTTY_ENCODE_OK .or. native_nsymbols.ne.frame_symbols) return - do i=1,len(text) - text(i:i)=c_text(i) - enddo - call genjtty(text,tones,nsymbols) - call expect(nsymbols.eq.native_nsymbols,'GUI CQ text generates one frame',count) - if(nsymbols.ne.native_nsymbols) return - call expect(all(tones(1:nsymbols).eq.native_tones(1:nsymbols)), & - 'GUI CQ text and native F1 generate identical channel symbols',count) + integer :: tones(MAX_FRAMES*frame_symbols),nsymbols,i + + status=jtty_cpp_cq_smoke(native_tones,native_nsymbols,c_text) + call expect(status.eq.JTTY_ENCODE_OK .and. native_nsymbols.eq.frame_symbols, & + 'native F1 generates one frame',count) + if(status.ne.JTTY_ENCODE_OK .or. native_nsymbols.ne.frame_symbols) return + do i=1,len(text) + text(i:i)=c_text(i) enddo - call decode_waveform(tones,nsymbols) - call expect(npending.eq.1,'compact CQ produces one update',count) - if(npending.eq.1) then - call expect(trim(normalized(pending_updates(1)%decoded)).eq.'CQ K1ABC CQ' .and. & - pending_updates(1)%complete .and. nactive.eq.0, & - 'compact CQ preserves text and completes',count) - endif + call genjtty(text,tones,nsymbols) + call expect(nsymbols.eq.native_nsymbols,'GUI CQ text generates one frame',count) + if(nsymbols.ne.native_nsymbols) return + call expect(all(tones(1:nsymbols).eq.native_tones(1:nsymbols)), & + 'GUI CQ text and native F1 generate identical channel symbols',count) + call expect_noiseless_message(native_tones,int(native_nsymbols),'CQ K1ABC CQ','compact CQ',count) text='TEST WB9XYZ 599 123 QSL TU' call genjtty(text,tones,nsymbols) @@ -159,20 +146,12 @@ contains 'native call plus serial generates two frames',count) if(nsymbols.le.0) return - call decode_waveform(tones,nsymbols) - - call expect(npending.eq.1, & - 'native call plus serial produces one update',count) - if(npending.ne.1) return - call expect(trim(normalized(pending_updates(1)%decoded)).eq.'WB9XYZ 599 1234', & - 'merged native atoms use canonical call and serial rendering',count) - call expect(pending_updates(1)%complete .and. nactive.eq.0, & - 'final native atom completes and releases the message',count) + call expect_noiseless_message(tones,nsymbols,'WB9XYZ 599 1234','native call plus serial',count) end subroutine decode_native_call_and_serial subroutine decode_c_adapter_atoms(count) integer, intent(inout) :: count - type(jtty_source_atom_c) :: atoms(6) + type(jtty_source_atom_c) :: atoms(7) integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols,status call expect(c_sizeof(atoms(1)).eq.20,'C atom descriptor remains 20 bytes',count) @@ -183,27 +162,25 @@ contains JTTY_ROLE_FULL,0,'CA') call initialize_c_atom(atoms(4),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION, & 3,1,'EMA') - call initialize_c_atom(atoms(5),JTTY_ATOM_GRID4,0,JTTY_ROLE_FIELD_ONLY,0,'FN42') - call initialize_c_atom(atoms(6),JTTY_ATOM_CONTROL,JTTY_CONTROL_QSL_TU,0,0,'') + call initialize_c_atom(atoms(5),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,10,'CT') + atoms(5)%text(3)=' ' + call initialize_c_atom(atoms(6),JTTY_ATOM_GRID4,0,JTTY_ROLE_FIELD_ONLY,0,'FN42') + call initialize_c_atom(atoms(7),JTTY_ATOM_CONTROL,JTTY_CONTROL_QSL_TU,0,0,'') call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) call expect(nsymbols.eq.size(atoms)*frame_symbols, & 'C adapter generates serial/state/FD/grid/control frames',count) call expect(status.eq.JTTY_ENCODE_OK,'C adapter reports successful encoding',count) if(nsymbols.le.0) return - call decode_waveform(tones,int(nsymbols)) - call expect(npending.eq.1,'C adapter atoms produce one update',count) - if(npending.ne.1) return - call expect(trim(normalized(pending_updates(1)%decoded)).eq. & - 'K1ABC 599 012 599 CA 1D EMA FN42 QSL TU', & - 'C adapter atoms retain canonical structured rendering',count) - call expect(pending_updates(1)%complete .and. nactive.eq.0, & - 'final C adapter atom completes and releases the message',count) + call expect_noiseless_message(tones,int(nsymbols), & + 'K1ABC 599 012 599 CA 1D EMA 10A CT FN42 QSL TU','C adapter atoms',count) end subroutine decode_c_adapter_atoms subroutine reject_invalid_c_descriptors(count) integer, intent(inout) :: count type(jtty_source_atom_c) :: atom(1) + character(len=4), parameter :: invalid_sections(*)=['ZZZ ','EMAX','CT X'] + integer :: i integer(c_int) :: tones(frame_symbols),nsymbols,status call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_LOC,JTTY_LOC_STATE_PROVINCE,1,0,'CA') @@ -218,11 +195,13 @@ contains call genjtty_atoms_c(atom,1,tones,nsymbols,status) call expect(nsymbols.eq.0,'C adapter rejects unterminated text',count) - call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,'ZZZ') - call genjtty_atoms_c(atom,1,tones,nsymbols,status) - call expect(nsymbols.eq.0,'C adapter rejects unknown Field Day section',count) - call expect(status.eq.JTTY_ENCODE_UNKNOWN_SECTION, & - 'C adapter identifies unknown Field Day section',count) + do i=1,size(invalid_sections) + call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,invalid_sections(i)) + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects unknown Field Day section '//trim(invalid_sections(i)),count) + call expect(status.eq.JTTY_ENCODE_UNKNOWN_SECTION, & + 'C adapter identifies unknown Field Day section '//trim(invalid_sections(i)),count) + enddo call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,0,0,1,'EMA') call genjtty_atoms_c(atom,1,tones,nsymbols,status) @@ -237,6 +216,29 @@ contains call expect(nsymbols.eq.0,'C adapter rejects unassigned control phrase',count) end subroutine reject_invalid_c_descriptors + subroutine reject_invalid_c_batch(count) + integer, intent(inout) :: count + type(jtty_source_atom_c) :: atoms(3) + integer(c_int) :: tones(3*frame_symbols),nsymbols,status + + call initialize_c_atom(atoms(1),JTTY_ATOM_CALL,JTTY_CALL_CALL,0,0,'K1ABC') + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,'EMAX') + call initialize_c_atom(atoms(3),JTTY_ATOM_CONTROL,JTTY_CONTROL_QSL_TU,0,0,'') + call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) + call expect(nsymbols.eq.0 .and. status.eq.JTTY_ENCODE_UNKNOWN_SECTION, & + 'invalid section rejects the whole descriptor batch',count) + + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_NUM,JTTY_NUM_SERIAL,JTTY_ROLE_FULL,131072,'') + call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) + call expect(nsymbols.eq.0 .and. status.eq.JTTY_ENCODE_INVALID_DESCRIPTOR, & + 'invalid source atom rejects the whole descriptor batch',count) + + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,'EMA') + call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) + call expect(nsymbols.eq.size(atoms)*frame_symbols .and. status.eq.JTTY_ENCODE_OK, & + 'valid descriptor batch encodes after a rejected batch',count) + end subroutine reject_invalid_c_batch + subroutine initialize_c_atom(atom,kind,subtype,role,value,text) type(jtty_source_atom_c), intent(out) :: atom integer, intent(in) :: kind,subtype,role,value @@ -280,6 +282,45 @@ contains 'CRC/FEC-valid source-invalid frame creates no message or update',count) end subroutine reject_reserved_struct_family + subroutine expect_noiseless_message(tones,nsymbols,expected,description,count) + integer, intent(in) :: tones(:),nsymbols + character(len=*), intent(in) :: expected,description + integer, intent(inout) :: count + complex(real32) :: correlations(0:3,TOTAL_K),halves(0:3,TOTAL_K) + integer(int32) :: payload(PAYLOAD_BITS) + character(len=34) :: frames(MAX_FRAMES) + character(len=80) :: decoded + integer :: iframe,nframes,offset,symbol + logical :: success,source_valid,is_last_frame + + nframes=nsymbols/frame_symbols + call expect(nframes.ge.1 .and. nframes.le.MAX_FRAMES .and. & + nsymbols.eq.nframes*frame_symbols,description//': complete channel frames',count) + if(nframes.lt.1 .or. nframes.gt.MAX_FRAMES .or. nsymbols.ne.nframes*frame_symbols) return + frames='' + halves=cmplx(0.0_real32,0.0_real32,real32) + do iframe=1,nframes + offset=(iframe-1)*frame_symbols + call expect(all(tones(offset+1:offset+size(is13)).eq.is13),description//': sync symbols',count) + offset=offset+size(is13) + call expect(all(tones(offset+1:offset+TOTAL_K).ge.0) .and. & + all(tones(offset+1:offset+TOTAL_K).le.3),description//': payload tones',count) + if(any(tones(offset+1:offset+TOTAL_K).lt.0) .or. any(tones(offset+1:offset+TOTAL_K).gt.3)) return + correlations=cmplx(0.0_real32,0.0_real32,real32) + do symbol=1,TOTAL_K + correlations(tones(offset+symbol),symbol)=cmplx(100.0_real32,0.0_real32,real32) + enddo + call jtty_tbcc_decode(correlations,halves,payload,success) + call expect(success,description//': TBCC payload recovery',count) + if(.not.success) return + write(frames(iframe),'(34i1)') payload + call unpack_jtty(frames,iframe,decoded,is_last_frame=is_last_frame,source_valid=source_valid) + call expect(source_valid,description//': source-valid prefix',count) + call expect(is_last_frame.eqv.(iframe.eq.nframes),description//': final-frame marker',count) + enddo + call expect(trim(normalized(decoded)).eq.expected,description//': canonical text and ordering',count) + end subroutine expect_noiseless_message + subroutine decode_waveform(tones,nsymbols,channel_width) integer, intent(in) :: tones(:),nsymbols real, intent(in), optional :: channel_width diff --git a/tests/unit/jtty/test_jtty_tbcc_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 index 50fb6f63..09d5f032 100644 --- a/tests/unit/jtty/test_jtty_tbcc_decoder.f90 +++ b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 @@ -32,6 +32,7 @@ program test_jtty_tbcc_decoder 'rank-one payload unexpectedly evaluated half-symbol fallback') call require(result%exported_candidate_count <= 4_int32, & 'coherence ladder exposed more than four hypotheses per rung') + call expect_decode_symmetry() payload(33) = 1_int32 call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) @@ -41,6 +42,7 @@ program test_jtty_tbcc_decoder call require(.not.success, 'coherence ladder accepted reserved bit one') call require(all(decoded == 0_int32), & 'reserved-bit rejection left a stale payload') + call expect_failure_result() halves = correlations correlations = cmplx(0.0_real32, 0.0_real32, real32) @@ -49,6 +51,7 @@ program test_jtty_tbcc_decoder call require(.not.success, 'half-symbol fallback accepted reserved bit one') call require(all(decoded == 0_int32), & 'half-symbol reserved-bit rejection left a stale payload') + call expect_failure_result() payload(33) = 0_int32 call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) @@ -68,16 +71,14 @@ program test_jtty_tbcc_decoder call jtty_tbcc_decode(correlations, halves, decoded, success, result) call require(.not.success, 'coherence ladder accepted the all-zero payload') call require(all(decoded == 0_int32), 'failed ladder decode left stale payload') - call require(result%evaluated_rung_count == 4_int32, & - 'failed decode did not report all evaluated rungs') + call expect_failure_result() correlations = cmplx(0.0_real32, 0.0_real32, real32) decoded = huge(0_int32) call jtty_tbcc_decode(correlations, halves, decoded, success, result) call require(.not.success, 'coherence ladder accepted flat correlations') call require(all(decoded == 0_int32), 'flat-correlation decode left stale payload') - call require(result%evaluated_rung_count == 4_int32, & - 'flat-correlation decode did not report all evaluated rungs') + call expect_failure_result() call expect_coherent_decodes() @@ -85,6 +86,54 @@ program test_jtty_tbcc_decoder contains + subroutine expect_decode_symmetry() + complex(real32) :: transformed(0:3, TOTAL_K) + integer(int32) :: transformed_payload(PAYLOAD_BITS) + type(jtty_tbcc_decode_result) :: baseline, transformed_result + logical :: transformed_success + + baseline = result + transformed = -correlations + call jtty_tbcc_decode(transformed, halves, transformed_payload, transformed_success, transformed_result) + call require(transformed_success .and. all(transformed_payload == payload), & + 'negated correlations changed the decode outcome') + call require(transformed_result%accepted_hypothesis_rank == baseline%accepted_hypothesis_rank .and. & + transformed_result%accepted_identity == baseline%accepted_identity .and. & + transformed_result%exported_candidate_count == baseline%exported_candidate_count .and. & + transformed_result%circular_candidate_count == baseline%circular_candidate_count .and. & + transformed_result%coherent_block_length == baseline%coherent_block_length .and. & + transformed_result%evaluated_rung_count == baseline%evaluated_rung_count, & + 'negated correlations changed the accepted hypothesis') + + transformed = 2.0_real32*correlations + call jtty_tbcc_decode(transformed, halves, transformed_payload, transformed_success, transformed_result) + call require(transformed_success .and. all(transformed_payload == payload), & + 'doubled correlations changed the decode outcome') + call require(transformed_result%accepted_hypothesis_rank == baseline%accepted_hypothesis_rank .and. & + transformed_result%accepted_identity == baseline%accepted_identity .and. & + transformed_result%exported_candidate_count == baseline%exported_candidate_count .and. & + transformed_result%circular_candidate_count == baseline%circular_candidate_count .and. & + transformed_result%coherent_block_length == baseline%coherent_block_length .and. & + transformed_result%evaluated_rung_count == baseline%evaluated_rung_count, & + 'doubled correlations changed the accepted hypothesis') + end subroutine expect_decode_symmetry + + subroutine expect_failure_result() + type(jtty_tbcc_decode_result) :: empty + + empty = jtty_tbcc_decode_result() + call require(result%accepted_hypothesis_rank == empty%accepted_hypothesis_rank .and. & + result%exported_candidate_count == empty%exported_candidate_count .and. & + result%circular_candidate_count == empty%circular_candidate_count .and. & + result%coherent_block_length == empty%coherent_block_length .and. & + result%accepted_identity == empty%accepted_identity .and. & + result%accepted_metric == empty%accepted_metric .and. & + (result%used_half_symbol_observation .eqv. empty%used_half_symbol_observation), & + 'failed decode left stale result metadata') + call require(result%evaluated_rung_count == 4_int32, & + 'failed decode did not report all evaluated rungs') + end subroutine expect_failure_result + subroutine expect_coherent_decodes() ! Seed 6 verifies that reserved-bit pruning retains the valid L1 path. integer(int32), parameter :: seeds(2) = [2,6], lengths(2) = [2,1], & diff --git a/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 index d8b4eed7..545e0221 100644 --- a/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 +++ b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 @@ -9,7 +9,10 @@ program test_jtty_tbcc_list_decoder call expect_optimized_reference_parity() call expect_noiseless_tailbiting_decode() call expect_reserved_bit_pruning() + call expect_candidate_contract() + call expect_workspace_isolation() call expect_deterministic_hypothesis_budget() + call expect_score_symmetry() call expect_coherent_normalization() print *, 'test_jtty_tbcc_list_decoder: all checks passed' @@ -24,14 +27,7 @@ contains complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) integer(int32) :: coherent_index, width_index, symbol, tone, wraps - do symbol = 1, JTTY_TBCC_INFORMATION_BITS - do tone = 0, 3 - correlations(tone, symbol) = cmplx( & - real(modulo(17*tone + 11*symbol, 29) - 14, real32)/8.0_real32, & - real(modulo(7*tone + 19*symbol, 31) - 15, real32)/9.0_real32, & - real32) - end do - end do + call make_pattern_correlations(correlations) do wraps = 1, 2 do coherent_index = 1, size(coherent_lengths) @@ -189,6 +185,80 @@ contains end if end subroutine expect_reserved_bit_pruning + subroutine expect_candidate_contract() + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bits(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states(JTTY_TBCC_MAX_HYPOTHESES), count, pool, rank, earlier + integer(int32) :: encoded(2, JTTY_TBCC_INFORMATION_BITS) + integer(int64) :: ids(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean(JTTY_TBCC_MAX_HYPOTHESES), paths(JTTY_TBCC_MAX_HYPOTHESES), rescored + logical :: crc(JTTY_TBCC_MAX_HYPOTHESES), closed, expected_crc + + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits, ids, clean, paths, states, crc, count, pool, prune_reserved_zero=.true.) + if (count /= JTTY_TBCC_MAX_HYPOTHESES .or. pool < count) & + error stop 'TBCC candidate contract fixture did not export four candidates' + + do rank = 1, count + if (any(bits(:, rank) < 0_int32) .or. any(bits(:, rank) > 1_int32)) & + error stop 'TBCC candidate contains a nonbinary bit' + if (bits(JTTY_TBCC_RESERVED_BIT, rank) /= 0_int32) & + error stop 'TBCC candidate retained a reserved bit' + if (ids(rank) /= jtty_tbcc_candidate_identity(bits(:, rank))) & + error stop 'TBCC candidate identity disagrees with its bits' + if (states(rank) /= jtty_tbcc_tailbiting_state(JTTY_TBCC_PROFILE_1167_1545_80F, bits(:, rank))) & + error stop 'TBCC candidate start state disagrees with its bits' + call encode_crc12(bits(1:34, rank), encoded, JTTY_TBCC_PROFILE_1167_1545_80F) + expected_crc = all(encoded(1, :) == bits(:, rank)) + if (crc(rank) .neqv. expected_crc) error stop 'TBCC candidate CRC status disagrees with encoding' + call jtty_tbcc_score_candidate(JTTY_TBCC_PROFILE_1167_1545_80F, correlations, & + 2_int32, bits(:, rank), rescored, closed) + if (.not.closed .or. .not.real_arrays_agree([rescored], [clean(rank)])) & + error stop 'TBCC candidate clean score or closure disagrees with rescore' + do earlier = 1, rank - 1 + if (ids(rank) == ids(earlier)) error stop 'TBCC candidate identity is duplicated' + end do + if (rank == 1) cycle + if (clean(rank) > clean(rank - 1)) error stop 'TBCC candidate clean scores are not descending' + if (clean(rank) == clean(rank - 1) .and. ids(rank) < ids(rank - 1)) & + error stop 'TBCC tied candidate identities are not ascending' + end do + end subroutine expect_candidate_contract + + subroutine expect_workspace_isolation() + type(jtty_tbcc_decoder_plan) :: plan + type(jtty_tbcc_decoder_workspace) :: workspace + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bits_a(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: bits_b(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states_a(JTTY_TBCC_MAX_HYPOTHESES), states_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: count_a, count_b, pool_a, pool_b + integer(int64) :: ids_a(JTTY_TBCC_MAX_HYPOTHESES), ids_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean_a(JTTY_TBCC_MAX_HYPOTHESES), clean_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: paths_a(JTTY_TBCC_MAX_HYPOTHESES), paths_b(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_a(JTTY_TBCC_MAX_HYPOTHESES), crc_b(JTTY_TBCC_MAX_HYPOTHESES) + + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + bits_a, ids_a, clean_a, paths_a, states_a, crc_a, count_a, pool_a, prune_reserved_zero=.true.) + correlations = cmplx(0.0_real32, 0.0_real32, real32) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.false.) + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.true.) + if (count_a /= count_b .or. pool_a /= pool_b .or. any(bits_a /= bits_b) .or. & + any(ids_a /= ids_b) .or. any(states_a /= states_b) .or. & + .not.real_arrays_agree(clean_a, clean_b) .or. & + .not.real_arrays_agree(paths_a, paths_b) .or. any(crc_a .neqv. crc_b)) & + error stop 'TBCC workspace retained state across A-B-A decodes' + end subroutine expect_workspace_isolation + subroutine expect_deterministic_hypothesis_budget() type(jtty_tbcc_code_profile) :: code complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) @@ -233,8 +303,61 @@ contains one_count, one_pool, prune_reserved_zero=.true.) if (one_count /= 1_int32 .or. one_id(1) /= ids_a(1) .or. one_pool /= pool_a) & error stop 'TBCC list decoder did not enforce the H1 budget' + + ! The nonzero pool must exceed H4 so this checks the admission boundary. + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava(correlations, code, 2_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, bits_a, ids_a, clean_a, path_a, states_a, & + crc_a, count_a, pool_a, prune_reserved_zero=.true.) + call jtty_tbcc_list_wava(correlations, code, 2_int32, 4_int32, 2_int32, & + 1_int32, one_bit, one_id, one_clean, one_path, one_state, one_crc, & + one_count, one_pool, prune_reserved_zero=.true.) + if (count_a /= JTTY_TBCC_MAX_HYPOTHESES .or. pool_a <= count_a .or. & + one_count /= 1_int32 .or. one_pool /= pool_a) & + error stop 'TBCC nonzero H1/H4 fixture did not cross the hypothesis boundary' + if (any(one_bit(:, 1) /= bits_a(:, 1)) .or. one_id(1) /= ids_a(1) .or. & + one_state(1) /= states_a(1) .or. one_crc(1) .neqv. crc_a(1) .or. & + .not.real_arrays_agree(one_clean, clean_a(1:1)) .or. & + .not.real_arrays_agree(one_path, path_a(1:1))) & + error stop 'TBCC nonzero H1 differs from the first H4 candidate' end subroutine expect_deterministic_hypothesis_budget + subroutine expect_score_symmetry() + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bits_a(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: bits_b(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states_a(JTTY_TBCC_MAX_HYPOTHESES), states_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: count_a, count_b, pool_a, pool_b + integer(int64) :: ids_a(JTTY_TBCC_MAX_HYPOTHESES), ids_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean_a(JTTY_TBCC_MAX_HYPOTHESES), clean_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: paths_a(JTTY_TBCC_MAX_HYPOTHESES), paths_b(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_a(JTTY_TBCC_MAX_HYPOTHESES), crc_b(JTTY_TBCC_MAX_HYPOTHESES) + + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits_a, ids_a, clean_a, paths_a, states_a, crc_a, count_a, pool_a, prune_reserved_zero=.true.) + if (count_a /= JTTY_TBCC_MAX_HYPOTHESES) error stop 'TBCC symmetry fixture lacks four candidates' + if (any(clean_a(1:count_a-1) - clean_a(2:count_a) <= 1.0e-6_real64)) & + error stop 'TBCC symmetry fixture has near-tied clean scores' + correlations = -correlations + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.true.) + if (count_b /= count_a .or. pool_b /= pool_a .or. any(bits_b /= bits_a) .or. & + any(ids_b /= ids_a) .or. any(states_b /= states_a) .or. any(crc_b .neqv. crc_a) .or. & + .not.real_arrays_agree(clean_b, clean_a)) & + error stop 'TBCC candidate order or score changed under negation' + correlations = 2.0_real32*correlations + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.true.) + if (count_b /= count_a .or. pool_b /= pool_a .or. any(bits_b /= bits_a) .or. & + any(ids_b /= ids_a) .or. any(states_b /= states_a) .or. any(crc_b .neqv. crc_a) .or. & + .not.real_arrays_agree(clean_b, 4.0_real64*clean_a)) & + error stop 'TBCC candidate order or score changed under amplitude doubling' + end subroutine expect_score_symmetry + subroutine expect_coherent_normalization() complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) integer(int32) :: tones4(4), tones2(2) @@ -282,6 +405,19 @@ contains end do end subroutine make_noiseless_correlations + subroutine make_pattern_correlations(correlations) + complex(real32), intent(out) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: symbol, tone + + do symbol = 1, JTTY_TBCC_INFORMATION_BITS + do tone = 0, 3 + correlations(tone, symbol) = cmplx( & + real(modulo(17*tone + 11*symbol, 29) - 14, real32)/8.0_real32, & + real(modulo(7*tone + 19*symbol, 31) - 15, real32)/9.0_real32, real32) + end do + end do + end subroutine make_pattern_correlations + pure logical function real_arrays_agree(left, right) result(agree) real(real64), intent(in) :: left(:), right(:) integer(int32) :: element diff --git a/tests/unit/jtty/test_jtty_transmit_queue.cpp b/tests/unit/jtty/test_jtty_transmit_queue.cpp new file mode 100644 index 00000000..d9b734a6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_transmit_queue.cpp @@ -0,0 +1,107 @@ +#include + +#include "widgets/JttyTransmitQueue.hpp" + +class TestJttyTransmitQueue final + : public QObject +{ + Q_OBJECT + + static Jtty::TransmitSegment segment (QString const& text, int toneCount = 2) + { + return {text, QVector (toneCount, 1), 0}; + } + +private slots: + void fifoPreservesFullSegmentsAndLaterRequests () + { + Jtty::TransmitQueue queue; + auto const full = QString (79, 'A') + 'Z'; + queue.append (11, {segment (full), segment ("TAIL")}); + QCOMPARE (queue.nextRequestId (), qint64 {11}); + QCOMPARE (queue.nextSegment ()->text, full); + QVERIFY (queue.commitNext (3072)); + + queue.append (12, {segment ("NEW MESSAGE")}); + QCOMPARE (queue.nextRequestId (), qint64 {11}); + QCOMPARE (queue.nextSegment ()->text, QString {"TAIL"}); + QVERIFY (!queue.commitNext (6144)); + QCOMPARE (queue.nextRequestId (), qint64 {12}); + QCOMPARE (queue.nextSegment ()->text, QString {"NEW MESSAGE"}); + QVERIFY (queue.commitNext (9216)); + QVERIFY (!queue.hasUncommitted ()); + QVERIFY (!queue.nextSegment ()); + QCOMPARE (queue.nextRequestId (), qint64 {0}); + QCOMPARE (queue.requests ().at (0).segments.at (0).text, full); + } + + void progressDoesNotCompleteRequests () + { + Jtty::TransmitQueue queue; + queue.append (21, {segment ("FIRST"), segment ("LAST", 3)}); + QCOMPARE (queue.segmentCount (), 2); + QCOMPARE (queue.nextSegment ()->sampleCount (), qint64 {3072}); + QCOMPARE (queue.remainingSegments (0), 2); + QCOMPARE (queue.pendingText (0), QString {"FIRST\nLAST"}); + queue.commitNext (3072); + QCOMPARE (queue.remainingSegments (3071), 2); + QCOMPARE (queue.remainingSegments (3072), 1); + QCOMPARE (queue.pendingText (3072), QString {"LAST"}); + QVERIFY (queue.complete (3072).isEmpty ()); + QCOMPARE (queue.nextSegment ()->sampleCount (), qint64 {4608}); + queue.commitNext (7680); + QCOMPARE (queue.remainingSegments (7680), 0); + QVERIFY (queue.pendingText (7680).isEmpty ()); + QVERIFY (!queue.empty ()); + QCOMPARE (queue.segmentCount (), 2); + QVERIFY (queue.complete (7679).isEmpty ()); + QCOMPARE (queue.complete (7680), QVector {21}); + QVERIFY (queue.empty ()); + QVERIFY (queue.complete (7680).isEmpty ()); + } + + void drainCompletesOnlyCommittedPrefix () + { + Jtty::TransmitQueue queue; + queue.append (31, {segment ("FIRST")}); + queue.append (32, {segment ("SECOND"), segment ("THIRD")}); + queue.append (33, {segment ("FOURTH")}); + queue.commitNext (3072); + queue.commitNext (6144); + QCOMPARE (queue.complete (6144), QVector {31}); + QCOMPARE (queue.requests ().size (), 2); + QCOMPARE (queue.nextSegment ()->text, QString {"THIRD"}); + queue.commitNext (9216); + queue.commitNext (12288); + QCOMPARE (queue.complete (9216), QVector {32}); + QCOMPARE (queue.complete (12288), QVector {33}); + QVERIFY (queue.empty ()); + } + + void cancellationReportsAcceptedAndUnsubmittedOnce () + { + Jtty::TransmitQueue queue; + queue.append (41, {segment ("ACCEPTED")}); + queue.append (42, {segment ("PENDING"), segment ("UNSUBMITTED")}); + queue.append (43, {segment ("LATER")}); + queue.commitNext (3072); + queue.commitNext (6144); + auto const cancelled = queue.cancel (); + QCOMPARE (cancelled, (QVector {41, 42, 43})); + QVERIFY (queue.empty ()); + QVERIFY (!queue.hasUncommitted ()); + QCOMPARE (queue.segmentCount (), 0); + QCOMPARE (queue.remainingSegments (0), 0); + QVERIFY (queue.pendingText (0).isEmpty ()); + QVERIFY (queue.cancel ().isEmpty ()); + QVERIFY (queue.complete (6144).isEmpty ()); + queue.append (44, {segment ("FRESH")}); + QCOMPARE (queue.nextSegment ()->text, QString {"FRESH"}); + QVERIFY (queue.commitNext (3072)); + QCOMPARE (queue.complete (3072), QVector {44}); + } +}; + +QTEST_GUILESS_MAIN (TestJttyTransmitQueue) + +#include "test_jtty_transmit_queue.moc" diff --git a/tests/unit/jtty/test_jtty_tx_lifecycle.cpp b/tests/unit/jtty/test_jtty_tx_lifecycle.cpp new file mode 100644 index 00000000..d133f9f6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tx_lifecycle.cpp @@ -0,0 +1,186 @@ +#include + +#include + +#include "widgets/JttyTxLifecycle.hpp" + +class TestJttyTxLifecycle final : public QObject +{ + Q_OBJECT + +private slots: + void pendingSessionRetainsBackendIdentity () + { + JttyTxLifecycle lifecycle; + auto const epoch = TxAudioQueueEpoch {7}; + + QVERIFY (lifecycle.begin (JttyTxLifecycle::Backend::Tci, epoch)); + QVERIFY (lifecycle.addPending (101, 201)); + + QCOMPARE (lifecycle.phase (), JttyTxLifecycle::Phase::AwaitingEnqueue); + QCOMPARE (lifecycle.backend (), JttyTxLifecycle::Backend::Tci); + QCOMPARE (lifecycle.epoch (), epoch); + QCOMPARE (lifecycle.pending ().size (), std::size_t {1}); + QCOMPARE (lifecycle.pending ().front ().request_id, 201); + } + + void stopSnapshotIsImmutable () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Local); + QVERIFY (epoch.isValid ()); + QVERIFY (lifecycle.addPending (1, 2)); + TxAudioQueueProgress progress; + progress.epoch = epoch; + progress.queued_samples = 3600; + progress.served_samples = 1200; + progress.total_samples = 4800; + auto const accepted = lifecycle.accept (epoch, 1, progress); + QVERIFY (accepted.pending.has_value ()); + QVERIFY (lifecycle.markTransmitting ()); + + auto const first = lifecycle.beginStop (); + QVERIFY (first.has_value ()); + QCOMPARE (first->backend, JttyTxLifecycle::Backend::Local); + QCOMPARE (first->epoch, epoch); + QCOMPARE (first->progress.queued_samples, 3600); + QCOMPARE (first->progress.served_samples, 1200); + QCOMPARE (first->progress.total_samples, 4800); + + QVERIFY (!lifecycle.begin (JttyTxLifecycle::Backend::Tci, + TxAudioQueueEpoch {99})); + QVERIFY (!lifecycle.addPending (3, 4)); + QVERIFY (!lifecycle.accept (epoch, 3, 9600).pending.has_value ()); + + auto const repeated = lifecycle.beginStop (); + QVERIFY (repeated.has_value ()); + QCOMPARE (repeated->backend, first->backend); + QCOMPARE (repeated->epoch, first->epoch); + QCOMPARE (repeated->progress.total_samples, first->progress.total_samples); + } + + void acceptanceAdvancingTotalDiscardsDeferredDrain () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 10)); + + QVERIFY (!lifecycle.observeDrain (epoch, 0).has_value ()); + QVERIFY (lifecycle.deferredDrain ().has_value ()); + + auto const accepted = lifecycle.accept (epoch, 1, 2400); + QVERIFY (accepted.pending.has_value ()); + QVERIFY (!accepted.drain.has_value ()); + QVERIFY (!lifecycle.deferredDrain ().has_value ()); + QCOMPARE (lifecycle.committedTotal (), 2400); + } + + void finalFailureReleasesMatchingDeferredDrain () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 10)); + QVERIFY (lifecycle.addPending (2, 20)); + + QVERIFY (!lifecycle.observeDrain (epoch, 0).has_value ()); + auto const first = lifecycle.fail (epoch, 1); + QVERIFY (first.pending.has_value ()); + QVERIFY (!first.drain.has_value ()); + + auto const last = lifecycle.fail (epoch, 2); + QVERIFY (last.pending.has_value ()); + QVERIFY (last.drain.has_value ()); + QCOMPARE (last.drain->epoch, epoch); + QCOMPARE (last.drain->total, 0); + } + + void rigCloseCanRejectEveryPendingRequestBeforeAcceptance () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 11)); + QVERIFY (lifecycle.addPending (2, 22)); + + auto const failed = lifecycle.failAll (); + QCOMPARE (failed.pending.size (), std::size_t {2}); + QCOMPARE (failed.pending.at (0).request_id, 11); + QCOMPARE (failed.pending.at (1).request_id, 22); + QVERIFY (!lifecycle.hasPending ()); + + auto const stop = lifecycle.beginStop (); + QVERIFY (stop.has_value ()); + QCOMPARE (stop->backend, JttyTxLifecycle::Backend::Tci); + QVERIFY (!lifecycle.accept (epoch, 1, 100).pending.has_value ()); + } + + void localStopCanRejectPendingAfterSnapshot () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 11)); + + auto const stop = lifecycle.beginStop (); + QVERIFY (stop.has_value ()); + QVERIFY (!lifecycle.fail (epoch, 1).pending.has_value ()); + + auto const failed = lifecycle.failAll (); + QCOMPARE (failed.pending.size (), std::size_t {1}); + QCOMPARE (failed.pending.front ().request_id, 11); + QVERIFY (!failed.drain.has_value ()); + } + + void preacceptanceTimeoutIsConfigurableAndStartsWithFirstPending () + { + using namespace std::chrono_literals; + + JttyTxLifecycle lifecycle {25ms}; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Local); + auto const start = JttyTxLifecycle::TimePoint {1s}; + + QVERIFY (!lifecycle.preacceptanceDeadline ().has_value ()); + QVERIFY (lifecycle.addPending (1, 1, start)); + QCOMPARE (lifecycle.preacceptanceTimeout (), 25ms); + QCOMPARE (*lifecycle.preacceptanceDeadline (), start + 25ms); + QVERIFY (!lifecycle.preacceptanceTimedOut (start + 24ms)); + QVERIFY (lifecycle.preacceptanceTimedOut (start + 25ms)); + + QVERIFY (lifecycle.addPending (2, 2, start + 20ms)); + QCOMPARE (*lifecycle.preacceptanceDeadline (), start + 25ms); + QVERIFY (lifecycle.accept (epoch, 1, 10).pending.has_value ()); + QVERIFY (lifecycle.preacceptanceDeadline ().has_value ()); + QVERIFY (lifecycle.fail (epoch, 2).pending.has_value ()); + QVERIFY (!lifecycle.preacceptanceDeadline ().has_value ()); + } + + void resetRequiresBackendStopRouting () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Local); + QVERIFY (lifecycle.addPending (1, 1)); + QVERIFY (lifecycle.accept (epoch, 1, 10).pending.has_value ()); + + auto const stop = lifecycle.beginStop (); + QVERIFY (stop.has_value ()); + QVERIFY (!lifecycle.reset ()); + QCOMPARE (lifecycle.phase (), JttyTxLifecycle::Phase::Stopping); + QCOMPARE (lifecycle.backend (), JttyTxLifecycle::Backend::Local); + + auto wrong = *stop; + wrong.backend = JttyTxLifecycle::Backend::Tci; + QVERIFY (!lifecycle.markBackendStopRouted (wrong)); + QVERIFY (!lifecycle.reset ()); + + QVERIFY (lifecycle.markBackendStopRouted (*stop)); + QVERIFY (lifecycle.reset ()); + QCOMPARE (lifecycle.phase (), JttyTxLifecycle::Phase::Idle); + QCOMPARE (lifecycle.backend (), JttyTxLifecycle::Backend::None); + QVERIFY (!lifecycle.accept (epoch, 1, 10).pending.has_value ()); + + auto const next = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QCOMPARE (next.value (), epoch.value () + 1); + } +}; + +QTEST_GUILESS_MAIN (TestJttyTxLifecycle) + +#include "test_jtty_tx_lifecycle.moc" diff --git a/tests/unit/jtty/test_jtty_txstream.cpp b/tests/unit/jtty/test_jtty_txstream.cpp index d71be2a6..0ad89db5 100644 --- a/tests/unit/jtty/test_jtty_txstream.cpp +++ b/tests/unit/jtty/test_jtty_txstream.cpp @@ -1,9 +1,13 @@ #include +#include #include #include #include #include +#include +#include + #include "Audio/AudioDevice.hpp" #include "Audio/TxAudioQueue.hpp" #include "Audio/TxIdentity.hpp" @@ -26,10 +30,12 @@ private slots: void gaplessConcatAndSilencePad (); void clearResetsCounters (); void clearThenEnqueueSkipsOldSamples (); + void resetMustBeAppliedBeforeReusingCapacity (); void clearDuringPartialPlaybackSkipsRemainder (); void pendingResetProgressExcludesAbortedAudio (); void fifoOverflowRejectsWithoutTruncating (); void fifoWrappedEnqueuePreservesOrder (); + void concurrentChainedEnqueueAndPullPreservesOrder (); void enqueueFitPredicate (); void fifoDrainStateCarriesEpochAndTotal (); void fifoDrainAfterResetUsesNewEpochAndTotal (); @@ -37,10 +43,18 @@ private slots: void drainedPredicate (); void readDoesNotEmitDrainedDirectly (); void timerEmitsDrainedEdge (); + void progressTracksConsumptionAppendAndReset (); + void progressPrecedesDrainAfterRefill (); + void stopAppliesPendingResetAndAcknowledges (); + void stopPreservesNewEpochSamples (); void drainedEmittedFromWorkerThread (); void sourceCommitUsesCurrentRealExtent (); void staleQueueEpochDoesNotStart (); void sourceCommitIsEmittedOncePerStart (); + void queuedClearAndEnqueueAcknowledgeReplacement (); + void queuedEnqueueReportsTypedFailures (); + void pendingPayloadBudgetSurvivesAbort (); + void pendingRequestBudgetRecoversAfterDelivery (); }; namespace @@ -77,11 +91,20 @@ namespace for (int i = 0; i < n; ++i) out.append (p[i]); return out; } + + QByteArray pcmBytes (QVector const& samples) + { + return QByteArray {reinterpret_cast (samples.constData ()), + samples.size () * int (sizeof (qint16))}; + } } void TestJttyTxStream::initTestCase () { qRegisterMetaType ("TxAudioQueueDrainState"); + qRegisterMetaType ( + "TxAudioQueueEnqueueFailure"); + qRegisterMetaType ("TxAudioQueueProgress"); } void TestJttyTxStream::gaplessConcatAndSilencePad () @@ -146,6 +169,25 @@ void TestJttyTxStream::clearThenEnqueueSkipsOldSamples () QCOMPARE (fifo.servedReal (), qint64 (2)); } +void TestJttyTxStream::resetMustBeAppliedBeforeReusingCapacity () +{ + JttyPcmFifo fifo {8}; + QVERIFY (fifo.enqueue (QVector {1, 2, 3, 4, 5, 6, 7}, 1)); + fifo.clear (2); + QVERIFY (!fifo.enqueue (QVector {8, 9}, 2)); + + fifo.applyPendingReset (); + QVERIFY (fifo.enqueue (QVector {8, 9}, 2)); + + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.queuedReal (), qint64 (2)); + + QCOMPARE (fifo.pullSample (2), qint16 (8)); + QCOMPARE (fifo.pullSample (2), qint16 (9)); + QCOMPARE (fifo.pullSample (2), qint16 (0)); + QCOMPARE (fifo.servedReal (), qint64 (2)); +} + void TestJttyTxStream::clearDuringPartialPlaybackSkipsRemainder () { JttyPcmFifo fifo {16}; @@ -213,6 +255,48 @@ void TestJttyTxStream::fifoWrappedEnqueuePreservesOrder () QCOMPARE (fifo.servedReal (), qint64 (7)); } +void TestJttyTxStream::concurrentChainedEnqueueAndPullPreservesOrder () +{ + constexpr int sampleCount = 5000; + constexpr int chunkSize = 17; + JttyPcmFifo fifo {64}; + QVector received; + received.reserve (sampleCount); + std::atomic producerDone {false}; + + std::thread producer {[&fifo, &producerDone] { + for (int first = 1; first <= sampleCount; first += chunkSize) + { + QVector chunk; + int const last = qMin (first + chunkSize, sampleCount + 1); + chunk.reserve (last - first); + for (int sample = first; sample < last; ++sample) + { + chunk.append (qint16 (sample)); + } + while (!fifo.enqueue (chunk, 1)) + { + std::this_thread::yield (); + } + } + producerDone.store (true, std::memory_order_release); + }}; + + while (!producerDone.load (std::memory_order_acquire) + || received.size () < sampleCount) + { + qint16 const sample = fifo.pullSample (64); + if (sample != 0) received.append (sample); + } + producer.join (); + + QCOMPARE (received.size (), sampleCount); + for (int i = 0; i < received.size (); ++i) + { + QCOMPARE (received.at (i), qint16 (i + 1)); + } +} + void TestJttyTxStream::enqueueFitPredicate () { QVERIFY (jttyPcmEnqueueFits (4, 0, 4)); @@ -308,10 +392,146 @@ void TestJttyTxStream::readDoesNotEmitDrainedDirectly () JttyTxStream s {queue}; QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); QSignalSpy spy (&s, &JttyTxStream::drained); + QSignalSpy progressSpy (&s, &JttyTxStream::progress); QVERIFY (queue.enqueue (QVector {7, 7, 7}, epoch).accepted); (void) readFrames (s, 3 + DEFAULT_GUARD); QCOMPARE (spy.count (), 0); + QCOMPARE (progressSpy.count (), 0); +} + +void TestJttyTxStream::progressTracksConsumptionAppendAndReset () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (35); + queue.clear (epoch); + JttyTxStream stream {queue}; + QSignalSpy spy (&stream, &JttyTxStream::progress); + QVERIFY (queue.enqueue (QVector {1, 2, 3}, epoch).accepted); + stream.start (jttyRequest (35, 1), nullptr); + + QTRY_COMPARE (spy.count (), 1); + auto current = qvariant_cast (spy.last ().at (0)); + QCOMPARE (current.epoch, epoch); + QCOMPARE (current.served_samples, qint64 (0)); + QCOMPARE (current.total_samples, qint64 (3)); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 1); + + QCOMPARE (readFrames (stream, 2), (QVector {1, 2})); + QCOMPARE (spy.count (), 1); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 2); + current = qvariant_cast (spy.last ().at (0)); + QCOMPARE (current.served_samples, qint64 (2)); + QCOMPARE (current.queued_samples, qint64 (1)); + + QVERIFY (queue.enqueue (QVector {4, 5}, epoch).accepted); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 3); + current = qvariant_cast (spy.last ().at (0)); + QCOMPARE (current.epoch, epoch); + QCOMPARE (current.served_samples, qint64 (2)); + QCOMPARE (current.total_samples, qint64 (5)); + + auto const nextEpoch = queueEpoch (36); + queue.clear (nextEpoch); + QVERIFY (queue.enqueue (QVector {6}, nextEpoch).accepted); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 4); + current = qvariant_cast (spy.last ().at (0)); + QCOMPARE (current.epoch, nextEpoch); + QCOMPARE (current.served_samples, qint64 (0)); + QCOMPARE (current.total_samples, qint64 (1)); + QCOMPARE (current.queued_samples, qint64 (1)); + + queue.clear (TxAudioQueueEpoch::invalid ()); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 4); + stream.stop (); + queue.clear (queueEpoch (37)); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 4); +} + +void TestJttyTxStream::progressPrecedesDrainAfterRefill () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (38); + queue.clear (epoch); + JttyTxStream stream {queue}; + QSignalSpy drainedSpy (&stream, &JttyTxStream::drained); + QVERIFY (queue.enqueue (QVector {1, 2, 3}, epoch).accepted); + stream.start (jttyRequest (38, 1), nullptr); + bool appended {false}; + bool progressPrecededDrain {false}; + connect (&stream, &JttyTxStream::drained, &stream, + [&appended, &progressPrecededDrain] (TxAudioQueueDrainState) { + progressPrecededDrain = appended; + }); + connect (&stream, &JttyTxStream::progress, &stream, + [&queue, epoch, &appended] (TxAudioQueueProgress current) { + if (!appended && current.served_samples == current.total_samples) + { + appended = queue.enqueue (QVector {4, 5}, epoch).accepted; + } + }); + + (void) readFrames (stream, 3 + DEFAULT_GUARD); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QVERIFY (appended); + QVERIFY (progressPrecededDrain); + QCOMPARE (drainedSpy.count (), 1); + QCOMPARE (qvariant_cast ( + drainedSpy.first ().at (0)).total_at_drain, qint64 (3)); + QCOMPARE (readFrames (stream, 2), (QVector {4, 5})); + (void) readFrames (stream, DEFAULT_GUARD); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (drainedSpy.count (), 2); + QCOMPARE (qvariant_cast ( + drainedSpy.last ().at (0)).total_at_drain, qint64 (5)); + stream.stop (); +} + +void TestJttyTxStream::stopAppliesPendingResetAndAcknowledges () +{ + TxAudioQueue queue {8}; + auto const epoch = queueEpoch (39); + auto const nextEpoch = queueEpoch (40); + queue.clear (epoch); + JttyTxStream stream {queue}; + QSignalSpy stoppedSpy (&stream, &JttyTxStream::stopped); + QVERIFY (queue.enqueue (QVector {1, 2, 3, 4, 5, 6}, epoch).accepted); + + // Stop during PTT lead: no audio pull has applied either reset yet. + queue.clear (nextEpoch); + stream.stop (); + QCOMPARE (stoppedSpy.count (), 1); + QVERIFY (queue.enqueue (QVector {7, 8, 9, 10, 11, 12}, nextEpoch).accepted); + stream.start (jttyRequest (40, 1), nullptr); + QCOMPARE (readFrames (stream, 6), (QVector {7, 8, 9, 10, 11, 12})); + stream.stop (); + stream.stop (); + QCOMPARE (stoppedSpy.count (), 3); +} + +void TestJttyTxStream::stopPreservesNewEpochSamples () +{ + TxAudioQueue queue {8}; + auto const epoch = queueEpoch (42); + auto const nextEpoch = queueEpoch (43); + queue.clear (epoch); + JttyTxStream stream {queue}; + QVERIFY (queue.enqueue (QVector {1, 2, 3, 4, 5, 6}, epoch).accepted); + stream.start (jttyRequest (42, 1), nullptr); + queue.clear (nextEpoch); + QVERIFY (queue.enqueue (QVector {7, 8}, nextEpoch).accepted); + + stream.stop (); + QCOMPARE (queue.progress ().queued_samples, qint64 (2)); + stream.start (jttyRequest (43, 2), nullptr); + QCOMPARE (readFrames (stream, 3), (QVector {7, 8, 0})); + stream.stop (); } void TestJttyTxStream::timerEmitsDrainedEdge () @@ -483,5 +703,161 @@ void TestJttyTxStream::sourceCommitIsEmittedOncePerStart () stream.stop (); } +void TestJttyTxStream::queuedClearAndEnqueueAcknowledgeReplacement () +{ + TxAudioQueue queue {8}; + auto const first = queueEpoch (91); + auto const replacement = queueEpoch (92); + queue.clear (first); + queue.applyPendingReset (); + QVector const aborted {1, 2, 3, 4, 5, 6, 7, 8}; + QVector const replacementSamples {11, 12, 13, 14, 15, 16, 17, 18}; + QVERIFY (queue.enqueue (aborted, first).accepted); + QCOMPARE (queue.enqueue (QVector {9}, first).failure, + TxAudioQueueEnqueueFailure::Capacity); + + auto * stream = new JttyTxStream {queue}; + QPointer streamWitness {stream}; + QObject receiver; + int acceptedCount {0}; + int failedCount {0}; + qint64 acceptedId {-1}; + qint64 acceptedSamples {-1}; + TxAudioQueueProgress signaledProgress; + TxAudioQueueProgress callbackProgress; + connect (stream, &JttyTxStream::enqueueAccepted, &receiver, + [&] (qint64 enqueueId, qint64 sampleCount, + TxAudioQueueProgress progress) { + ++acceptedCount; + acceptedId = enqueueId; + acceptedSamples = sampleCount; + signaledProgress = progress; + callbackProgress = queue.progress (); + }, Qt::QueuedConnection); + connect (stream, &JttyTxStream::enqueueFailed, &receiver, + [&] {++failedCount;}, Qt::QueuedConnection); + + QThread audioThread; + stream->moveToThread (&audioThread); + connect (&audioThread, &QThread::finished, stream, &QObject::deleteLater); + + QMetaObject::invokeMethod (stream, [stream, replacement] { + stream->clearQueue (replacement); + }, Qt::QueuedConnection); + QMetaObject::invokeMethod ( + stream, [stream, replacement, replacementSamples] { + stream->enqueuePcm (pcmBytes (replacementSamples), replacement, 101); + }, Qt::QueuedConnection); + audioThread.start (); + + QElapsedTimer callbackWait; + callbackWait.start (); + while (!acceptedCount && !failedCount && callbackWait.elapsed () < 2000) + { + QCoreApplication::processEvents (QEventLoop::AllEvents, 10); + QThread::msleep (1); + } + + bool const stopped = QMetaObject::invokeMethod ( + stream, "stop", Qt::BlockingQueuedConnection); + audioThread.quit (); + bool const threadStopped = audioThread.wait (2000); + + QVERIFY (stopped); + QVERIFY (threadStopped); + QVERIFY (streamWitness.isNull ()); + QCOMPARE (failedCount, 0); + QCOMPARE (acceptedCount, 1); + QCOMPARE (acceptedId, qint64 (101)); + QCOMPARE (acceptedSamples, qint64 (replacementSamples.size ())); + QCOMPARE (signaledProgress.epoch, replacement); + QCOMPARE (signaledProgress.queued_samples, + qint64 (replacementSamples.size ())); + QCOMPARE (signaledProgress.total_samples, + qint64 (replacementSamples.size ())); + QCOMPARE (callbackProgress.epoch, replacement); + QCOMPARE (callbackProgress.total_samples, + qint64 (replacementSamples.size ())); + for (auto sample : replacementSamples) + { + QCOMPARE (queue.pullSample (0), sample); + } + QCOMPARE (queue.pullSample (0), qint16 (0)); +} + +void TestJttyTxStream::queuedEnqueueReportsTypedFailures () +{ + TxAudioQueue queue {2}; + auto const current = queueEpoch (101); + queue.clear (current); + queue.applyPendingReset (); + JttyTxStream stream {queue}; + QSignalSpy accepted (&stream, &JttyTxStream::enqueueAccepted); + QSignalSpy failed (&stream, &JttyTxStream::enqueueFailed); + + stream.enqueuePcm (pcmBytes (QVector {1, 2}), current, 201); + stream.enqueuePcm (pcmBytes (QVector {3}), current, 202); + stream.enqueuePcm (pcmBytes (QVector {4}), queueEpoch (102), 203); + + QCOMPARE (accepted.count (), 1); + QCOMPARE (failed.count (), 2); + QCOMPARE (failed.at (0).at (0).value (), current); + QCOMPARE (failed.at (0).at (1).toLongLong (), qint64 (202)); + QCOMPARE (failed.at (0).at (2).value (), + TxAudioQueueEnqueueFailure::Capacity); + QCOMPARE (failed.at (1).at (1).toLongLong (), qint64 (203)); + QCOMPARE (failed.at (1).at (2).value (), + TxAudioQueueEnqueueFailure::StaleEpoch); +} + +void TestJttyTxStream::pendingPayloadBudgetSurvivesAbort () +{ + TxAudioQueue queue; + JttyTxStream stream {queue}; + auto const first = queueEpoch (1); + auto const replacement = queueEpoch (2); + stream.clearQueue (first); + QSignalSpy accepted (&stream, &JttyTxStream::enqueueAccepted); + QSignalSpy failed (&stream, &JttyTxStream::enqueueFailed); + QByteArray const full (int (TxAudioQueue::defaultCapacity () * sizeof (qint16)), '\0'); + + stream.queuePcm (full, first, 1); + stream.clearQueue (replacement); + stream.queuePcm (pcmBytes ({7}), replacement, 2); + QCOMPARE (failed.count (), 1); + QCOMPARE (failed.at (0).at (2).value (), + TxAudioQueueEnqueueFailure::Capacity); + + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 0); + QCOMPARE (failed.count (), 2); + QCOMPARE (failed.at (1).at (2).value (), + TxAudioQueueEnqueueFailure::StaleEpoch); + + stream.queuePcm (full, replacement, 3); + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 1); +} + +void TestJttyTxStream::pendingRequestBudgetRecoversAfterDelivery () +{ + TxAudioQueue queue; + JttyTxStream stream {queue}; + auto const epoch = queueEpoch (1); + stream.clearQueue (epoch); + QSignalSpy accepted (&stream, &JttyTxStream::enqueueAccepted); + QSignalSpy failed (&stream, &JttyTxStream::enqueueFailed); + for (int id = 1; id <= 65; ++id) stream.queuePcm (pcmBytes ({7}), epoch, id); + QCOMPARE (failed.count (), 1); + QCOMPARE (failed.at (0).at (1).toLongLong (), qint64 (65)); + + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 64); + stream.queuePcm (pcmBytes ({8}), epoch, 66); + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 65); + QCOMPARE (failed.count (), 1); +} + QTEST_MAIN (TestJttyTxStream) #include "test_jtty_txstream.moc" diff --git a/tests/unit/jtty/test_jtty_waterfall.cpp b/tests/unit/jtty/test_jtty_waterfall.cpp new file mode 100644 index 00000000..0611a2f8 --- /dev/null +++ b/tests/unit/jtty/test_jtty_waterfall.cpp @@ -0,0 +1,104 @@ +#include +#include +#include + +#include "commons.h" +#include "widgets/plotter.h" + +namespace { +dec_data_t storage; +} +dec_data_t& dec_data = storage; +QVector g_ColorTbl (256, Qt::black); + +class TestablePlotter final : public CPlotter +{ +public: + using CPlotter::mouseDoubleClickEvent; + + TestablePlotter () + { + setMode ("JTTY"); + setNsps (0, 6912); + setCurrent (false); + setPlot2dGain (0); + setPlot2dZero (0); + setCumulative (true); + setLinearAvg (false); + setReference (false); + setQ65_Sync (false); + setVHF (false); + setSingleDecode (false); + setFlatten (false, false); + setWaterfallAvg (2); + setBars (false); + setTimestamp (1); + setDiskUTC (-1); + setDataFromDisk (false); + setTol (100); + resize (700, 350); + show (); + QCoreApplication::processEvents (); + } + + void push (JttyWaterfallRow const& row) + { + std::array values {}; + if (row.gap) values.fill (1.e30f); + setJttyRow (row); + draw (values.data (), true, false); + } + + void clickRow (int row) + { + QMouseEvent event {QEvent::MouseButtonDblClick, QPointF (100, 30 + row), + Qt::LeftButton, Qt::LeftButton, Qt::NoModifier}; + mouseDoubleClickEvent (&event); + } +}; + +class TestJttyWaterfall final : public QObject +{ + Q_OBJECT +private slots: + void rowIdentitySurvivesAverageResizeAndReplot () + { + TestablePlotter plotter; + QSignalSpy selected (&plotter, &CPlotter::jttyDecodeAgainAtSample); + qint64 const start = qint64 (1) << 34; + plotter.push ({12, start, start + 6912, 180000, false}); + plotter.setWaterfallAvg (11); + plotter.push ({12, start + 6912, start + 6912 + 38016, 183168, false}); + plotter.resize (1000, 450); + QCoreApplication::processEvents (); + plotter.replot (); + plotter.clickRow (1); + QCOMPARE (selected.size (), 1); + QCOMPARE (selected[0][0].toULongLong (), quint64 (12)); + QCOMPARE (selected[0][1].toLongLong (), start + 6912); + plotter.clickRow (0); + QCOMPARE (selected.size (), 2); + QCOMPARE (selected[1][1].toLongLong (), start + 6912 + 38016); + } + + void gapsAndUnpopulatedRowsDoNotSelectUnrelatedAudio () + { + TestablePlotter plotter; + QSignalSpy selected (&plotter, &CPlotter::jttyDecodeAgainAtSample); + plotter.push ({4, 0, 3456, 288, false}); + plotter.push ({4, 3456, 3456, 288, true}); + plotter.push ({5, 0, 3456, 190000, false}); + plotter.clickRow (1); + plotter.clickRow (10); + QCOMPARE (selected.size (), 0); + plotter.clickRow (2); + QCOMPARE (selected.size (), 1); + QCOMPARE (selected[0][0].toULongLong (), quint64 (4)); + plotter.clickRow (0); + QCOMPARE (selected.size (), 2); + QCOMPARE (selected[1][0].toULongLong (), quint64 (5)); + } +}; + +QTEST_MAIN (TestJttyWaterfall) +#include "test_jtty_waterfall.moc" diff --git a/tests/unit/map65/CMakeLists.txt b/tests/unit/map65/CMakeLists.txt index 88064d64..d02e4604 100644 --- a/tests/unit/map65/CMakeLists.txt +++ b/tests/unit/map65/CMakeLists.txt @@ -20,3 +20,14 @@ add_executable (test_map65_runtime_paths target_include_directories (test_map65_runtime_paths PRIVATE ${CMAKE_SOURCE_DIR}/map65) target_link_libraries (test_map65_runtime_paths Qt5::Test) add_test (NAME test_map65_runtime_paths COMMAND test_map65_runtime_paths) + +if (UNIX) + add_executable (test_map65_ptt_unix test_map65_ptt_unix.c) + set_target_properties (test_map65_ptt_unix PROPERTIES AUTOMOC OFF) + add_test (NAME test_map65_ptt_unix COMMAND test_map65_ptt_unix) +endif () + +add_executable (test_map65_ptt_windows test_map65_ptt_windows.c) +target_include_directories (test_map65_ptt_windows PRIVATE windows_fake) +set_target_properties (test_map65_ptt_windows PROPERTIES AUTOMOC OFF) +add_test (NAME test_map65_ptt_windows COMMAND test_map65_ptt_windows) diff --git a/tests/unit/map65/decode_history/decode_history_stubs.f90 b/tests/unit/map65/decode_history/decode_history_stubs.f90 index 9582e19a..89dd9bac 100644 --- a/tests/unit/map65/decode_history/decode_history_stubs.f90 +++ b/tests/unit/map65/decode_history/decode_history_stubs.f90 @@ -5,6 +5,12 @@ module decode_history_observations integer :: jt65_attempts = 0, q65_successes = 0 integer :: phase_attempts(0:12) = 0 integer :: summary_count = 0, fitted_phase = -999 + integer :: display_calls = 0 + ! decode1a's fit values (a), and whether ccf65 reports each bin's + ! shorthand sync from ss(2,1) of that bin instead of -99, so a test can + ! place a shorthand's two tones in chosen bins. + real :: stub_fit = 0.0 + logical :: stub_short_from_ss = .false. logical :: phase_has_signal(0:12) = .true. end module @@ -47,6 +53,7 @@ contains end module module ccf65_legacy_mod + use decode_history_observations implicit none contains subroutine ccf65(ss_plane, nhsym, ssmax, sync1, ipol1, jpz, dt1, flipk, & @@ -59,6 +66,7 @@ contains dt1 = 0.0 flipk = 1.0 syncshort = -99.0 + if (stub_short_from_ss) syncshort = ss_plane(2,1) snr2 = 0.0 dt2 = 0.0 ipol1 = 1 @@ -96,7 +104,7 @@ contains endif decoded = 'K1ABC W9XYZ FN42' sync2 = 100.0 - a = 0.0 + a = stub_fit dt = 0.0 pol = 0.0 qual = 5.0 + 4.0*sin(dphi) @@ -139,11 +147,13 @@ contains end module module display_mod + use decode_history_observations implicit none contains - subroutine display(nkeep, ftol) - integer, intent(in) :: nkeep + subroutine display(nkeep, ftol, nutc) + integer, intent(in) :: nkeep, nutc real, intent(in) :: ftol + display_calls = display_calls + 1 end subroutine end module diff --git a/tests/unit/map65/decode_history/test_map65_decode_history.f90 b/tests/unit/map65/decode_history/test_map65_decode_history.f90 index eb5ce18c..bd2eb9dc 100644 --- a/tests/unit/map65/decode_history/test_map65_decode_history.f90 +++ b/tests/unit/map65/decode_history/test_map65_decode_history.f90 @@ -4,10 +4,17 @@ program test_map65_decode_history use datcom_ptrs_mod, only: ss_old, savg_old use decodes_mod, only: nhsym1, nhsym2 use map65a_mod, only: map65a + use message_history_mod, only: message_record, recent_messages use decode_history_observations implicit none real, allocatable :: samples(:,:) integer :: unit, before_jt65, before_q65 + integer :: messages, rx_log, before_display + integer :: band_nfa = 0, band_nfb = 0, cursor_khz = 0, fits(3), test_nmode = 11 + integer :: click_bin + real :: rec_khz + character(len=128) :: rec + character(len=*), parameter :: JT65_MSG = 'K1ABC W9XYZ FN42' ! Only the center bin has signal power; DSP stand-ins never read samples. nfft_active = 1024 @@ -60,9 +67,84 @@ program test_map65_decode_history call run_pass(nhsym2, 0, 0) call require(jt65_attempts == before_jt65+2 .and. q65_successes == before_q65+2, & 'final pass retains successes after a skipped-period boundary') + + ! A double-click decode reaches Messages/Band Map and map65_rx.log + ! without repeating a decode already recorded by the wideband pass. + messages = count_history_records(JT65_MSG) + rx_log = count_records(21, JT65_MSG) + call require(messages >= 1 .and. rx_log >= 1, 'wideband pass records the JT65 decode') + before_jt65 = jt65_attempts + before_display = display_calls + call click() + call require(jt65_attempts == before_jt65+1, 'click decodes JT65 at the cursor') + call require(count_history_records(JT65_MSG) == messages .and. count_records(21, JT65_MSG) == rx_log, & + 'click does not repeat a decode the wideband pass recorded') + call require(display_calls == before_display+1, 'click refreshes the Messages window') + active_input_generation = 4 + call click() + call require(count_history_records(JT65_MSG) == messages+1 .and. count_records(21, JT65_MSG) == rx_log+1, & + 'click records a decode the wideband pass did not') + call click() + call require(count_history_records(JT65_MSG) == messages+1 .and. count_records(21, JT65_MSG) == rx_log+1, & + 'second click on the same signal is not recorded again') + + ! A click on a JT65C RRR shorthand: its sync tone in the clicked bin and + ! the upper tone 30*4 tone spacings (~3 bins) above, noise elsewhere. It + ! must be found although the click's best JT65 sync bin is elsewhere, be + ! labeled RRR, be recorded at the clicked kHz (band center (nfa+nfb)/2 = + ! 130 kHz, cursor 130 kHz: 144.130 MHz), and carry no fit values left in + ! sig by an earlier decode. + stub_fit = 7.0 + active_input_generation = 5 + call run_pass(nhsym1, 0, 0) + stub_fit = 0.0 + click_bin = nfft_active/2 + 1 + ss_old(2,1,:) = -99.0 + ss_old(2,1,click_bin) = 10.0 + ss_old(2,1,click_bin + nint(3*4*10.0*(11025.0/4096.0)/(96000.0/nfft_active))) = 10.0 + stub_short_from_ss = .true. + test_nmode = 13 + band_nfa = 100 + band_nfb = 160 + cursor_khz = 130 + active_input_generation = 6 + call click() + call require(last_history_record('RRR', rec), 'shorthand click is found and labeled RRR') + read(rec(1:8), *) rec_khz + read(rec(14:22), '(3i3)') fits + call require(abs(rec_khz - 144.130) < 0.0005, 'shorthand click is recorded at the clicked kHz') + call require(all(fits == 0), 'shorthand click records no stale fit values') print '(a)', 'MAP65 decode history tests passed.' contains + integer function count_history_records(text) + character(len=*), intent(in) :: text + type(message_record), allocatable :: records(:) + integer :: i + + call recent_messages(huge(0), records) + count_history_records = 0 + do i = 1, size(records) + if (index(records(i)%line, text) > 0) count_history_records = count_history_records + 1 + enddo + end function + + logical function last_history_record(text, found) + character(len=*), intent(in) :: text + character(len=*), intent(out) :: found + type(message_record), allocatable :: records(:) + integer :: i + + call recent_messages(huge(0), records) + last_history_record = .false. + found = ' ' + do i = 1, size(records) + if (index(records(i)%line, text) == 0) cycle + found = records(i)%line + last_history_record = .true. + enddo + end function + subroutine run_pass(half_symbols, again, find_phase) integer, intent(in) :: half_symbols, again, find_phase integer :: newdat, utc, done, ndphi, mcall3b, nsum, nsave @@ -74,11 +156,33 @@ contains nsum = 0 nsave = 0 call system_clock(t_start) - call map65a(samples,newdat,utc,144.0_real64,100,0,0,0,0,0,again,done,0,ndphi,0, & + call map65a(samples,newdat,utc,144.0_real64,100,0,band_nfa,band_nfb,0,cursor_khz, & + again,done,0,ndphi,0, & -1270,20,mcall3b,nsum,nsave,0,'K1ABC ','FN42 ',0,3,0, & - 'W9XYZ ','EN50 ',half_symbols,96000,0,1,11,0) + 'W9XYZ ','EN50 ',half_symbols,96000,0,1,test_nmode,0) end subroutine + subroutine click() + ! MainWindow::freezeDecode() sets nagain=1 and the manual decode flag. + manualDecodeFlag = 1 + call run_pass(nhsym2, 1, 0) + end subroutine + + integer function count_records(u, text) + integer, intent(in) :: u + character(len=*), intent(in) :: text + character(len=128) :: rec + integer :: ios + count_records = 0 + rewind(u) + do + read(u, '(a)', iostat=ios) rec + if (ios /= 0) exit + if (index(rec, text) > 0) count_records = count_records + 1 + enddo + backspace(u) + end function + subroutine require(condition, description) logical, intent(in) :: condition character(len=*), intent(in) :: description diff --git a/tests/unit/map65/messages_retention/CMakeLists.txt b/tests/unit/map65/messages_retention/CMakeLists.txt new file mode 100644 index 00000000..407ae630 --- /dev/null +++ b/tests/unit/map65/messages_retention/CMakeLists.txt @@ -0,0 +1,17 @@ +# Run the production display() against a stand-in stdout channel that +# records the "@" (Messages window) lines instead of sending them to the GUI. +# Keep replacement module files out of the production module directory. +add_executable (test_map65_messages_retention + messages_retention_stubs.f90 + test_map65_messages_retention.f90 + ${CMAKE_SOURCE_DIR}/map65/libm65/message_history_mod.f90 + ${CMAKE_SOURCE_DIR}/map65/libm65/display.f90) +target_include_directories (test_map65_messages_retention BEFORE PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} + ${PROJECT_BINARY_DIR}/map65/libm65) +target_link_libraries (test_map65_messages_retention PRIVATE m65impl) +target_compile_options (test_map65_messages_retention PRIVATE + $<$:-fcheck=bounds>) +add_test (NAME test_map65_messages_retention COMMAND test_map65_messages_retention) +set_tests_properties (test_map65_messages_retention PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} TIMEOUT 60) diff --git a/tests/unit/map65/messages_retention/messages_retention_stubs.f90 b/tests/unit/map65/messages_retention/messages_retention_stubs.f90 new file mode 100644 index 00000000..a92d952e --- /dev/null +++ b/tests/unit/map65/messages_retention/messages_retention_stubs.f90 @@ -0,0 +1,35 @@ +! Stand-in for the decoder's stdout channel: summarizes the "@" (Messages) +! and "&" (Band Map) lines one display() call sends to the GUI. +module stdout_channel_mod + implicit none + integer :: shown = 0, shown_at_utc = 0, want_utc = -1, oldest_utc = 9999 + integer :: bandmap_entries = 0, display_begins = 0 + integer :: first_shown_utc = -1, second_shown_utc = -1 + character(len=3) :: first_bandmap_frequency = ' ' + ! Mode character (# JT65, : Q65) of each of the first 8 Band Map entries. + character(len=8) :: bandmap_modes = ' ' + character(len=4) :: first_bandmap_utc = ' ' + character(len=12) :: first_bandmap_call = ' ' +contains + subroutine write_stdout(line) + character(len=*), intent(in) :: line + integer :: utc + if (index(line, '') == 1) display_begins = display_begins + 1 + if (line(1:1) == '&' .and. len_trim(line) > 2) then + bandmap_entries = bandmap_entries + 1 + if (bandmap_entries == 1) first_bandmap_frequency = line(2:4) + ! "&" + kHz(3) + ndf(5) + " " + callsign(12) + age(2) + mode(1) + UTC(4) + if (bandmap_entries == 1 .and. len(line) >= 22) first_bandmap_call = line(11:22) + if (bandmap_entries <= 8 .and. len(line) >= 25) & + bandmap_modes(bandmap_entries:bandmap_entries) = line(25:25) + if (bandmap_entries == 1 .and. len(line) >= 29) first_bandmap_utc = line(26:29) + endif + if (line(1:1) /= '@') return + shown = shown + 1 + read(line(20:23), '(i4)') utc ! hhmm column of the "@" line + if (shown == 1) first_shown_utc = utc + if (shown == 2) second_shown_utc = utc + if (utc == want_utc) shown_at_utc = shown_at_utc + 1 + oldest_utc = min(oldest_utc, utc) + end subroutine +end module diff --git a/tests/unit/map65/messages_retention/test_map65_messages_retention.f90 b/tests/unit/map65/messages_retention/test_map65_messages_retention.f90 new file mode 100644 index 00000000..b5b26547 --- /dev/null +++ b/tests/unit/map65/messages_retention/test_map65_messages_retention.f90 @@ -0,0 +1,189 @@ +program test_map65_messages_retention + use iso_fortran_env, only: int64, real64 + use stdout_channel_mod + use display_mod, only: display + use message_history_mod, only: message_record, append_message, clear_messages, recent_messages, & + message_expired + implicit none + integer :: missed, retained, begins_before + + ! A light band keeps exactly Timeout minutes of history. + call run_band(40, 3, 60, missed, retained) + call require(missed == 0, 'light band: every minute''s decodes are shown') + call require(oldest_utc == 1219, '40-minute timeout keeps 40 minutes (1219-1259)') + call run_band(10, 3, 60, missed, retained) + call require(oldest_utc == 1249, '10-minute timeout keeps 10 minutes (1249-1259)') + + ! History retains the timeout interval while display shows the newest rows. + call run_band(40, 25, 120, missed, retained) + call require(missed == 0, 'busy band: newest decodes shown every minute') + call require(retained == 1025, 'busy band: all 40 minutes remain in memory') + call run_band(20, 18, 120, missed, retained) + call require(missed == 0, '20-minute timeout, 18 decodes/min: newest shown every minute') + call test_bandmap_capacity() + call test_midnight_expiry() + call test_bandmap_newest_across_groups() + call test_expiry_edge() + call test_bandmap_modes() + call test_bandmap_compound_call() + call clear_messages() + shown = 0 + begins_before = display_begins + call display(10, 0.010, 1200) + call require(shown == 0, 'empty history emits no Messages rows') + call require(display_begins == begins_before + 1, 'empty history emits a snapshot boundary') + print '(a)', 'MAP65 Messages retention tests passed.' + +contains + subroutine run_band(nkeep, per_min, minutes, missed, retained) + integer, intent(in) :: nkeep, per_min, minutes + integer, intent(out) :: missed, retained + integer :: k, minute, nutc + character(len=22) :: msg + character(len=83) :: rec + real(real64) :: f0 + type(message_record), allocatable :: records(:) + call clear_messages() + missed = 0 + do minute = 0, minutes - 1 + nutc = 100*(12 + minute/60) + mod(minute, 60) + do k = 1, per_min + f0 = 144.0_real64 + 0.001_real64*(100 + 3*k) + write(msg, '(a,i3.3,a)') 'CQ K', k, 'X FN42' + write(rec, 1014) f0, 0, 0, 0, 0, 0.0, 0, 5, -20, nutc, msg, '#', ' ', '#B' + call append_message(rec, nutc, f0, 0) + enddo + call display(nkeep, 0.010, nutc) + shown = 0; shown_at_utc = 0; want_utc = nutc; oldest_utc = 9999 + call display(nkeep, 0.010, nutc) + if (shown_at_utc /= per_min) missed = missed + 1 + enddo + call recent_messages(2000, records) + retained = size(records) +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a22, 7x, 2a1, 2x, a2) + end subroutine + + ! Records exactly Timeout minutes old by UTC are kept whatever mode stored + ! them. A Q65 record is stored during the pass, up to about 20 s before a + ! JT65 record stored at its end, so it is older by the wall clock. + subroutine test_expiry_edge() + call require(.not. message_expired(10, 600_int64, 10), 'edge: record stored at the end of the pass is kept') + call require(.not. message_expired(10, 620_int64, 10), 'edge: record stored earlier in the pass is kept') + call require(message_expired(11, 660_int64, 10), 'edge: record older than the Timeout by UTC expires') + call require(message_expired(10, 86400_int64, 10), 'edge: same UTC minute a day later expires') + call require(.not. message_expired(10, -1_int64, 10), 'edge: unknown storage time falls back to UTC age') + end subroutine + + subroutine test_midnight_expiry() + character(len=83) :: rec + character(len=22) :: msg + type(message_record), allocatable :: records(:) + + call clear_messages() + msg = 'CQ K001X FN42' + write(rec, 1014) 144.100_real64, 0, 0, 0, 0, 0.0, 0, 5, -20, 2358, msg, '#', ' ', '#B' + call append_message(rec, 2358, 144.100_real64, 0) + write(rec, 1014) 144.101_real64, 0, 0, 0, 0, 0.0, 0, 5, -20, 1, msg, '#', ' ', '#B' + call append_message(rec, 1, 144.101_real64, 0) + shown = 0; bandmap_entries = 0; first_bandmap_frequency = ' ' + call display(10, 0.010, 2) + call recent_messages(10, records) + call require(size(records) == 2, 'midnight: recent records remain') + call require(first_shown_utc == 2358 .and. second_shown_utc == 1, & + 'midnight: Messages preserve chronological order') + call require(bandmap_entries == 1 .and. first_bandmap_frequency == '101', & + 'midnight: Band Map uses the newest frequency for a call') + call display(10, 0.010, 10) + call recent_messages(10, records) + call require(size(records) == 1 .and. records(1)%utc == 1, 'midnight: old record expires') +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a22, 7x, 2a1, 2x, a2) + end subroutine + + subroutine test_bandmap_newest_across_groups() + character(len=22) :: msg + character(len=83) :: rec + + call clear_messages() + msg = 'CQ K001X FN42' + write(rec, 1014) 144.200_real64, 0, 0, 0, 0, 0.0, 0, 5, -20, 1200, msg, '#', ' ', '#B' + call append_message(rec, 1200, 144.200_real64, 0) + write(rec, 1014) 144.100_real64, 0, 0, 0, 0, 0.0, 0, 5, -20, 1201, msg, '#', ' ', '#B' + call append_message(rec, 1201, 144.100_real64, 0) + bandmap_entries = 0; first_bandmap_frequency = ' '; first_bandmap_utc = ' ' + call display(10, 0.010, 1201) + call require(bandmap_entries == 1 .and. first_bandmap_frequency == '100', & + 'Band Map uses the newest decode across frequency groups') + ! The waterfall label ages from this UTC, so it must be the newest decode's. + call require(first_bandmap_utc == '1201', 'Band Map entry carries the newest decode''s UTC') +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a22, 7x, 2a1, 2x, a2) + end subroutine + + ! Band Map entries carry the decode's mode, for the waterfall label color. + subroutine test_bandmap_modes() + character(len=22) :: msg + character(len=83) :: rec + + call clear_messages() + msg = 'CQ K001X FN42' + write(rec, 1014) 144.100_real64, 0, 0, 0, 0, 0.0, 0, 5, -20, 1200, msg, '#', ' ', '#B' + call append_message(rec, 1200, 144.100_real64, 0) + msg = 'CQ K002X FN42' + write(rec, 1014) 144.200_real64, 0, 0, 0, 0, 0.0, 0, 5, -20, 1200, msg, ':', ' ', ':A' + call append_message(rec, 1200, 144.200_real64, 0) + bandmap_entries = 0; bandmap_modes = ' ' + call display(10, 0.010, 1200) + call require(bandmap_entries == 2 .and. bandmap_modes(1:2) == '#:', & + 'Band Map entries carry each decode''s mode') +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a22, 7x, 2a1, 2x, a2) + end subroutine + + ! A compound call (prefix/call) reaches the Band Map whole, with the mode + ! and UTC after it, for the Band Map window and the waterfall label. + subroutine test_bandmap_compound_call() + character(len=22) :: msg + character(len=83) :: rec + + call clear_messages() + msg = 'CQ ER/EA8DBM' + write(rec, 1014) 144.124_real64, -500, 0, 0, 0, 0.0, 0, 5, -20, 1200, msg, ':', ' ', ':A' + call append_message(rec, 1200, 144.124_real64, -500) + bandmap_entries = 0; bandmap_modes = ' '; first_bandmap_call = ' '; first_bandmap_utc = ' ' + call display(10, 0.010, 1200) + call require(bandmap_entries == 1 .and. first_bandmap_call == 'ER/EA8DBM', & + 'compound call reaches the Band Map whole') + call require(bandmap_modes(1:1) == ':' .and. first_bandmap_utc == '1200', & + 'compound call entry keeps its mode and UTC') +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a22, 7x, 2a1, 2x, a2) + end subroutine + + subroutine test_bandmap_capacity() + integer :: k + character(len=22) :: msg + character(len=83) :: rec + real(real64) :: f0 + + call clear_messages() + do k = 1, 600 + f0 = 144.0_real64 + 0.001_real64*(100 + k) + write(msg, '(a,i3.3,a)') 'CQ K', k, 'X FN42' + write(rec, 1014) f0, 0, 0, 0, 0, 0.0, 0, 5, -20, 1200, msg, '#', ' ', '#B' + call append_message(rec, 1200, f0, 0) + enddo + shown = 0; shown_at_utc = 0; want_utc = 1200; bandmap_entries = 0 + first_bandmap_frequency = ' ' + call display(40, 0.010, 1200) + call require(shown_at_utc == 600, '600 busy-band Messages rows are shown') + call require(bandmap_entries == 600, 'Band Map includes every visible call') + call require(first_bandmap_frequency == '101', 'Band Map remains frequency ordered') +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a22, 7x, 2a1, 2x, a2) + end subroutine + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine +end program diff --git a/tests/unit/map65/test_map65_deep_search_cache.f90 b/tests/unit/map65/test_map65_deep_search_cache.f90 index 6479bcad..a30b1165 100644 --- a/tests/unit/map65/test_map65_deep_search_cache.f90 +++ b/tests/unit/map65/test_map65_deep_search_cache.f90 @@ -130,8 +130,9 @@ contains integer :: cached_count cached_count = ntot - cached_messages = testmsg(1:ntot) - cached_symbols = ncode(:, 1:ntot) + allocate(cached_messages(cached_count), cached_symbols(size(ncode, 1), cached_count)) + cached_messages(:) = testmsg(1:cached_count) + cached_symbols(:, :) = ncode(:, 1:cached_count) call build_fresh(local_call, dx_call, dx_grid, eme_only) call require(ntot == cached_count, description//': cached and fresh candidate counts match') call require(all(testmsg(1:ntot) == cached_messages), description//': cached and fresh messages match') diff --git a/tests/unit/map65/test_map65_filbig_boundary.f90 b/tests/unit/map65/test_map65_filbig_boundary.f90 new file mode 100644 index 00000000..80931ac9 --- /dev/null +++ b/tests/unit/map65/test_map65_filbig_boundary.f90 @@ -0,0 +1,64 @@ +program test_map65_filbig_boundary + use iso_fortran_env, only: real32, real64 + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite, ieee_quiet_nan, ieee_value + use filbig_mod, only: filbig, MAXFFT1, MAXFFT2 + use cacb_mod, only: init_cacb, ca, cb + use decode1a_mod, only: jt65c_center_offset + use npar_ptrs_mod, only: set_runtime_params + implicit none + + real(real32) :: dd(4,1) + complex :: cx(MAXFFT2), cy(MAXFFT2) + real(real64) :: f0 + integer :: rate, nfft, nfft_big, newdat, n4 + integer, parameter :: nfft_short = 77175 + character(len=16) :: argument + + call get_command_argument(1, argument) + read(argument, *) rate + nfft = 32768 * (rate / 96000) + nfft_big = 56 * rate + call set_runtime_params(rate, nfft, nfft_big) + call init_cacb(MAXFFT1) + + ! Poison unused storage so reads beyond the active FFT cannot pass unnoticed. + ca = cmplx(ieee_value(0.0_real32, ieee_quiet_nan), 0.0_real32) + ca(:nfft_big) = cmplx(1.0_real32, -0.25_real32) + cb = ca + dd = 0.0_real32 + newdat = 0 + + f0 = real(nfft - 52, real64) * real(rate, real64) / real(nfft, real64) + call check_extraction(f0) + call check_extraction(f0 + jt65c_center_offset) + call check_extraction(0.0_real64) + + call filbig(dd, 1, real(rate, real64) + 1378.125_real64, newdat, rate, .true., cx, cy, n4) + call require(all(abs(cx(:nfft_short)) == 0.0), 'out-of-band X extraction is zero') + call require(all(abs(cy(:nfft_short)) == 0.0), 'out-of-band Y extraction is zero') + print '(a)', 'MAP65 filter boundary tests passed' + +contains + + subroutine check_extraction(center) + real(real64), intent(in) :: center + + call filbig(dd, 1, center, newdat, rate, .true., cx, cy, n4) + call require(all(ieee_is_finite(real(cx(:nfft_short)))) .and. & + all(ieee_is_finite(aimag(cx(:nfft_short)))), 'X extraction is finite') + call require(all(ieee_is_finite(real(cy(:nfft_short)))) .and. & + all(ieee_is_finite(aimag(cy(:nfft_short)))), 'Y extraction is finite') + call require(any(abs(cx(:nfft_short)) > 0.0), 'available in-band samples are retained') + call require(all(cx(:nfft_short) == cy(:nfft_short)), 'polarizations use the same boundary handling') + end subroutine check_extraction + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine require +end program test_map65_filbig_boundary diff --git a/tests/unit/map65/test_map65_ptt_unix.c b/tests/unit/map65/test_map65_ptt_unix.c new file mode 100644 index 00000000..65af255d --- /dev/null +++ b/tests/unit/map65/test_map65_ptt_unix.c @@ -0,0 +1,489 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int serial_open(const char *, int, ...); +static int serial_ioctl(int, unsigned long, ...); +static int serial_close(int); +static int serial_poll(struct pollfd *, nfds_t, int); + +#define open serial_open +#define ioctl serial_ioctl +#define close serial_close +#define poll serial_poll +#ifndef PTT_UNIX_SOURCE +#define PTT_UNIX_SOURCE "../../../map65/libm65/ptt_unix.c" +#endif +#include PTT_UNIX_SOURCE +#undef open +#undef ioctl +#undef close +#undef poll + +enum operation { OPEN_PORT, GET_LINES, SET_LINES, CLOSE_PORT }; +struct event { + enum operation operation; + int descriptor; + int lines; + char path[256]; +}; + +static struct event events[128]; +static int event_count; +static int lines[64]; +static int opened[64]; +static int next_descriptor = 10; +static int fail_open; +static unsigned long fail_ioctl_request; +static int fail_ioctl_countdown; +static int failed_descriptor; +static short poll_events; +static int fail_poll; +static int mock_failed; +static int iptt; +static const int ptt_lines = TIOCM_RTS | TIOCM_DTR; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __func__, __LINE__, #condition); \ + return 0; \ + } \ +} while (0) + +static struct event *record(enum operation operation, int descriptor) +{ + struct event *event; + if (event_count == (int)(sizeof(events) / sizeof(events[0]))) { + fprintf(stderr, "Serial event buffer exhausted\n"); + exit(2); + } + event = &events[event_count++]; + memset(event, 0, sizeof(*event)); + event->operation = operation; + event->descriptor = descriptor; + return event; +} + +static int serial_open(const char *path, int flags, ...) +{ + int descriptor = next_descriptor++; + struct event *event = record(OPEN_PORT, descriptor); + snprintf(event->path, sizeof(event->path), "%s", path); + if (!(flags & O_NONBLOCK) || !(flags & O_NOCTTY) + || (flags & O_ACCMODE) != O_RDWR + || descriptor >= (int)(sizeof(opened) / sizeof(opened[0]))) { + mock_failed = 1; + return -1; + } + if (fail_open) { + errno = EACCES; + return -1; + } + opened[descriptor] = 1; + lines[descriptor] = TIOCM_CTS | TIOCM_DTR | TIOCM_RTS; + return descriptor; +} + +static int serial_ioctl(int descriptor, unsigned long request, ...) +{ + va_list arguments; + int *value; + struct event *event = record(request == TIOCMGET ? GET_LINES : SET_LINES, + descriptor); + va_start(arguments, request); + value = va_arg(arguments, int *); + va_end(arguments); + if (descriptor < 0 || descriptor >= 64 || !opened[descriptor] + || (request != TIOCMGET && request != TIOCMSET)) { + mock_failed = 1; + return -1; + } + event->lines = request == TIOCMSET ? *value : lines[descriptor]; + if (descriptor == failed_descriptor + || (request == fail_ioctl_request && --fail_ioctl_countdown == 0)) { + errno = EIO; + return -1; + } + if (request == TIOCMGET) + *value = lines[descriptor]; + else + lines[descriptor] = *value; + return 0; +} + +static int serial_close(int descriptor) +{ + record(CLOSE_PORT, descriptor); + if (descriptor < 0 || descriptor >= 64 || !opened[descriptor]) { + mock_failed = 1; + return -1; + } + opened[descriptor] = 0; + return 0; +} + +static int serial_poll(struct pollfd *ports, nfds_t count, int timeout) +{ + if (count != 1 || timeout != 0 || ports[0].events != 0 + || ports[0].fd < 0 || ports[0].fd >= 64 || !opened[ports[0].fd]) { + mock_failed = 1; + return -1; + } + if (fail_poll) { + errno = EINTR; + return -1; + } + ports[0].revents = poll_events; + return poll_events ? 1 : 0; +} + +static int command(int on) +{ + int unused = 0; + return ptt_(&unused, &on, &iptt); +} + +static void fail_next_ioctl(unsigned long request, int occurrence) +{ + fail_ioctl_request = request; + fail_ioctl_countdown = occurrence; +} + +static void reset(void) +{ + fail_open = 0; + fail_ioctl_request = 0; + failed_descriptor = -1; + poll_events = 0; + fail_poll = 0; + ptt_close(); + ptt_set_override(NULL); + event_count = 0; + next_descriptor = 10; + mock_failed = 0; + iptt = 0; + memset(opened, 0, sizeof(opened)); + memset(lines, 0, sizeof(lines)); +} + +static int count(enum operation operation) +{ + int result = 0; + int i; + for (i = 0; i < event_count; ++i) + result += events[i].operation == operation; + return result; +} + +static int first(enum operation operation) +{ + int i; + for (i = 0; i < event_count; ++i) + if (events[i].operation == operation) + return i; + return -1; +} + +static int disabled_and_unopened_off(void) +{ + CHECK(command(1) == 0 && iptt == 1); + CHECK(command(0) == 0 && iptt == 0); + CHECK(event_count == 0); + ptt_set_override("/dev/serial-A"); + CHECK(command(0) == 0 && iptt == 0); + CHECK(event_count == 0); + return 1; +} + +static int reuse_and_preserve_lines(void) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0 && iptt == 1); + CHECK(events[0].operation == OPEN_PORT); + CHECK(events[1].operation == GET_LINES); + CHECK(events[2].operation == SET_LINES && events[2].lines == TIOCM_CTS); + CHECK(lines[10] == (TIOCM_CTS | ptt_lines)); + CHECK(command(0) == 0 && iptt == 0); + CHECK(lines[10] == TIOCM_CTS); + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0 && iptt == 1); + CHECK(count(OPEN_PORT) == 1 && count(CLOSE_PORT) == 0); + return 1; +} + +static int idle_switch(void) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0); + CHECK(command(0) == 0); + event_count = 0; + ptt_set_override("/dev/serial-B"); + CHECK(command(1) == 0 && iptt == 1); + CHECK(count(CLOSE_PORT) == 1 && count(OPEN_PORT) == 1); + CHECK(first(CLOSE_PORT) < first(OPEN_PORT)); + CHECK(strcmp(events[first(OPEN_PORT)].path, "/dev/serial-B") == 0); + CHECK(!opened[10] && opened[11]); + CHECK(lines[10] == TIOCM_CTS && lines[11] == (TIOCM_CTS | ptt_lines)); + return 1; +} + +static int active_switch(void) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0); + event_count = 0; + ptt_set_override("/dev/serial-B"); + CHECK(count(OPEN_PORT) == 0 && count(CLOSE_PORT) == 0); + CHECK(command(1) == 0 && iptt == 1); + CHECK(count(OPEN_PORT) == 0 && count(CLOSE_PORT) == 0); + CHECK(command(0) == 0 && iptt == 0); + CHECK(count(OPEN_PORT) == 0 && count(CLOSE_PORT) == 1); + CHECK(lines[10] == TIOCM_CTS); + CHECK(first(SET_LINES) < first(CLOSE_PORT)); + CHECK(command(1) == 0); + CHECK(strcmp(events[first(OPEN_PORT)].path, "/dev/serial-B") == 0); + return 1; +} + +static int active_disable(void) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0); + event_count = 0; + ptt_set_override(NULL); + CHECK(count(CLOSE_PORT) == 0); + CHECK(command(0) == 0 && iptt == 0); + CHECK(lines[10] == TIOCM_CTS && !opened[10]); + CHECK(count(CLOSE_PORT) == 1 && count(OPEN_PORT) == 0); + event_count = 0; + CHECK(command(1) == 0 && iptt == 1); + CHECK(command(0) == 0 && iptt == 0); + CHECK(event_count == 0); + return 1; +} + +static int repeated_switches(void) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0); + ptt_set_override("/dev/serial-B"); + ptt_set_override("/dev/serial-A"); + CHECK(command(0) == 0); + CHECK(count(OPEN_PORT) == 1 && count(CLOSE_PORT) == 0); + CHECK(command(1) == 0); + ptt_set_override("/dev/serial-B"); + ptt_set_override(NULL); + ptt_set_override("/dev/serial-C"); + CHECK(command(0) == 0); + CHECK(count(OPEN_PORT) == 1 && count(CLOSE_PORT) == 1); + event_count = 0; + CHECK(command(1) == 0); + CHECK(strcmp(events[first(OPEN_PORT)].path, "/dev/serial-C") == 0); + return 1; +} + +static int open_failure(void) +{ + ptt_set_override("/dev/serial-A"); + fail_open = 1; + CHECK(command(1) != 0 && iptt == 0); + CHECK(count(GET_LINES) == 0 && count(SET_LINES) == 0); + fail_open = 0; + CHECK(command(1) == 0 && iptt == 1); + return 1; +} + +static int initialization_failure(unsigned long request) +{ + int i; + ptt_set_override("/dev/serial-A"); + fail_next_ioctl(request, 1); + CHECK(command(1) != 0 && iptt == 0); + for (i = 0; i < event_count; ++i) + CHECK(events[i].operation != SET_LINES || !(events[i].lines & ptt_lines)); + event_count = 0; + CHECK(command(1) != 0 && iptt == 0); + CHECK(count(OPEN_PORT) == 0 && count(SET_LINES) == 0); + CHECK(command(0) == 0 && iptt == 0); + CHECK(command(1) == 0 && iptt == 1); + return 1; +} + +static int initial_get_failure(void) { return initialization_failure(TIOCMGET); } +static int initial_set_failure(void) { return initialization_failure(TIOCMSET); } + +static int keying_failure(unsigned long request) +{ + ptt_set_override("/dev/serial-A"); + fail_next_ioctl(request, 2); + CHECK(command(1) != 0 && iptt == 0); + event_count = 0; + ptt_set_override("/dev/serial-B"); + CHECK(command(1) != 0 && iptt == 0); + CHECK(count(OPEN_PORT) == 0 && count(CLOSE_PORT) == 0); + CHECK(command(0) == 0 && iptt == 0); + CHECK(!opened[10]); + CHECK(command(1) == 0 && iptt == 1); + CHECK(strcmp(events[first(OPEN_PORT)].path, "/dev/serial-B") == 0); + return 1; +} + +static int keying_get_failure(void) { return keying_failure(TIOCMGET); } +static int keying_set_failure(void) { return keying_failure(TIOCMSET); } + +static int release_failure(unsigned long request, const char *next_path) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0 && iptt == 1); + event_count = 0; + ptt_set_override(next_path); + fail_next_ioctl(request, 1); + CHECK(command(0) != 0 && iptt == 1); + CHECK(opened[10] && count(OPEN_PORT) == 0 && count(CLOSE_PORT) == 0); + CHECK(command(1) != 0 && iptt == 1); + CHECK(count(OPEN_PORT) == 0 && count(CLOSE_PORT) == 0); + CHECK(command(0) == 0 && iptt == 0); + CHECK(lines[10] == TIOCM_CTS && !opened[10]); + CHECK(count(CLOSE_PORT) == 1); + CHECK(command(1) == 0 && iptt == 1); + CHECK(count(OPEN_PORT) == (next_path ? 1 : 0)); + return 1; +} + +static int release_get_failure(void) { return release_failure(TIOCMGET, "/dev/serial-B"); } +static int release_set_failure(void) { return release_failure(TIOCMSET, "/dev/serial-B"); } +static int disable_release_failure(void) { return release_failure(TIOCMSET, NULL); } + +static int disconnected_port(int during_tx, const char *next_path) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == PTT_OK); + if (!during_tx) + CHECK(command(0) == PTT_OK); + failed_descriptor = 10; + poll_events = POLLHUP | POLLERR; + event_count = 0; + CHECK(command(during_tx ? 0 : 1) == PTT_DEVICE_LOST && iptt == 0); + CHECK(!opened[10] && count(CLOSE_PORT) == 1); + CHECK(count(OPEN_PORT) == 0); + ptt_set_override(next_path); + poll_events = 0; + CHECK(command(1) == PTT_OK && iptt == 1); + CHECK(count(OPEN_PORT) == (next_path ? 1 : 0)); + if (next_path) + CHECK(strcmp(events[first(OPEN_PORT)].path, next_path) == 0); + CHECK(command(0) == PTT_OK && iptt == 0); + return 1; +} + +static int disconnect_idle(void) { return disconnected_port(0, "/dev/serial-B"); } +static int disconnect_active(void) { return disconnected_port(1, "/dev/serial-B"); } +static int disconnect_same_path(void) { return disconnected_port(1, "/dev/serial-A"); } +static int disconnect_disable(void) { return disconnected_port(1, NULL); } + +static int persistent_control_failure(void) +{ + int i; + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == PTT_OK); + ptt_set_override("/dev/serial-B"); + failed_descriptor = 10; + event_count = 0; + for (i = 0; i < 3; ++i) { + poll_events = i == 1 ? POLLERR : 0; + fail_poll = i == 2; + CHECK(command(0) == PTT_ERROR && iptt == 1); + CHECK(command(1) == PTT_ERROR && iptt == 1); + CHECK(opened[10] && count(CLOSE_PORT) == 0 && count(OPEN_PORT) == 0); + } + fail_poll = 0; + poll_events = POLLHUP; + CHECK(command(0) == PTT_DEVICE_LOST && iptt == 0); + CHECK(!opened[10] && count(CLOSE_PORT) == 1); + poll_events = 0; + CHECK(command(1) == PTT_OK && iptt == 1); + CHECK(strcmp(events[first(OPEN_PORT)].path, "/dev/serial-B") == 0); + return 1; +} + +static int disconnect_initialization(void) +{ + ptt_set_override("/dev/serial-A"); + failed_descriptor = 10; + poll_events = POLLHUP; + CHECK(command(1) == PTT_DEVICE_LOST && iptt == 0); + CHECK(!opened[10] && count(CLOSE_PORT) == 1); + CHECK(count(SET_LINES) == 0); + poll_events = 0; + CHECK(command(1) == PTT_OK && iptt == 1); + return 1; +} + +static int shutdown_cleanup(void) +{ + ptt_set_override("/dev/serial-A"); + CHECK(command(1) == 0); + event_count = 0; + ptt_close(); + CHECK(lines[10] == TIOCM_CTS && !opened[10]); + CHECK(count(SET_LINES) == 1 && count(CLOSE_PORT) == 1); + CHECK(first(SET_LINES) < first(CLOSE_PORT)); + event_count = 0; + ptt_close(); + CHECK(event_count == 0); + CHECK(command(1) == 0); + fail_next_ioctl(TIOCMSET, 1); + event_count = 0; + ptt_close(); + CHECK(count(SET_LINES) == 1 && count(CLOSE_PORT) == 1 && !opened[11]); + return 1; +} + +int main(void) +{ + const struct { + const char *name; + int (*run)(void); + } tests[] = { + {"disabled and unopened off", disabled_and_unopened_off}, + {"reuse and preserve lines", reuse_and_preserve_lines}, + {"idle switch", idle_switch}, + {"active switch", active_switch}, + {"active disable", active_disable}, + {"repeated switches", repeated_switches}, + {"open failure", open_failure}, + {"initial get failure", initial_get_failure}, + {"initial set failure", initial_set_failure}, + {"keying get failure", keying_get_failure}, + {"keying set failure", keying_set_failure}, + {"release get failure", release_get_failure}, + {"release set failure", release_set_failure}, + {"disable release failure", disable_release_failure}, + {"disconnect while idle", disconnect_idle}, + {"disconnect while active", disconnect_active}, + {"disconnect and reuse path", disconnect_same_path}, + {"disconnect and disable", disconnect_disable}, + {"persistent control failure", persistent_control_failure}, + {"disconnect during initialization", disconnect_initialization}, + {"shutdown cleanup", shutdown_cleanup} + }; + int failed = 0; + size_t i; + for (i = 0; i < sizeof(tests) / sizeof(tests[0]); ++i) { + int passed; + reset(); + passed = tests[i].run() && !mock_failed; + printf("%s: %s\n", passed ? "PASS" : "FAIL", tests[i].name); + failed += !passed; + } + reset(); + return failed ? 1 : 0; +} diff --git a/tests/unit/map65/test_map65_ptt_windows.c b/tests/unit/map65/test_map65_ptt_windows.c new file mode 100644 index 00000000..23113c6c --- /dev/null +++ b/tests/unit/map65/test_map65_ptt_windows.c @@ -0,0 +1,323 @@ +#include +#include +#include +#include + +#ifndef PTT_WINDOWS_SOURCE +#define PTT_WINDOWS_SOURCE "../../../map65/libm65/ptt.c" +#endif +/* Redirect ptt.c's call (and our mock below) so our definition doesn't collide with libkernel32's real GetLastError at link time. */ +#define GetLastError GetLastErr +DWORD GetLastErr(void); +#include PTT_WINDOWS_SOURCE + +enum { OPEN_PORT = 100, CLOSE_PORT, RTS = 1, DTR = 2 }; +struct event { + DWORD operation; + int handle; + char path[64]; +}; + +static struct event events[128]; +static int event_count; +static int opened[64]; +static int lines[64]; +static int next_handle = 10; +static int fail_open; +static int fail_close; +static int failures[10]; +static DWORD errors[10]; +static DWORD last_error; +static int mock_failed; +static int iptt; +static int port; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __func__, __LINE__, #condition); \ + return 0; \ + } \ +} while (0) + +static struct event *record(DWORD operation, int handle) +{ + struct event *event; + if (event_count == (int)(sizeof(events) / sizeof(events[0]))) + exit(2); + event = &events[event_count++]; + memset(event, 0, sizeof(*event)); + event->operation = operation; + event->handle = handle; + return event; +} + +static int valid_handle(HANDLE handle) +{ + intptr_t value = (intptr_t)handle; + if (value < 0 || value >= 64 || !opened[value]) { + mock_failed = 1; + return 0; + } + return 1; +} + +HANDLE CreateFileA(const char *path, DWORD access, DWORD sharing, void *security, + DWORD creation, DWORD attributes, HANDLE template_file) +{ + int handle = next_handle++; + struct event *event = record(OPEN_PORT, handle); + snprintf(event->path, sizeof(event->path), "%s", path); + if (access != GENERIC_WRITE || sharing || security || creation != OPEN_EXISTING + || attributes != FILE_ATTRIBUTE_NORMAL || template_file || handle >= 64) + mock_failed = 1; + if (mock_failed || fail_open) { + last_error = ERROR_ACCESS_DENIED; + return INVALID_HANDLE_VALUE; + } + opened[handle] = 1; + return (HANDLE)(intptr_t)handle; +} + +BOOL EscapeCommFunction(HANDLE handle, DWORD operation) +{ + int value = (int)(intptr_t)handle; + record(operation, value); + if (!valid_handle(handle)) + return 0; + if (operation != SETRTS && operation != SETDTR && operation != CLRRTS + && operation != CLRDTR && operation != CLRBREAK) { + mock_failed = 1; + return 0; + } + if (failures[operation]) { + if (failures[operation] > 0) + --failures[operation]; + last_error = errors[operation]; + return 0; + } + last_error = 0; + if (operation == SETRTS) lines[value] |= RTS; + if (operation == SETDTR) lines[value] |= DTR; + if (operation == CLRRTS) lines[value] &= ~RTS; + if (operation == CLRDTR) lines[value] &= ~DTR; + return 1; +} + +BOOL CloseHandle(HANDLE handle) +{ + record(CLOSE_PORT, (int)(intptr_t)handle); + if (!valid_handle(handle)) + return 0; + if (fail_close) { + last_error = ERROR_GEN_FAILURE; + return 0; + } + opened[(intptr_t)handle] = 0; + return 1; +} + +DWORD GetLastError(void) { return last_error; } + +static int command(int on) { return ptt_(&port, &on, &iptt); } + +static int count(DWORD operation) +{ + int total = 0; + int i; + for (i = 0; i < event_count; ++i) + total += events[i].operation == operation; + return total; +} + +static void fail(DWORD operation, DWORD error, int attempts) +{ + failures[operation] = attempts; + errors[operation] = error; +} + +static void reset(void) +{ + memset(failures, 0, sizeof(failures)); + fail_open = fail_close = 0; + ptt_close(); + memset(opened, 0, sizeof(opened)); + memset(lines, 0, sizeof(lines)); + event_count = mock_failed = iptt = 0; + next_handle = 10; + port = 3; +} + +static int disabled_and_unopened_release(void) +{ + CHECK(command(0) == PTT_OK && !iptt); + port = 0; + CHECK(command(1) == PTT_OK && iptt); + CHECK(command(0) == PTT_OK && !iptt); + ptt_close(); + CHECK(event_count == 0); + return 1; +} + +static int normal_cycle_and_switch(void) +{ + CHECK(command(1) == PTT_OK && iptt); + CHECK(strcmp(events[0].path, "COM3") == 0); + CHECK(lines[10] == (RTS | DTR)); + event_count = 0; + port = 12; + CHECK(command(1) == PTT_OK && iptt); + CHECK(!event_count); + CHECK(command(0) == PTT_OK && !iptt); + CHECK(!lines[10] && !opened[10]); + CHECK(events[0].operation == CLRRTS && events[1].operation == CLRDTR); + CHECK(events[2].operation == CLRBREAK && events[3].operation == CLOSE_PORT); + CHECK(command(1) == PTT_OK && iptt); + CHECK(strcmp(events[4].path, "\\\\.\\COM12") == 0); + port = 0; + CHECK(command(0) == PTT_OK && !iptt && !opened[11] && !lines[11]); + event_count = 0; + CHECK(command(1) == PTT_OK && iptt); + CHECK(command(0) == PTT_OK && !iptt && !event_count); + return 1; +} + +static int open_failure(void) +{ + fail_open = 1; + CHECK(command(1) == PTT_ERROR && !iptt); + CHECK(event_count == 1); + CHECK(command(0) == PTT_OK && !iptt && event_count == 1); + fail_open = 0; + CHECK(command(1) == PTT_OK && iptt); + return 1; +} + +static int key_failure(DWORD operation) +{ + fail(operation, ERROR_GEN_FAILURE, 1); + CHECK(command(1) == PTT_ERROR && !iptt); + CHECK(opened[10] && count(CLOSE_PORT) == 0); + CHECK(lines[10] == (operation == SETDTR ? RTS : 0)); + if (operation == SETRTS) CHECK(count(SETDTR) == 0); + event_count = 0; + port = 12; + CHECK(command(1) == PTT_ERROR && !iptt && !event_count); + CHECK(command(0) == PTT_OK && !iptt && !opened[10] && !lines[10]); + CHECK(command(1) == PTT_OK && iptt); + CHECK(strcmp(events[4].path, "\\\\.\\COM12") == 0); + return 1; +} + +static int rts_key_failure(void) { return key_failure(SETRTS); } +static int dtr_key_failure(void) { return key_failure(SETDTR); } + +static int release_failure(DWORD operation, int attempts) +{ + CHECK(command(1) == PTT_OK && iptt); + event_count = 0; + port = 0; + fail(operation, ERROR_GEN_FAILURE, attempts); + CHECK(command(0) == PTT_ERROR && iptt && opened[10]); + CHECK(count(CLRRTS) == 1 && count(CLRDTR) == 1 && count(CLRBREAK) == 1); + CHECK(count(CLOSE_PORT) == 0); + CHECK(command(1) == PTT_ERROR && iptt); + CHECK(count(SETRTS) == 0 && count(SETDTR) == 0 && count(OPEN_PORT) == 0); + if (attempts < 0) { + CHECK(command(0) == PTT_ERROR && iptt && opened[10]); + CHECK(count(CLOSE_PORT) == 0); + failures[operation] = 0; + } + CHECK(command(0) == PTT_OK && !iptt && !opened[10] && !lines[10]); + CHECK(count(CLOSE_PORT) == 1); + event_count = 0; + CHECK(command(1) == PTT_OK && iptt && !event_count); + return 1; +} + +static int transient_rts_failure(void) { return release_failure(CLRRTS, 1); } +static int persistent_dtr_failure(void) { return release_failure(CLRDTR, -1); } +static int unsupported_break(void) +{ + CHECK(command(1) == PTT_OK && iptt); + event_count = 0; + fail(CLRBREAK, ERROR_GEN_FAILURE, -1); + CHECK(command(0) == PTT_OK && !iptt && !opened[10] && !lines[10]); + CHECK(count(CLRRTS) == 1 && count(CLRDTR) == 1 && count(CLRBREAK) == 1); + CHECK(count(CLOSE_PORT) == 1); + CHECK(command(1) == PTT_OK && iptt && opened[11]); + return 1; +} + +static int device_loss(DWORD operation, DWORD error) +{ + if (operation == CLRRTS) CHECK(command(1) == PTT_OK && iptt); + fail(operation, error, -1); + CHECK(command(operation == SETDTR) == PTT_DEVICE_LOST && !iptt); + CHECK(!opened[10] && count(CLOSE_PORT) == 1); + event_count = 0; + CHECK(command(0) == PTT_OK && !iptt && !event_count); + failures[operation] = 0; + CHECK(command(1) == PTT_OK && iptt && opened[11]); + return 1; +} + +static int lost_during_key(void) { return device_loss(SETDTR, ERROR_NO_SUCH_DEVICE); } +static int lost_during_release(void) { return device_loss(CLRRTS, ERROR_DEVICE_NOT_CONNECTED); } + +static int close_failure(void) +{ + CHECK(command(1) == PTT_OK); + fail_close = 1; + CHECK(command(0) == PTT_ERROR && !iptt && opened[10] && !lines[10]); + event_count = 0; + CHECK(command(1) == PTT_ERROR && !event_count); + fail_close = 0; + CHECK(command(0) == PTT_OK && !opened[10]); + return 1; +} + +static int shutdown_cleanup(void) +{ + CHECK(command(1) == PTT_OK); + event_count = 0; + fail(CLRRTS, ERROR_GEN_FAILURE, -1); + ptt_close(); + CHECK(count(CLRRTS) == 1 && count(CLRDTR) == 1 && count(CLRBREAK) == 1); + CHECK(count(CLOSE_PORT) == 1 && !opened[10]); + event_count = 0; + ptt_close(); + CHECK(!event_count); + return 1; +} + +int main(void) +{ + const struct { + const char *name; + int (*run)(void); + } tests[] = { + {"disabled and unopened release", disabled_and_unopened_release}, + {"normal cycle and switch", normal_cycle_and_switch}, + {"open failure", open_failure}, + {"RTS key failure", rts_key_failure}, + {"DTR key failure", dtr_key_failure}, + {"transient RTS release failure", transient_rts_failure}, + {"persistent DTR release failure", persistent_dtr_failure}, + {"unsupported break", unsupported_break}, + {"lost during key", lost_during_key}, + {"lost during release", lost_during_release}, + {"close failure", close_failure}, + {"shutdown cleanup", shutdown_cleanup} + }; + int failed = 0; + size_t i; + for (i = 0; i < sizeof(tests) / sizeof(tests[0]); ++i) { + int passed; + reset(); + passed = tests[i].run() && !mock_failed; + printf("%s: %s\n", passed ? "PASS" : "FAIL", tests[i].name); + failed += !passed; + } + reset(); + return failed ? 1 : 0; +} diff --git a/tests/unit/map65/test_map65_q65_dphi.f90 b/tests/unit/map65/test_map65_q65_dphi.f90 index a9c0527d..3008a787 100644 --- a/tests/unit/map65/test_map65_q65_dphi.f90 +++ b/tests/unit/map65/test_map65_q65_dphi.f90 @@ -22,6 +22,8 @@ program test_map65_q65_dphi integer, allocatable :: seed(:) type(candidate) :: candidates(MAX_CANDIDATES) character(len=24) :: sent_message + character(len=12) :: hiscall + character(len=6) :: hisgrid integer(int8) :: lstrong(0:1023) integer :: i, k, nwave, seed_size, ncand, selected, newdat, n4, idec integer :: nb, nbslider, ihsym, nzap, nkh @@ -70,6 +72,8 @@ program test_map65_q65_dphi idphi = 180 fcenter = 144.125_real64 nkhz_center = 125 + hiscall = ' ' + hisgrid = ' ' nb = 0 nbslider = 40 @@ -103,12 +107,23 @@ program test_map65_q65_dphi sample_rate, .true., c4a, c4b, n4) call system_clock(t_start) call q65b(1, 0, 0, fcenter, 0, sample_rate, nkhz_center, 0, 100, .true., idphi, & - 'N0CALL ', 'FN31 ', ' ', ' ', 2, & + 'N0CALL ', 'FN31 ', hiscall, hisgrid, 2, & real(candidates(selected)%f, real64), 1.270, newdat, 0, 0, 0, idec) call require(.not. logical(abort_decode), 'decode within the time budget') call require(nsnr0 > -99 .and. trim(msg0) == trim(message), & 'recover the Q65 message despite opposite-phase receiver channels') + + manualDecodeFlag = 1 + hiscall = ' ' + hisgrid = ' ' + call system_clock(t_start) + call q65b(1, 0, 0, fcenter, 0, sample_rate, nkhz_center, 0, 100, .true., idphi, & + 'N0CALL ', 'FN31 ', hiscall, hisgrid, 2, & + real(candidates(selected)%f, real64) + 0.040_real64, 1.270, 0, 1, 0, 0, idec) + call require(nsnr0 > -99 .and. trim(msg0) == trim(message), & + 'manual center recovers Q65 when f0 is displaced from the clicked frequency') + call require(.not. logical(abort_decode), 'manual decode stays within the time budget') call fini_timer() print '(a)', 'MAP65 Q65 Dphi test passed.' diff --git a/tests/unit/map65/test_map65_q65_handoff.f90 b/tests/unit/map65/test_map65_q65_handoff.f90 new file mode 100644 index 00000000..268a480a --- /dev/null +++ b/tests/unit/map65/test_map65_q65_handoff.f90 @@ -0,0 +1,117 @@ +program test_map65_q65_handoff + use iso_fortran_env, only: int16, real64 + use cacb_mod, only: ca, cb, init_cacb + use q65b_mod, only: build_q65_samples + implicit none + + integer, parameter :: nfft2 = 336000, nfft1 = 5376000, sample_rate = 12000 + integer, parameter :: k_auto = 2600000, k_manual = 2600100 + real, parameter :: df = 96000.0/nfft1 + real, parameter :: input_amplitude = 100000000.0 + real(real64), parameter :: pi = acos(-1.0_real64) + integer(int16), allocatable :: wave(:), reference(:) + real(real64) :: reference_rms + integer :: tone_index + + allocate(wave(720000), reference(720000)) + call init_cacb(nfft1) + call set_tone(k_auto, 1000) + cb = cmplx(1000000., -1000000.) + + call build_q65_samples(k_auto,nfft2,df,.false.,0,0.0,reference) + call require(maxval(abs(int(reference))) < 1000, 'X-only samples do not clip') + call require(all(reference(2*nfft2+1:) == 0), '56-second samples have a zero tail') + call expect_tone(reference, 1.0_real64, 'automatic center preserves 1000 Hz level and phase') + reference_rms = rms(reference) + + cb = cmplx(-2000000., 3000000.) + call build_q65_samples(k_auto,nfft2,df,.false.,180,45.0,wave) + call require(all(wave == reference), 'single-polarization mode ignores Y') + + cb = ca + call build_q65_samples(k_auto,nfft2,df,.true.,0,45.0,wave) + call expect_tone(wave, sqrt(2.0_real64), 'equal X and Y combine coherently') + + cb = -ca + call build_q65_samples(k_auto,nfft2,df,.true.,0,45.0,wave) + call require(rms(wave) < 1.0_real64, 'opposite-phase Y cancels without correction') + call build_q65_samples(k_auto,nfft2,df,.true.,180,45.0,wave) + call expect_tone(wave, sqrt(2.0_real64), '180-degree correction restores opposite-phase Y') + + tone_index = k_auto + nint(1000.0/df) + cb = 0. + cb(tone_index) = cmplx(0.0, -input_amplitude) + call build_q65_samples(k_auto,nfft2,df,.true.,90,45.0,wave) + call expect_tone(wave, sqrt(2.0_real64), '90-degree correction preserves rotation sign') + + call set_tone(k_manual, 1000) + call build_q65_samples(k_manual,nfft2,df,.false.,0,0.0,wave) + call expect_tone(wave, 1.0_real64, 'shifted extraction offset preserves level and phase') + + call expect_filter(250, 0.5_real64) + call expect_filter(2750, 0.5_real64) + call expect_filter(3500, 0.0_real64) + + print '(a)', 'MAP65 Q65 sample handoff contracts passed.' + +contains + + subroutine set_tone(center, frequency) + integer, intent(in) :: center, frequency + ca = 0. + ca(center+nint(real(frequency)/df)) = cmplx(input_amplitude, 0.0) + end subroutine set_tone + + subroutine expect_tone(samples, gain, description) + integer(int16), intent(in) :: samples(:) + real(real64), intent(in) :: gain + character(len=*), intent(in) :: description + real(real64) :: expected + integer :: i + + do i = 1, sample_rate + expected = gain * 2.0_real64 * real(input_amplitude, real64) / real(nfft2, real64) * & + cos(2.0_real64*pi*1000.0_real64*real(i, real64)/real(sample_rate, real64)) + if (abs(int(samples(i))-nint(expected)) > 2) then + print '(a,i0)', 'FAIL: '//description//' at sample ', i + error stop 1 + endif + enddo + end subroutine expect_tone + + subroutine expect_filter(frequency, expected_ratio) + integer, intent(in) :: frequency + real(real64), intent(in) :: expected_ratio + real(real64) :: ratio + + call set_tone(k_auto, frequency) + call build_q65_samples(k_auto,nfft2,df,.false.,0,0.0,wave) + ratio = rms(wave)/reference_rms + call require(abs(ratio-expected_ratio) < 0.01_real64, 'filter response at '//frequency_text(frequency)) + end subroutine expect_filter + + function frequency_text(frequency) result(value) + integer, intent(in) :: frequency + character(len=16) :: value + write(value, '(i0,a)') frequency, ' Hz' + end function frequency_text + + real(real64) function rms(samples) + integer(int16), intent(in) :: samples(:) + integer :: i + rms = 0.0_real64 + do i=1,sample_rate + rms = rms + real(samples(i),real64)**2 + enddo + rms = sqrt(rms/real(sample_rate,real64)) + end function rms + + subroutine require(condition,description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine require +end program test_map65_q65_handoff diff --git a/tests/unit/map65/test_map65_symspec_contract.f90 b/tests/unit/map65/test_map65_symspec_contract.f90 new file mode 100644 index 00000000..d9267268 --- /dev/null +++ b/tests/unit/map65/test_map65_symspec_contract.f90 @@ -0,0 +1,118 @@ +program test_map65_symspec_contract + use iso_fortran_env, only: int8, real32 + use, intrinsic :: ieee_arithmetic, only: ieee_quiet_nan, ieee_value + use datcom_ptrs_mod, only: dd, ss, savg + use npar_ptrs_mod, only: set_runtime_params + use symspec_mod, only: symspec + implicit none + + integer, parameter :: bins(5) = [4000, 4300, 4600, 4900, 5200] + real(real32), parameter :: pi = 3.14159265358979323846_real32 + integer :: rate, fft_size, i, k, ihsym, nzap, nkhz + integer(int8) :: lstrong(0:1023) + character(len=16) :: rate_text + real(real32), allocatable :: waterfall(:) + real(real32) :: gainx, gainy, phasex, phasey, rejectx, rejecty, pxdb, pydb, slimit + real(real32) :: power(4,5), expected(4,3), phase, nan_value + complex(real32) :: x, y + + call get_command_argument(1, rate_text) + read(rate_text, *) rate + call require(rate == 96000 .or. rate == 192000, 'supported sample rate') + fft_size = 32768 * (rate / 96000) + call set_runtime_params(rate, fft_size, 56 * rate) + allocate(dd(4, fft_size + 1024), ss(4, 1, fft_size), savg(4, fft_size), waterfall(fft_size)) + dd = 0.0 + ss = 0.0 + savg = 0.0 + + do i = 1, fft_size + 1024 + x = cmplx(0.0_real32, 0.0_real32, real32) + y = x + phase = 2.0_real32 * pi * real(i - 1, real32) / real(fft_size, real32) + x = x + tone(bins(1), phase) + x = x + tone(bins(2), phase) + y = y + tone(bins(2), phase) + x = x + tone(bins(3), phase) + y = y - tone(bins(3), phase) + x = x + 2.0_real32 * tone(bins(4), phase) + x = x + tone(bins(5), phase + 0.71_real32) + dd(1,i) = real(x) + dd(2,i) = aimag(x) + dd(3,i) = real(y) + dd(4,i) = aimag(y) + end do + + call spectrum(fft_size + 512, 1) + call require(ihsym == 1, 'first completed row') + do i = 1, 5 + call require(abs(maxloc(ss(1,1,:), dim=1) - (bins(4) + 1)) <= 1, & + 'strongest X frequency bin') + power(:,i) = ss(:,1,bins(i)+1) + call require(all(abs(savg(:,bins(i)+1) - power(:,i)) <= 0.0001_real32 * max(1.0_real32, maxval(power(:,i)))), & + 'savg accumulates completed row') + end do + expected(:,1) = [1.0_real32, 0.5_real32, 0.0_real32, 0.5_real32] + expected(:,2) = [1.0_real32, 2.0_real32, 1.0_real32, 0.0_real32] + expected(:,3) = [1.0_real32, 0.0_real32, 1.0_real32, 2.0_real32] + do i = 1, 3 + call require(all(abs(power(:,i) / power(1,i) - expected(:,i)) < 0.03_real32), & + 'polarization relative powers') + end do + call require(abs(power(1,4) / power(1,1) - 4.0_real32) < 0.12_real32, 'amplitude squared power') + call require(abs(power(1,5) / power(1,1) - 1.0_real32) < 0.03_real32, 'phase preserves power') + + nan_value = ieee_value(0.0_real32, ieee_quiet_nan) + dd = 0.0 + do i = 1, fft_size + 1024 + x = tone(bins(1), 2.0_real32*pi*real(i-1, real32)/real(fft_size, real32)) + dd(1,i) = real(x) + dd(2,i) = aimag(x) + end do + dd(3:4,:) = nan_value + call spectrum(fft_size, 0) + call require(ihsym == 1, 'single-polarization reset row') + call require(abs(maxloc(ss(1,1,:), dim=1) - (bins(1) + 1)) <= 1, 'single-polarization frequency bin') + call require(abs(ss(1,1,bins(1)+1) / power(1,1) - 1.0_real32) < 0.03_real32, & + 'poisoned Y cannot affect X power') + call require(abs(savg(1,bins(1)+1) / ss(1,1,bins(1)+1) - 1.0_real32) < 0.001_real32, & + 'single-polarization savg reset') + print '(a,i0)', 'MAP65 symspec contract passed at ', rate + +contains + + function tone(bin, angle) result(value) + integer, intent(in) :: bin + real(real32), intent(in) :: angle + complex(real32) :: value + real(real32) :: theta + + theta = real(bin, real32) * angle + value = 300.0_real32 * cmplx(cos(theta), -sin(theta), real32) + end function tone + + subroutine spectrum(sample_count, polarization_count) + integer, intent(in) :: sample_count, polarization_count + + k = sample_count + ihsym = 0 + nzap = 0 + gainx = 1.0 + gainy = 1.0 + phasex = 0.0 + phasey = 0.0 + slimit = 0.0 + call symspec(k, polarization_count, 1, 0, 40, 0, 0, 0, gainx, gainy, phasex, phasey, & + rejectx, rejecty, pxdb, pydb, waterfall, nkhz, ihsym, nzap, slimit, lstrong) + end subroutine spectrum + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require +end program test_map65_symspec_contract diff --git a/tests/unit/map65/windows_fake/windows.h b/tests/unit/map65/windows_fake/windows.h new file mode 100644 index 00000000..3c1ab60c --- /dev/null +++ b/tests/unit/map65/windows_fake/windows.h @@ -0,0 +1,29 @@ +#ifndef MAP65_TEST_WINDOWS_H +#define MAP65_TEST_WINDOWS_H + +#include + +typedef void *HANDLE; +typedef uint32_t DWORD; +typedef int BOOL; + +#define INVALID_HANDLE_VALUE ((HANDLE)(intptr_t)-1) +#define GENERIC_WRITE 0x40000000 +#define OPEN_EXISTING 3 +#define FILE_ATTRIBUTE_NORMAL 0x80 +#define SETRTS 3 +#define CLRRTS 4 +#define SETDTR 5 +#define CLRDTR 6 +#define CLRBREAK 9 +#define ERROR_ACCESS_DENIED 5 +#define ERROR_GEN_FAILURE 31 +#define ERROR_NO_SUCH_DEVICE 433 +#define ERROR_DEVICE_NOT_CONNECTED 1167 + +HANDLE CreateFileA(const char *, DWORD, DWORD, void *, DWORD, DWORD, HANDLE); +BOOL EscapeCommFunction(HANDLE, DWORD); +BOOL CloseHandle(HANDLE); +DWORD GetLastError(void); + +#endif diff --git a/tests/unit/network/CMakeLists.txt b/tests/unit/network/CMakeLists.txt index 6087a11d..502a27c7 100644 --- a/tests/unit/network/CMakeLists.txt +++ b/tests/unit/network/CMakeLists.txt @@ -1,3 +1,10 @@ +add_executable (test_lotw_users + test_lotw_users.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp +) +target_link_libraries (test_lotw_users wsjt_qt Boost::log_setup Qt5::Test Qt5::Network) +add_test (NAME test_lotw_users COMMAND test_lotw_users) + add_executable (test_pskreporter_ipfix test_pskreporter_ipfix.cpp ${CMAKE_SOURCE_DIR}/Network/PSKReporterIPFIX.cpp @@ -29,6 +36,15 @@ add_executable (test_map65_pskreporter_decode target_link_libraries (test_map65_pskreporter_decode Qt5::Test) add_test (NAME test_map65_pskreporter_decode COMMAND test_map65_pskreporter_decode) +add_executable (test_map65_livecq_decode + test_map65_livecq_decode.cpp + ${CMAKE_SOURCE_DIR}/map65/livecq_decode.cpp + ${CMAKE_SOURCE_DIR}/Network/DecodedTime.cpp + ${CMAKE_SOURCE_DIR}/validators/LiveCQCallsign.cpp +) +target_link_libraries (test_map65_livecq_decode Qt5::Test) +add_test (NAME test_map65_livecq_decode COMMAND test_map65_livecq_decode) + add_executable (test_wsprnet_upload test_wsprnet_upload.cpp ${CMAKE_SOURCE_DIR}/Network/wsprnet.cpp @@ -36,6 +52,13 @@ add_executable (test_wsprnet_upload target_link_libraries (test_wsprnet_upload Qt5::Test Qt5::Network) add_test (NAME test_wsprnet_upload COMMAND test_wsprnet_upload) +add_executable (test_livecq_upload + test_livecq_upload.cpp + ${CMAKE_SOURCE_DIR}/Network/LiveCQUpload.cpp + ) +target_link_libraries (test_livecq_upload Qt5::Test Qt5::Network) +add_test (NAME test_livecq_upload COMMAND test_livecq_upload) + add_executable (test_message_client_replay test_message_client_replay.cpp ) @@ -64,6 +87,14 @@ target_include_directories (test_cloudlog_connection_check PRIVATE ${CMAKE_BINAR target_link_libraries (test_cloudlog_connection_check Boost::log Qt5::Test Qt5::Network Qt5::Widgets) add_test (NAME test_cloudlog_connection_check COMMAND test_cloudlog_connection_check) +add_executable (test_sample_downloader + test_sample_downloader.cpp + ${CMAKE_SOURCE_DIR}/SampleDownloader/RemoteFile.cpp + ) +target_include_directories (test_sample_downloader PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_sample_downloader Qt5::Test Qt5::Network) +add_test (NAME test_sample_downloader COMMAND test_sample_downloader) + if (WSJT_ENABLE_TSAN) set (wsjt_tsan_network_test_environment "QT_QPA_PLATFORM=offscreen" diff --git a/tests/unit/network/test_livecq_upload.cpp b/tests/unit/network/test_livecq_upload.cpp new file mode 100644 index 00000000..7976c127 --- /dev/null +++ b/tests/unit/network/test_livecq_upload.cpp @@ -0,0 +1,257 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "Network/LiveCQUpload.hpp" + +namespace +{ + class FakeReply final + : public QNetworkReply + { + public: + FakeReply (QNetworkRequest const& request, QNetworkReply::NetworkError error, + QString const& error_string, QObject *parent = nullptr) + : QNetworkReply {parent} + , error_ {error} + , error_string_ {error_string} + { + setRequest (request); + setUrl (request.url ()); + setOperation (QNetworkAccessManager::PostOperation); + open (QIODevice::ReadOnly | QIODevice::Unbuffered); + } + + void abort () override + { + error_ = QNetworkReply::OperationCanceledError; + error_string_ = "aborted"; + finish (); + } + + void finish () + { + if (isFinished ()) + { + return; + } + setFinished (true); + if (QNetworkReply::NoError != error_) + { + setError (error_, error_string_); + } + Q_EMIT finished (); + } + + void setHttpStatus (int status) + { + setAttribute (QNetworkRequest::HttpStatusCodeAttribute, status); + } + + protected: + qint64 readData (char *, qint64) override + { + return -1; + } + + private: + QNetworkReply::NetworkError error_; + QString error_string_; + }; + + class FakeTransport final + : public QObject + , public LiveCQUpload::Transport + { + public: + struct Request + { + QUrl url; + QByteArray body; + QString content_type; + QByteArray user_agent; + }; + + explicit FakeTransport (QObject *parent = nullptr) + : QObject {parent} + { + } + + QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) override + { + Request recorded; + recorded.url = request.url (); + recorded.body = body; + recorded.content_type + = request.header (QNetworkRequest::ContentTypeHeader).toString (); + recorded.user_agent = request.rawHeader ("User-Agent"); + requests.append (recorded); + + auto *reply = new FakeReply {request, error_, error_string_, this}; + replies.append (reply); + if (auto_finish) + { + QTimer::singleShot (0, reply, [reply] () { reply->finish (); }); + } + return reply; + } + + QList requests; + QList replies; + bool auto_finish {true}; + QNetworkReply::NetworkError error_ {QNetworkReply::NoError}; + QString error_string_; + }; + + QUrlQuery spotQuery () + { + QUrlQuery query; + query.addQueryItem ("skedfreq", "50313.0"); + query.addQueryItem ("callsign", "K1ABC"); + query.addQueryItem ("apptype", "MAP65"); + return query; + } +} + +class TestLiveCQUpload final + : public QObject +{ + Q_OBJECT + +private slots: + void postsSpotToEndpoint () + { + FakeTransport transport; + LiveCQUpload upload {&transport, false}; + QVERIFY (upload.setEndpoint (QUrl {"https://w3sz.com/livecq_update.php"})); + upload.setUserAgent ("WSJT-X/test"); + + QSignalSpy posted {&upload, &LiveCQUpload::spotPosted}; + upload.postSpot (spotQuery ()); + + QCOMPARE (transport.requests.size (), 1); + auto const& request = transport.requests.first (); + QCOMPARE (request.url.host (), QString {"w3sz.com"}); + QCOMPARE (request.url.path (), QString {"/livecq_update.php"}); + QVERIFY (request.body.contains ("skedfreq=50313.0")); + QVERIFY (request.body.contains ("apptype=MAP65")); + QCOMPARE (request.content_type, QString {"application/x-www-form-urlencoded"}); + QCOMPARE (request.user_agent, QByteArray {"WSJT-X/test"}); + + QTRY_COMPARE (posted.count (), 1); + } + + void rejectsPlaintextEndpoint () + { + FakeTransport transport; + LiveCQUpload upload {&transport, false}; + QSignalSpy errors {&upload, &LiveCQUpload::errorOccurred}; + + QVERIFY (!upload.setEndpoint (QUrl {"http://w3sz.com/livecq_update.php"})); + QCOMPARE (errors.count (), 1); + QVERIFY (!upload.endpoint ().isValid ()); + + upload.postSpot (spotQuery ()); + QCOMPARE (transport.requests.size (), 0); + } + + void rejectsInvalidEndpoint () + { + FakeTransport transport; + LiveCQUpload upload {&transport, false}; + QSignalSpy errors {&upload, &LiveCQUpload::errorOccurred}; + QVERIFY (!upload.setEndpoint (QUrl {})); + QCOMPARE (errors.count (), 1); + } + + void rejectsPostBeforeEndpointSet () + { + FakeTransport transport; + LiveCQUpload upload {&transport, false}; + QSignalSpy errors {&upload, &LiveCQUpload::errorOccurred}; + + upload.postSpot (spotQuery ()); + QCOMPARE (errors.count (), 1); + QCOMPARE (transport.requests.size (), 0); + } + + void postIsAsynchronous () + { + FakeTransport transport; + transport.auto_finish = false; + LiveCQUpload upload {&transport, false}; + QVERIFY (upload.setEndpoint (QUrl {"https://w3sz.com/livecq_update.php"})); + + QSignalSpy posted {&upload, &LiveCQUpload::spotPosted}; + upload.postSpot (spotQuery ()); + + QCOMPARE (transport.requests.size (), 1); + QCOMPARE (posted.count (), 0); + QCOMPARE (transport.replies.size (), 1); + transport.replies.first ()->finish (); + QCOMPARE (posted.count (), 1); + } + + void reportsReplyError () + { + FakeTransport transport; + transport.error_ = QNetworkReply::HostNotFoundError; + transport.error_string_ = "host not found"; + LiveCQUpload upload {&transport, false}; + QVERIFY (upload.setEndpoint (QUrl {"https://w3sz.com/livecq_update.php"})); + + QSignalSpy errors {&upload, &LiveCQUpload::errorOccurred}; + upload.postSpot (spotQuery ()); + QTRY_COMPARE (errors.count (), 1); + } + + void reportsHttpErrorStatus () + { + FakeTransport transport; + transport.auto_finish = false; + LiveCQUpload upload {&transport, false}; + QVERIFY (upload.setEndpoint (QUrl {"https://w3sz.com/livecq_update.php"})); + + QSignalSpy posted {&upload, &LiveCQUpload::spotPosted}; + QSignalSpy errors {&upload, &LiveCQUpload::errorOccurred}; + upload.postSpot (spotQuery ()); + QCOMPARE (transport.replies.size (), 1); + transport.replies.first ()->setHttpStatus (500); + transport.replies.first ()->finish (); + QCOMPARE (posted.count (), 0); + QCOMPARE (errors.count (), 1); + } + + void abortsOutstandingRequestsOnDestruction () + { + FakeTransport transport; + transport.auto_finish = false; + auto upload = std::make_unique (&transport, false); + QVERIFY (upload->setEndpoint (QUrl {"https://w3sz.com/livecq_update.php"})); + upload->postSpot (spotQuery ()); + QCOMPARE (transport.replies.size (), 1); + auto *reply = transport.replies.first (); + + upload.reset (); + QCOMPARE (reply->error (), QNetworkReply::OperationCanceledError); + } + + void runsOnCallingThread () + { + FakeTransport transport; + LiveCQUpload upload {&transport, false}; + QCOMPARE (upload.thread (), QThread::currentThread ()); + QVERIFY (upload.findChildren ().isEmpty ()); + } +}; + +QTEST_MAIN (TestLiveCQUpload) + +#include "test_livecq_upload.moc" diff --git a/tests/unit/network/test_lotw_users.cpp b/tests/unit/network/test_lotw_users.cpp new file mode 100644 index 00000000..843e2313 --- /dev/null +++ b/tests/unit/network/test_lotw_users.cpp @@ -0,0 +1,312 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef Q_OS_UNIX +#include +#endif + +#include "Network/LotWUsers.hpp" + +namespace +{ + bool write_csv (QString const& path, QByteArray const& data) + { + QFile file {path}; + return file.open (QIODevice::WriteOnly) && file.write (data) == data.size (); + } + + QByteArray record (char const * call, QDate const& date) + { + return QByteArray {call} + ',' + date.toString (Qt::ISODate).toLatin1 () + ",12:00:00\n"; + } + + QDate utc_today () + { + return QDateTime::currentDateTimeUtc ().date (); + } + + class FailingReply final : public QNetworkReply + { + public: + FailingReply (QNetworkAccessManager::Operation operation, QNetworkRequest const& request, QObject * parent) + : QNetworkReply {parent} + { + setOperation (operation); + setRequest (request); + setUrl (request.url ()); + open (QIODevice::ReadOnly | QIODevice::Unbuffered); + QTimer::singleShot (0, this, [this] { + if (isFinished ()) return; + setError (QNetworkReply::HostNotFoundError, "Simulated download failure"); +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) + Q_EMIT errorOccurred (QNetworkReply::HostNotFoundError); +#else + Q_EMIT error (QNetworkReply::HostNotFoundError); +#endif + setFinished (true); + Q_EMIT finished (); + }); + } + + void abort () override + { + if (isFinished ()) return; + setError (QNetworkReply::OperationCanceledError, "Request aborted"); + setFinished (true); + Q_EMIT finished (); + } + + private: + qint64 readData (char *, qint64) override { return -1; } + }; + + class FailingNetworkAccessManager final : public QNetworkAccessManager + { + protected: + QNetworkReply * createRequest (Operation operation, QNetworkRequest const& request, + QIODevice * outgoing_data) override + { + Q_UNUSED (outgoing_data); + return new FailingReply {operation, request, this}; + } + }; + +#ifdef Q_OS_UNIX + class ScopedTimeZone final + { + public: + explicit ScopedTimeZone (QByteArray const& value) + : previous_ {qgetenv ("TZ")} + , was_set_ {qEnvironmentVariableIsSet ("TZ")} + { + qputenv ("TZ", value); + tzset (); + } + + ~ScopedTimeZone () + { + if (was_set_) qputenv ("TZ", previous_); + else qunsetenv ("TZ"); + tzset (); + } + + private: + QByteArray previous_; + bool was_set_; + }; +#endif +} + +class TestLotWUsers final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void upload_age_requires_valid_past_activity () + { + for (int attempt = 0; attempt < 3; ++attempt) + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const path = directory.filePath ("users.csv"); + auto const today = utc_today (); + auto const date = today.toString (Qt::ISODate).toLatin1 (); + QVERIFY (write_csv (path, record ("RECENT", today) + record ("BOUNDARY", today.addDays (-30)) + + record ("STALE", today.addDays (-31)) + record ("FUTURE", today.addDays (1)) + + record ("DUPLICATE", today.addDays (-60)) + record ("DUPLICATE", today) + + "TWO_FIELD," + date + '\n' + "PADDED, " + date + " ,12:00:00\n" + + "DUPLICATE,not-a-date,12:00:00\nINVALID,2025-02-30,12:00:00\nMALFORMED\n" + + record ("", today))); + QNetworkAccessManager network; + LotWUsers users {&network}; + QSignalSpy finished {&users, &LotWUsers::load_finished}; + users.set_age_constraint (30); + users.set_local_file_path (path); + users.load ({}, false); + QTRY_COMPARE (finished.size (), 1); + auto const recent = users.user ("RECENT"); + auto const boundary = users.user ("BOUNDARY"); + auto const stale = users.user ("STALE"); + auto const future = users.user ("FUTURE"); + auto const duplicate = users.user ("DUPLICATE"); + auto const two_field = users.user ("TWO_FIELD"); + auto const padded = users.user ("PADDED"); + auto const invalid = users.user ("INVALID"); + auto const malformed = users.user ("MALFORMED"); + auto const empty = users.user (""); + auto const absent = users.user ("ABSENT"); + users.set_age_constraint (31); + auto const stale_at_31 = users.user ("STALE"); + users.set_age_constraint (0); + auto const recent_at_0 = users.user ("RECENT"); + auto const boundary_at_0 = users.user ("BOUNDARY"); + if (utc_today () != today) continue; + QVERIFY (recent); + QVERIFY (boundary); + QVERIFY (!stale); + QVERIFY (!future); + QVERIFY (duplicate); + QVERIFY (two_field); + QVERIFY (padded); + QVERIFY (!invalid); + QVERIFY (!malformed); + QVERIFY (!empty); + QVERIFY (!absent); + QVERIFY (stale_at_31); + QVERIFY (recent_at_0); + QVERIFY (!boundary_at_0); + return; + } + QFAIL ("UTC date changed during each attempt"); + } + + void utc_upload_dates_do_not_use_local_day () + { +#ifdef Q_OS_UNIX + ScopedTimeZone time_zone {"UTC+24"}; + auto const today = utc_today (); + if (QDate::currentDate () != today.addDays (-1)) QSKIP ("Local time zone override is unavailable"); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const path = directory.filePath ("users.csv"); + QVERIFY (write_csv (path, record ("TODAY_UTC", today))); + QNetworkAccessManager network; + LotWUsers users {&network}; + QSignalSpy finished {&users, &LotWUsers::load_finished}; + users.set_age_constraint (0); + users.set_local_file_path (path); + users.load ({}, false); + QTRY_COMPARE (finished.size (), 1); + auto const uploaded_today = users.user ("TODAY_UTC"); + if (utc_today () != today) QSKIP ("UTC date changed during the test"); + QVERIFY (uploaded_today); +#else + QSKIP ("Local time zone override requires a Unix platform"); +#endif + } + + void failed_fetch_preserves_in_flight_cache_load () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const path = directory.filePath ("users.csv"); + QVERIFY (write_csv (path, record ("CACHED", utc_today ()))); + FailingNetworkAccessManager network; + LotWUsers users {&network}; + QSignalSpy errors {&users, &LotWUsers::LotW_users_error}; + QSignalSpy finished {&users, &LotWUsers::load_finished}; + users.set_local_file_path (path); + users.load ({}, false); + users.load ("https://example.invalid/lotw-user-activity.csv", true, true); + QTRY_COMPARE (errors.size (), 1); + QTRY_COMPARE (finished.size (), 1); + QVERIFY (users.user ("CACHED")); + } + + void completion_publishes_once_on_owner_thread () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const path = directory.filePath ("users.csv"); + QVERIFY (write_csv (path, record ("FIRST", QDate::currentDate ()) + + record ("LAST", QDate::currentDate ()))); + QNetworkAccessManager network; + LotWUsers users {&network}; + std::atomic wrong_thread {false}; + bool complete_snapshot {false}; + auto * owner_thread = users.thread (); + connect (&users, &LotWUsers::load_finished, &users, [&] { + if (QThread::currentThread () != owner_thread) wrong_thread.store (true); + else complete_snapshot = users.user ("FIRST") && users.user ("LAST"); + }, Qt::DirectConnection); + int completion_count {0}; + connect (&users, &LotWUsers::load_finished, &users, [&] { + ++completion_count; + }, Qt::QueuedConnection); + users.set_local_file_path (path); + users.load ({}, false); + QTRY_VERIFY (completion_count > 0); + QVERIFY (!wrong_thread.load ()); + QVERIFY (complete_snapshot); + QCOMPARE (completion_count, 1); + QVERIFY (users.user ("FIRST")); + QVERIFY (!users.user ("ABSENT")); + QCoreApplication::processEvents (); + QCOMPARE (completion_count, 1); + } + + void reload_replaces_snapshot_and_coalesces_pending_requests () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const initial = directory.filePath ("initial.csv"); + auto const obsolete = directory.filePath ("obsolete.csv"); + auto const latest = directory.filePath ("latest.csv"); + QVERIFY (write_csv (initial, record ("INITIAL", QDate::currentDate ()))); + QVERIFY (write_csv (obsolete, record ("OBSOLETE", QDate::currentDate ()))); + QVERIFY (write_csv (latest, record ("LATEST", QDate::currentDate ()))); + QNetworkAccessManager network; + LotWUsers users {&network}; + users.set_local_file_path (initial); + users.load ({}, false); + QTRY_VERIFY (users.user ("INITIAL")); + QCoreApplication::processEvents (); + int completion_count {0}; + connect (&users, &LotWUsers::load_finished, &users, [&] { + ++completion_count; + }, Qt::QueuedConnection); + + users.set_local_file_path (obsolete); + users.load ({}, false); + users.set_local_file_path (latest); + users.load ({}, false); + QVERIFY (users.user ("INITIAL")); + QTRY_VERIFY (completion_count > 0); + QVERIFY (users.user ("LATEST")); + QVERIFY (!users.user ("INITIAL")); + QVERIFY (!users.user ("OBSOLETE")); + QCoreApplication::processEvents (); + QCOMPARE (completion_count, 1); + } + + void failed_reload_retains_previous_snapshot () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const path = directory.filePath ("users.csv"); + QVERIFY (write_csv (path, record ("RETAINED", QDate::currentDate ()))); + QNetworkAccessManager network; + LotWUsers users {&network}; + users.set_local_file_path (path); + users.load ({}, false); + QTRY_VERIFY (users.user ("RETAINED")); + QCoreApplication::processEvents (); + int error_count {0}; + connect (&users, &LotWUsers::LotW_users_error, &users, [&] { + ++error_count; + }, Qt::QueuedConnection); + int completion_count {0}; + connect (&users, &LotWUsers::load_finished, &users, [&] { + ++completion_count; + }, Qt::QueuedConnection); + users.set_local_file_path (directory.path ()); + users.load ({}, false); + QTRY_COMPARE (error_count, 1); + QTRY_COMPARE (completion_count, 1); + QVERIFY (users.user ("RETAINED")); + } +}; + +QTEST_GUILESS_MAIN (TestLotWUsers) + +#include "test_lotw_users.moc" diff --git a/tests/unit/network/test_map65_livecq_decode.cpp b/tests/unit/network/test_map65_livecq_decode.cpp new file mode 100644 index 00000000..d9fe9775 --- /dev/null +++ b/tests/unit/network/test_map65_livecq_decode.cpp @@ -0,0 +1,196 @@ +#include + +#include +#include + +#include "map65/livecq_decode.hpp" + +namespace +{ + QDateTime nowUtc() + { + return {QDate {2026, 8, 17}, QTime {12, 34, 56}, Qt::UTC}; + } + + QString decodeLine(QStringList const& message, QString const& time = "1234", + QString const& polarization = "0.1") + { + return (QStringList {"50313.0", "1000", polarization, time, "-12"} + message) + .join(' '); + } +} + +class TestMap65LiveCQDecode final : public QObject +{ + Q_OBJECT + +private slots: + void parsesSupportedLayouts() + { + QStringList seen; + auto const spots = Map65LiveCQ::parseSpots( + { + decodeLine({"CQ", "K1ABC", "1200.0", "#A"}), + decodeLine({"CQ", "K1ABC", "FN20", "1200.0", ":B"}), + decodeLine({"CQ", "DX", "K1ABC", "1200.0", "#C"}), + decodeLine({"CQ", "DX", "K1ABC", "FN20", "1200.0", ":D"}) + }, "N0CALL", "FN21", false, nowUtc(), seen); + + QCOMPARE(spots.size(), 4); + QCOMPARE(spots.at(0).callsign, QString {"K1ABC"}); + QCOMPARE(spots.at(0).grid, QString {"--"}); + QCOMPARE(spots.at(0).mode, QString {"JT65A"}); + QCOMPARE(spots.at(0).deltaTime, QString {"1200.0"}); + QCOMPARE(spots.at(1).callsign, QString {"K1ABC"}); + QCOMPARE(spots.at(1).grid, QString {"FN20"}); + QCOMPARE(spots.at(1).mode, QString {"Q65-60B"}); + QCOMPARE(spots.at(2).callsign, QString {"K1ABC"}); + QCOMPARE(spots.at(2).grid, QString {"--"}); + QCOMPARE(spots.at(2).mode, QString {"JT65C"}); + QCOMPARE(spots.at(3).callsign, QString {"K1ABC"}); + QCOMPARE(spots.at(3).grid, QString {"FN20"}); + QCOMPARE(spots.at(3).mode, QString {"Q65-60D"}); + } + + void rejectsShortOrMalformedLines() + { + const auto malformed = QStringList { + QString {}, + "50313.0 1000 0.1", + "50313.0 1000 0.1 1234 -12", + "50313.0 1000 0.1 1234 -12 CQ", + "50313.0 1000 0.1 1234 -12 CQ K1ABC", + "50313.0 1000 0.1 1234 -12 CQ K1ABC 1200.0", + decodeLine({"CQ", "K1ABC", "not-a-time", "#A"}), + decodeLine({"CQ", "K1ABC", "1200.0", "?A"}) + }; + + for (auto const& line : malformed) { + QStringList seen; + QVERIFY2(Map65LiveCQ::parseSpots( + {line}, "N0CALL", "FN21", false, nowUtc(), seen).isEmpty(), + qPrintable(line)); + } + } + + void rejectsNonReportableMessageTypes() + { + for (auto const& type : {QString {"DE"}, QString {"K1ABC"}, QString {"TU"}}) { + QStringList seen; + QVERIFY(Map65LiveCQ::parseSpots( + {decodeLine({type, "K1ABC", "1200.0", "#A"})}, + "N0CALL", "FN21", false, nowUtc(), seen).isEmpty()); + } + } + + void rejectsInvalidCallsigns() + { + for (auto const& callsign : {QString {"KABC"}, QString {"N5"}, QString {"Q1ABC"}}) { + QStringList seen; + QVERIFY2(Map65LiveCQ::parseSpots( + {decodeLine({"CQ", callsign, "1200.0", "#A"})}, + "N0CALL", "FN21", false, nowUtc(), seen).isEmpty(), + qPrintable(callsign)); + } + } + + void requiresReceiverCallAndGrid() + { + auto const line = decodeLine({"CQ", "K1ABC", "1200.0", "#A"}); + QStringList seen; + QVERIFY(Map65LiveCQ::parseSpots( + {line}, "NO", "FN21", false, nowUtc(), seen).isEmpty()); + QVERIFY(Map65LiveCQ::parseSpots( + {line}, "N0CALL", "FN", false, nowUtc(), seen).isEmpty()); + QVERIFY(seen.isEmpty()); + } + + void defaultsTransmitPolarizationWhenXpolDisabled() + { + QStringList seen; + auto const spots = Map65LiveCQ::parseSpots( + {decodeLine({"CQ", "K1ABC", "FN20", "1200.0", ":B", "V"})}, + "N0CALL", "FN21", false, nowUtc(), seen); + QCOMPARE(spots.size(), 1); + QCOMPARE(spots.first().polarization, QString {"--"}); + QCOMPARE(spots.first().transmitPolarization, QString {"--"}); + } + + void mapsPolarizationWhenXpolEnabled() + { + QStringList seen; + auto const spots = Map65LiveCQ::parseSpots( + {decodeLine({"CQ", "K1ABC", "FN20", "1200.0", ":B", "V"}, "1234", "0.7")}, + "N0CALL", "FN21", true, nowUtc(), seen); + QCOMPARE(spots.size(), 1); + QCOMPARE(spots.first().polarization, QString {"0.7"}); + QCOMPARE(spots.first().transmitPolarization, QString {"V"}); + } + + void mapsPolarizationWhenXpolEnabledForNoGridLayout() + { + QStringList seen; + auto const spots = Map65LiveCQ::parseSpots( + {decodeLine({"CQ", "K1ABC", "1200.0", "#A"}, "1234", "0.7")}, + "N0CALL", "FN21", true, nowUtc(), seen); + QCOMPARE(spots.size(), 1); + QCOMPARE(spots.first().polarization, QString {"0.7"}); + QCOMPARE(spots.first().transmitPolarization, QString {"--"}); + } + + void timestampIsUtc() + { + QStringList seen; + auto const spots = Map65LiveCQ::parseSpots( + {decodeLine({"CQ", "K1ABC", "1200.0", "#A"})}, + "N0CALL", "FN21", false, nowUtc(), seen); + QCOMPARE(spots.size(), 1); + auto const expected = QDateTime {QDate {2026, 8, 17}, QTime {12, 34, 0}, Qt::UTC}; + QCOMPARE(spots.first().utcDateTime, expected); + } + + void buildsExpectedQueryFields() + { + QStringList seen; + auto const spots = Map65LiveCQ::parseSpots( + {decodeLine({"CQ", "K1ABC", "FN20", "1200.0", "#A"})}, + "N0CALL", "FN21", false, nowUtc(), seen); + QCOMPARE(spots.size(), 1); + + auto const query = Map65LiveCQ::spotQuery(spots.first(), "N0CALL", "FN21"); + auto const item = [&query](QString const& key) { + return query.queryItemValue(key, QUrl::FullyDecoded); + }; + QCOMPARE(item("skedfreq"), QString {"50313.0"}); + QCOMPARE(item("rxfreq"), QString {"1000"}); + QCOMPARE(item("rpol"), QString {"--"}); + QCOMPARE(item("dt"), QString {"1200.0"}); + QCOMPARE(item("dB"), QString {"-12"}); + QCOMPARE(item("msgtype"), QString {"CQ"}); + QCOMPARE(item("callsign"), QString {"K1ABC"}); + QCOMPARE(item("grid"), QString {"FN20"}); + QCOMPARE(item("mode"), QString {"JT65A"}); + QCOMPARE(item("utcdatetime"), QString {"2026-08-17T12:34:00Z"}); + QCOMPARE(item("spotter"), QString {"N0CALL"}); + QCOMPARE(item("spottergrid"), QString {"FN21"}); + QCOMPARE(item("txpol"), QString {"--"}); + QCOMPARE(item("apptype"), QString {"MAP65"}); + } + + void deduplicatesSeenDecodes() + { + auto const first = decodeLine({"CQ", "K1ABC", "1200.0", "#A"}) + " trailing-one"; + auto const second = decodeLine({"CQ", "K1ABC", "1200.0", "#A"}) + " trailing-two"; + QCOMPARE(first.left(53), second.left(53)); + + QStringList seen; + auto const spots = Map65LiveCQ::parseSpots( + {first, second}, "N0CALL", "FN21", false, nowUtc(), seen); + QCOMPARE(spots.size(), 1); + QCOMPARE(seen.size(), 1); + } +}; + +QTEST_APPLESS_MAIN(TestMap65LiveCQDecode) + +#include "test_map65_livecq_decode.moc" diff --git a/tests/unit/network/test_sample_downloader.cpp b/tests/unit/network/test_sample_downloader.cpp new file mode 100644 index 00000000..690b08df --- /dev/null +++ b/tests/unit/network/test_sample_downloader.cpp @@ -0,0 +1,151 @@ +#include "wsjtx_config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "SampleDownloader.hpp" +#include "SampleDownloader/RemoteFile.hpp" + +namespace +{ + class UnsentReply final + : public QNetworkReply + { + public: + UnsentReply (QNetworkAccessManager::Operation operation, QNetworkRequest const& request, QObject * parent) + : QNetworkReply {parent} + { + setOperation (operation); + setRequest (request); + setUrl (request.url ()); + setError (QNetworkReply::OperationCanceledError, "not sent"); + setFinished (true); + } + + void abort () override {} + + private: + qint64 readData (char *, qint64) override { return -1; } + }; + + class NoTlsNetworkAccessManager final + : public QNetworkAccessManager + { + Q_OBJECT + + public: + QList requested; + + protected: + QNetworkReply * createRequest (Operation operation, QNetworkRequest const& request, QIODevice *) override + { + requested << request.url (); + return new UnsentReply {operation, request, this}; + } + + protected Q_SLOTS: + QStringList supportedSchemesImplementation () const + { + auto schemes = QNetworkAccessManager::supportedSchemesImplementation (); + schemes.removeAll ("https"); + return schemes; + } + }; + + class Listener final + : public RemoteFile::ListenerInterface + { + public: + void error (QString const& title, QString const& message) override + { + errors << title + ": " + message; + } + + void download_finished (bool success) override + { + finished << success; + } + + QStringList errors; + QList finished; + }; +} + +class TestSampleDownloader final + : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void unsaved_url_reads_as_pages () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QSettings settings {directory.filePath ("settings.ini"), QSettings::IniFormat}; + QCOMPARE (saved_samples_url (settings), QString {"https://wsjtx.github.io/wsjtx/"}); + } + + void saved_sourceforge_default_reads_as_pages () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QSettings settings {directory.filePath ("settings.ini"), QSettings::IniFormat}; + settings.setValue ("SamplesURL", "http://downloads.sourceforge.net/project/wsjt/"); + QCOMPARE (saved_samples_url (settings), QString {"https://wsjtx.github.io/wsjtx/"}); + } + + void custom_url_is_kept () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QSettings settings {directory.filePath ("settings.ini"), QSettings::IniFormat}; + settings.setValue ("SamplesURL", "https://mirror.example.org/wsjt/"); + QCOMPARE (saved_samples_url (settings), QString {"https://mirror.example.org/wsjt/"}); + } + + void default_url_is_not_saved () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QSettings settings {directory.filePath ("settings.ini"), QSettings::IniFormat}; + settings.setValue ("SamplesURL", "http://downloads.sourceforge.net/project/wsjt/"); + save_samples_url (settings, "https://wsjtx.github.io/wsjtx/"); + QVERIFY (!settings.contains ("SamplesURL")); + } + + void custom_url_is_saved () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QSettings settings {directory.filePath ("settings.ini"), QSettings::IniFormat}; + save_samples_url (settings, "https://mirror.example.org/wsjt/"); + QCOMPARE (settings.value ("SamplesURL").toString (), QString {"https://mirror.example.org/wsjt/"}); + } + + void https_without_tls_reports_tls_required () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + NoTlsNetworkAccessManager network; + QVERIFY (!network.supportedSchemes ().contains ("https")); + Listener listener; + RemoteFile file {&listener, &network, directory.filePath ("samples/contents_3.3.json")}; + file.sync (QUrl {"https://wsjtx.github.io/wsjtx/samples/contents_3.3.json"}); + QCOMPARE (network.requested, QList {}); + QCOMPARE (listener.finished, QList {false}); + QCOMPARE (listener.errors.size (), 1); + QVERIFY2 (listener.errors.first ().contains ("SSL/TLS"), qPrintable (listener.errors.first ())); + QVERIFY (!file.local ()); + } +}; + +QTEST_GUILESS_MAIN (TestSampleDownloader) + +#include "test_sample_downloader.moc" diff --git a/tests/unit/packjt77/CMakeLists.txt b/tests/unit/packjt77/CMakeLists.txt index 2ce41135..8f8904ef 100644 --- a/tests/unit/packjt77/CMakeLists.txt +++ b/tests/unit/packjt77/CMakeLists.txt @@ -70,6 +70,13 @@ wsjt_link_common_fortran (test_packjt77_hash_state) add_test (NAME test_packjt77_hash_state COMMAND test_packjt77_hash_state) +add_executable (test_packjt77_context_state + test_packjt77_context_state.f90) +target_include_directories (test_packjt77_context_state PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_packjt77_context_state) + +add_test (NAME test_packjt77_context_state COMMAND test_packjt77_context_state) + if (WSJT_BUILD_FORTRAN_OPENMP) add_executable (test_packjt77_concurrent_unpack test_packjt77_concurrent_unpack.f90) diff --git a/tests/unit/packjt77/test_packjt77_context_state.f90 b/tests/unit/packjt77/test_packjt77_context_state.f90 new file mode 100644 index 00000000..3360cb87 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_context_state.f90 @@ -0,0 +1,117 @@ +program test_packjt77_context_state + use packjt77 + implicit none + + type(pack77_state), target :: first, second + character(len=13), pointer :: saved_calls(:) + character(len=77) :: bits + character(len=37) :: message + character(len=37) :: input + character(len=13) :: call,resolved_call + integer :: i3,n3,status,n10,n12,n22 + logical :: ok + + calls10='' + calls12='' + calls22='' + ihash22=-1 + nzhash=0 + mycall13='' + dxcall13='' + + call='W7ABC' + n10=-99 + n12=-99 + n22=-99 + call save_hash_call_for_state(first,call,n10,n12,n22) + call initialize_pack77_state(second) + call require(first%calls12(n12).eq.call,'first state records the call') + call require(second%calls12(n12).eq.'','second state is independent') + call require(calls12(n12).eq.'','legacy store is independent') + + input='PJ2/W1AW RR73' + call pack77_for_state(first,input,i3,n3,bits, & + pack77_options(record_tx_hashes=.false.),status) + call require(status.eq.PACK77_STATUS_ENCODED,'explicit encode accepted') + call require(i3.eq.4.and.n3.eq.0,'explicit encode selected type 4') + call require(first%nzhash.eq.1.and.second%nzhash.eq.0.and.nzhash.eq.0, & + 'encode without TX recording preserves separate stores') + + call unpack77_for_state(second,bits,1,message,ok) + call require(ok.and.trim(message).eq.'PJ2/W1AW <...> RR73', & + 'second state initially lacks the hashed call') + + call unpack77_for_state(first,bits,1,message,ok) + call require(ok.and.trim(message).eq.'PJ2/W1AW RR73', & + 'first state resolves the hashed call') + call unpack77_for_state(second,bits,1,message,ok) + call require(ok.and.trim(message).eq.'PJ2/W1AW <...> RR73', & + 'second state remains unresolved') + call unpack77(bits,1,message,ok) + call require(ok.and.trim(message).eq.'PJ2/W1AW <...> RR73', & + 'legacy decode remains unresolved') + + call queue_hash_call_for_thread_for_state(second,call,2) + call require(second%calls12(n12).eq.'','thread fact waits for fold') + call fold_queued_calls_for_state(second,2) + call require(second%calls12(n12).eq.call,'thread fact folds into its state') + call require(calls12(n12).eq.'','thread fold does not mutate legacy store') + + call prepare_configured_decode_for_state(second,'N0AAA','N0BBB') + call require(second%mycall13_configured_set,'configured call belongs to state') + call require(.not.first%mycall13_configured_set, & + 'other state configured call remains clear') + call require(mycall13.eq.'','legacy configured call remains clear') + + n10=-99 + n12=-99 + n22=-99 + call save_hash_call_for_state(first,'<...> ',n10,n12,n22) + call require(n10.eq.-99.and.n12.eq.-99.and.n22.eq.-99, & + 'ignored calls leave hash outputs untouched') + + call pack77_for_state(second,'K1ABC W9XYZ FN42',i3,n3,bits,status=status) + call require(status.eq.PACK77_STATUS_ENCODED.and.i3.eq.1, & + 'explicit encode accepts an assumed-length message') + call require(nzhash.eq.0,'explicit encode leaves the legacy store untouched') + + call prepare_configured_decode_for_state(first,'N0AAA','N0BBB') + call queue_hash_call_for_thread_for_state(first,call,2) + saved_calls=>first%calls12 + call initialize_pack77_state(first) + call hash12_for_state(first,ihashcall(call,12),resolved_call) + call require(trim(resolved_call).eq.'<'//trim(call)//'>','initialization preserves learned calls') + call require(first%mycall13.eq.'N0AAA'.and.first%mycall13_configured_set, & + 'initialization preserves configured calls') + call require(first%nqueued_calls_by_thread(2).gt.0,'initialization preserves queued calls') + + call reset_pack77_state(first) + call require(associated(saved_calls,first%calls12),'reset retains table storage and views') + call require(all(saved_calls.eq.''),'existing view observes the reset') + call require(lbound(first%calls10,1).eq.0.and.lbound(first%calls12,1).eq.0, & + 'reset preserves zero-based hash tables') + call hash12_for_state(first,ihashcall(call,12),resolved_call) + call require(trim(resolved_call).eq.'<...>','reset forgets learned calls') + call require(first%nzhash.eq.0.and.all(first%ihash22.eq.-1),'reset clears hash entries') + call require(first%mycall13.eq.''.and..not.first%mycall13_configured_set, & + 'reset clears configured calls') + call fold_queued_calls_for_state(first,2) + call require(all(first%calls12.eq.''),'reset discards queued calls before folding') + call hash12_for_state(second,ihashcall(call,12),resolved_call) + call require(trim(resolved_call).eq.'<'//trim(call)//'>','reset leaves other states unchanged') + call save_hash_call_for_state(first,call,n10,n12,n22) + call require(saved_calls(n12).eq.call,'reset storage remains usable through existing views') + + print *, 'packjt77 explicit state isolation passed' + +contains + + subroutine require(condition,label) + logical, intent(in) :: condition + character(len=*), intent(in) :: label + + if(condition) return + print *, 'FAIL: ',label + error stop 1 + end subroutine require +end program test_packjt77_context_state diff --git a/tests/unit/packjt77/test_packjt77_grammar_gate.f90 b/tests/unit/packjt77/test_packjt77_grammar_gate.f90 index 2698baa1..94246c00 100644 --- a/tests/unit/packjt77/test_packjt77_grammar_gate.f90 +++ b/tests/unit/packjt77/test_packjt77_grammar_gate.f90 @@ -1,6 +1,8 @@ program test_packjt77_grammar_gate - use packjt77_grammar, only: pack77_gate_messages_match + use packjt77_grammar, only: pack77_gate_messages_match, & + pack77_exact_free_text_ok,pack77_free_text_alphabet_ok, & + pack77_configured_type12_ok,pack77_configured_type4_ok implicit none integer :: ntests @@ -38,11 +40,56 @@ program test_packjt77_grammar_gate call expect_no_match('changed serial', & 'K1ABC FN42 37', 'K1ABC FN42 38', no_calls, 0) + call expect_text_and_configured_receive_rules() + write(*,1000) ntests 1000 format('packjt77 grammar gate tests passed: ',i0) contains + subroutine expect_text_and_configured_receive_rules() + character(len=13) :: call_1,call_2 + character(len=37) :: msg + + call expect_rule('empty free text',pack77_exact_free_text_ok('')) + call expect_rule('13-character free text',pack77_exact_free_text_ok('ABCDEFGHIJKLM')) + call expect_rule('14-character free text rejected',.not.pack77_exact_free_text_ok('ABCDEFGHIJKLMN')) + call expect_rule('alphabet independent of length',pack77_free_text_alphabet_ok('ABCDEFGHIJKLMN')) + call expect_rule('free text punctuation',pack77_exact_free_text_ok('0123 +-./?')) + call expect_rule('lowercase requires normalization',.not.pack77_exact_free_text_ok('abc')) + call expect_rule('unsupported free text symbol',.not.pack77_free_text_alphabet_ok('ABC@')) + + call_1='' + call_2='W9XYZ/R' + call expect_rule('configured rover collision rejected', & + .not.pack77_configured_type12_ok(call_1,call_2,'FN42',0)) + call expect_rule('configured rover acknowledgement allowed', & + pack77_configured_type12_ok(call_1,call_2,'FN42',1)) + call expect_rule('configured rover RR73 allowed', & + pack77_configured_type12_ok(call_1,call_2,'RR73',0)) + + call_1='CQ' + call_2='PJ4/K1ABC' + msg='CQ PJ4/K1ABC' + call expect_rule('configured compound CQ allowed', & + pack77_configured_type4_ok(call_1,call_2,msg,0,1,0)) + call_2='12/K1ABC' + msg='CQ 12/K1ABC' + call expect_rule('configured two-digit prefix rejected', & + .not.pack77_configured_type4_ok(call_1,call_2,msg,0,1,0)) + end subroutine expect_text_and_configured_receive_rules + + subroutine expect_rule(label,ok) + character(len=*), intent(in) :: label + logical, intent(in) :: ok + + if(.not.ok) then + write(*,'(a)') trim(label)//' failed' + error stop 1 + endif + ntests=ntests+1 + end subroutine expect_rule + subroutine expect_match(label,input_msg,decoded_msg,staged_calls,nstaged) character(len=*), intent(in) :: label,input_msg,decoded_msg character(len=13), intent(in) :: staged_calls(:) diff --git a/tests/unit/packjt77/test_packjt77_hash_state.f90 b/tests/unit/packjt77/test_packjt77_hash_state.f90 index b122ba46..346bc972 100644 --- a/tests/unit/packjt77/test_packjt77_hash_state.f90 +++ b/tests/unit/packjt77/test_packjt77_hash_state.f90 @@ -6,9 +6,21 @@ program test_packjt77_hash_state implicit none integer :: ntests - external :: fillhashvar - external :: ft8apsetvar external :: genft8 + interface + subroutine fillhashvar(numthreads,lfill,knowledge) + import :: pack77_state + integer, intent(in) :: numthreads + logical, intent(in) :: lfill + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads,knowledge) + import :: pack77_state + logical(1), intent(in) :: lmycallstd,lhiscallstd + integer :: numthreads + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + end interface ntests=0 @@ -881,8 +893,11 @@ contains subroutine expect_ft8apsetvar_does_not_record_template_hashes() logical(1) :: lmycallstd, lhiscallstd + type(pack77_state), target :: knowledge call clear_all_state('N0AAA','PJ2/W1AW') + knowledge%mycall13='N0AAA' + knowledge%dxcall13='PJ2/W1AW' mycall='N0AAA ' hiscall='PJ2/W1AW ' mybcall='N0AAA ' @@ -892,8 +907,13 @@ contains lmycallstd=.true. lhiscallstd=.false. - call ft8apsetvar(lmycallstd,lhiscallstd,1) - call assert_shared_hash_tables_empty('ft8apsetvar template hashes') + call ft8apsetvar(lmycallstd,lhiscallstd,1,knowledge) + call assert_int('ft8apsetvar owned nzhash',0,knowledge%nzhash) + call assert_true('ft8apsetvar owned calls10',all(knowledge%calls10.eq.'')) + call assert_true('ft8apsetvar owned calls12',all(knowledge%calls12.eq.'')) + call assert_true('ft8apsetvar owned calls22',all(knowledge%calls22.eq.'')) + call assert_true('ft8apsetvar owned recent calls',all(knowledge%recent_calls.eq.'')) + call assert_shared_hash_tables_empty('ft8apsetvar legacy isolation') ntests=ntests+1 end subroutine expect_ft8apsetvar_does_not_record_template_hashes diff --git a/tests/unit/packjt77/test_packjt77_schema_decoder.f90 b/tests/unit/packjt77/test_packjt77_schema_decoder.f90 index 7c9816f5..3e837ed0 100644 --- a/tests/unit/packjt77/test_packjt77_schema_decoder.f90 +++ b/tests/unit/packjt77/test_packjt77_schema_decoder.f90 @@ -13,6 +13,7 @@ program test_packjt77_schema_decoder call expect_type2_tag_decode() call expect_invalid_binary_and_tag_fail() call expect_type1_grid_boundary() + call expect_wspr_dispatch() call expect_wspr_selector_padding_and_power_checks() call expect_type5_grid_range_check() call expect_type5_raw_invalid_serial_rejected() @@ -121,6 +122,39 @@ contains ntests=ntests+1 end subroutine expect_type1_grid_boundary + subroutine expect_wspr_dispatch() + character(len=77) :: c77 + integer :: selector + integer, parameter :: expected(0:7)=[1,2,3,2,1,2,3,2] + type(pack77_wspr_type3_fields) :: type3_fields + logical :: ok + + c77=repeat('0',77) + c77(72:77)='110000' + do selector=0,7 + write(c77(48:50),'(b3.3)') selector + call assert_int('WSPR subtype selector',expected(selector), & + pack77_wspr_payload_type(c77)) + call assert_int('WSPR prevalidated subtype selector',expected(selector), & + pack77_wspr_payload_type(c77,.true.)) + enddo + + c77(48:50)='110' + call decode_pack77_wspr_type3(c77,type3_fields,ok,.true.) + call assert_true('dispatched invalid WSPR selector rejected',.not.ok) + + c77(48:50)='010' + c77(1:1)='x' + call assert_int('WSPR dispatch rejects nonbinary payload',0, & + pack77_wspr_payload_type(c77)) + c77(1:1)='0' + c77(50:50)='x' + call assert_int('WSPR dispatch rejects nonbinary selector',0, & + pack77_wspr_payload_type(c77)) + + ntests=ntests+1 + end subroutine expect_wspr_dispatch + subroutine expect_wspr_selector_padding_and_power_checks() character(len=77) :: c77 type(pack77_wspr_type1_fields) :: type1_fields diff --git a/tests/unit/packjt77/test_packjt77sdvar_invariants.f90 b/tests/unit/packjt77/test_packjt77sdvar_invariants.f90 index d0ffac93..643e9ff3 100644 --- a/tests/unit/packjt77/test_packjt77sdvar_invariants.f90 +++ b/tests/unit/packjt77/test_packjt77sdvar_invariants.f90 @@ -2,15 +2,14 @@ program test_packjt77sdvar_invariants use packjt77 use packjt77_test_helpers + use ft8var_codec_context, only: ft8sdvar,ft8svar,tonesdvar use ft8_mod1, only : idtone56_valid,idtone56,itone56,msg,lastrxmsg,mycall, & hiscall,nlasttx,csyncsd_valid,csyncsdcq_valid implicit none integer :: ntests + logical(kind=1), parameter :: flag_false=.false.,flag_true=.true. external :: genft8sdvar - external :: ft8sdvar - external :: ft8svar - external :: tonesdvar ntests=0 @@ -134,7 +133,7 @@ contains decoded='' lft8s=.false. - call ft8svar(s8,0.0,itone,decoded,lft8s,1,.false.) + call ft8svar(s8,0.0,itone,decoded,lft8s,1,flag_false) call assert_true('ft8svar last grid row valid',logical(idtone56_valid(53))) call assert_text_equal('ft8svar last grid message', & @@ -150,7 +149,7 @@ contains csyncsd_valid=.true. msgd=' W9XYZ -01' - call tonesdvar(msgd,.false.) + call tonesdvar(msgd,flag_false) call assert_true('failed QSO template invalidates sync', & .not.logical(csyncsd_valid)) @@ -164,7 +163,7 @@ contains csyncsdcq_valid=.true. msgd='CQ PJ4/K1ABC' - call tonesdvar(msgd,.true.) + call tonesdvar(msgd,flag_true) call assert_true('failed CQ template invalidates sync', & .not.logical(csyncsdcq_valid)) diff --git a/tests/unit/q65/CMakeLists.txt b/tests/unit/q65/CMakeLists.txt index 698ea12d..71c8223b 100644 --- a/tests/unit/q65/CMakeLists.txt +++ b/tests/unit/q65/CMakeLists.txt @@ -1,6 +1,5 @@ -add_executable (test_q65_workspace - test_q65_workspace.f90 - ${CMAKE_SOURCE_DIR}/lib/qra/q65/q65_workspace.f90) +add_executable (test_q65_workspace test_q65_workspace.f90) +wsjt_link_common_fortran (test_q65_workspace) add_test (NAME test_q65_workspace COMMAND test_q65_workspace) @@ -21,7 +20,8 @@ add_test (NAME test_q65_decode_pipeline COMMAND test_q65_decode_pipeline) set_tests_properties (test_q65_decode_pipeline PROPERTIES COST 10 # Allow for hosted ARM emulation without leaving the test unbounded. - TIMEOUT 180) + # The full-period spectra and drift cases added about a third to the runtime. + TIMEOUT 360) if (WSJT_ENABLE_TSAN) set_tests_properties (test_q65_decode_pipeline PROPERTIES ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_fortran_options}") @@ -33,3 +33,11 @@ target_include_directories (test_q65_llh_contracts PRIVATE ${CMAKE_SOURCE_DIR}/lib/qra/q65) target_link_libraries (test_q65_llh_contracts PRIVATE wsjt_cxx) add_test (NAME test_q65_llh_contracts COMMAND test_q65_llh_contracts) + +add_executable (test_q65_callers test_q65_callers.f90) +wsjt_link_common_fortran (test_q65_callers) +add_test (NAME test_q65_callers COMMAND test_q65_callers) + +add_executable (test_q65_caller_display test_q65_caller_display.f90) +wsjt_link_common_fortran (test_q65_caller_display) +add_test (NAME test_q65_caller_display COMMAND test_q65_caller_display) diff --git a/tests/unit/q65/test_map65_wideband_sync_rows.f90 b/tests/unit/q65/test_map65_wideband_sync_rows.f90 index 143f0c3a..185bd96f 100644 --- a/tests/unit/q65/test_map65_wideband_sync_rows.f90 +++ b/tests/unit/q65/test_map65_wideband_sync_rows.f90 @@ -105,4 +105,136 @@ program test_map65_wideband_sync_rows call get_candidates(ss,savg,.true.,jz,1,2,0,1,candidates,ncand) if (sync(target_bin)%ccfmax /= ccf_before) & error stop 'invalid covariance did not preserve the legacy Q65 score' + + call test_candidate_search() + +contains + + subroutine reset_search_floor() + integer :: bin,row + ss(:,1:jz,ia:ib)=1.0 + savg(:,ia:ib)=real(jz) + do bin=ia,ib + do row=1,jz + ss(1,row,bin)=1.0+0.002*real(mod(17*row+13*bin,23)) + enddo + savg(1,bin)=sum(ss(1,1:jz,bin)) + enddo + end subroutine reset_search_floor + + subroutine add_search_sync(bin,level) + integer, intent(in) :: bin + real, intent(in) :: level + integer :: symbol,row,offset + do symbol=1,size(expanded_sync) + row=expanded_sync(symbol)+lag + do offset=0,2 + if(row+offset<=jz) ss(1,row+offset,bin)=ss(1,row+offset,bin)+level + enddo + enddo + savg(1,bin)=sum(ss(1,1:jz,bin)) + end subroutine add_search_sync + + subroutine add_jt65_sync(bin,ooo) + integer, intent(in) :: bin + logical, intent(in) :: ooo + integer, parameter :: standard_symbols(63) = [ & + 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] + integer :: symbol,row + do symbol=1,126 + if(ooo .eqv. any(standard_symbols==symbol)) cycle + row=2*(symbol-1)+1+lag + ss(1,row:row+1,bin)=ss(1,row:row+1,bin)+50.0 + enddo + savg(1,bin)=sum(ss(1,1:jz,bin)) + end subroutine add_jt65_sync + + subroutine assert_one_at(bin,description) + integer, intent(in) :: bin + character(len=*), intent(in) :: description + integer :: index + logical :: matches + matches=.false. + do index=1,ncand + if(candidates(index)%iflip==0 .and. & + abs(candidates(index)%f-0.001*(bin-1)*df)<0.0005*df .and. & + abs(candidates(index)%xdt-(lag*2048.0/11025.0-1.0))<0.001) matches=.true. + enddo + if(.not.matches) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine assert_one_at + + subroutine test_candidate_search() + type(candidate) :: first + integer :: first_count, second_bin + + second_bin=target_bin+120 + call reset_search_floor() + call add_search_sync(target_bin,50.0) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(ncand/=1) error stop 'one MAP65 Q65 sync candidate was not isolated' + call assert_one_at(target_bin,'one MAP65 Q65 candidate frequency and time') + first_count=ncand + first=candidates(1) + + call reset_search_floor() + call add_search_sync(second_bin,50.0) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(ncand/=1) error stop 'alternate MAP65 candidate was not isolated' + call assert_one_at(second_bin,'alternate MAP65 candidate frequency and time') + + call reset_search_floor() + call add_search_sync(target_bin,50.0) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(ncand/=first_count .or. candidates(1)%f/=first%f .or. & + candidates(1)%xdt/=first%xdt .or. candidates(1)%snr/=first%snr .or. & + candidates(1)%iflip/=first%iflip) error stop 'MAP65 A-B-A candidate changed' + + ss(2:4,1:jz,ia:ib)=1.0e20 + savg(2:4,ia:ib)=1.0e20 + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(ncand/=first_count .or. candidates(1)%f/=first%f .or. & + candidates(1)%snr/=first%snr) error stop 'inactive MAP65 polarization affected search' + + call reset_search_floor() + call add_search_sync(target_bin,50.0) + call add_search_sync(second_bin,45.0) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(ncand/=2) error stop 'separated MAP65 Q65 signals did not survive' + + call reset_search_floor() + call add_search_sync(target_bin,50.0) + call add_search_sync(target_bin+2,20.0) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(ncand/=1) error stop 'nearby MAP65 peaks did not collapse to one candidate' + call assert_one_at(target_bin,'stronger MAP65 nearby peak survived') + + call reset_search_floor() + ss(1,1:jz,target_bin)=ss(1,1:jz,target_bin)+80.0 + savg(1,target_bin)=sum(ss(1,1:jz,target_bin)) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(ncand/=0) error stop 'continuous MAP65 carrier entered the Q65 candidate list' + + call reset_search_floor() + call add_jt65_sync(second_bin,.false.) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(sync(second_bin)%iflip/=1) error stop 'standard JT65 sync fixture was not recognized' + if(ncand/=0) error stop 'standard JT65 sync entered Q65-only search' + + call reset_search_floor() + call add_jt65_sync(second_bin,.true.) + call get_candidates(ss,savg,.false.,jz,1,2,0,1,candidates,ncand) + if(sync(second_bin)%iflip/=-1) error stop 'OOO JT65 sync fixture was not recognized' + if(ncand/=0) error stop 'OOO JT65 sync entered Q65-only search' + + call reset_search_floor() + call add_search_sync(target_bin,50.0) + call get_candidates(ss,savg,.false.,jz,2,3,0,1,candidates,ncand) + if(ncand/=0) error stop 'MAP65 candidate outside search band was admitted' + end subroutine test_candidate_search end program test_map65_wideband_sync_rows diff --git a/tests/unit/q65/test_q65_caller_display.f90 b/tests/unit/q65/test_q65_caller_display.f90 new file mode 100644 index 00000000..87e54590 --- /dev/null +++ b/tests/unit/q65/test_q65_caller_display.f90 @@ -0,0 +1,123 @@ +program test_q65_caller_display + use types, only: q3list + use q65_callers + use, intrinsic :: iso_fortran_env, only: int8 + implicit none + + type(q3list) :: callers(Q65_MAX_CALLERS),loaded(Q65_MAX_CALLERS) + character(len=Q65_ROW_WIDTH) :: rows(Q65_MAX_CALLERS) + character(len=256) :: ephemeris + character(len=*), parameter :: path='caller-display-history.dat' + character(len=*), parameter :: other='caller-display-removal.dat' + character(len=*), parameter :: malformed='caller-display-malformed.dat' + integer(int8), allocatable :: before(:),after(:) + integer :: i,now,count,status,unit + logical*1 :: disk_data + + ephemeris='missing-caller-display-ephemeris' + call jpl_setup(ephemeris) + now=time() + do i=1,Q65_MAX_CALLERS + write(callers(i)%call,'(a1,i5.5)') 'K',i + callers(i)%grid='FN42' + callers(i)%nsec=now + callers(i)%nfreq=1500-i + callers(i)%moonel=99 + enddo + callers(1)%nsec=now-90000 + call q65_save_callers(path,callers,Q65_MAX_CALLERS,status) + call require(status.eq.0,'save mixed-age history') + call read_bytes(path,before) + + disk_data=.true. + call get_q3list(path,disk_data,Q65_MAX_CALLERS,count,rows) + call require(count.eq.Q65_MAX_CALLERS-1,'display excludes expired callers') + call require(rows(1)(12:17).eq.callers(Q65_MAX_CALLERS)%call, & + 'display sorts callers by frequency') + call require(rows(count)(12:17).eq.callers(2)%call,'display retains every fresh caller') + call require(iachar(rows(count)(Q65_ROW_WIDTH:Q65_ROW_WIDTH)).eq.0,'row terminator') + call require_unchanged(path,before,'disk display preserves history bytes') + + disk_data=.false. + call get_q3list(path,disk_data,Q65_MAX_CALLERS,count,rows) + call require_unchanged(path,before,'live visibility filtering preserves history bytes') + disk_data=.true. + rows='untouched' + call get_q3list(path,disk_data,2,count,rows) + call require(count.eq.2,'display respects output capacity') + call require(all(rows(3:).eq.'untouched'),'display does not write beyond capacity') + call require(rows(1)(12:17).eq.callers(Q65_MAX_CALLERS)%call, & + 'bounded display preserves frequency ordering') + rows='untouched' + call get_q3list(path,disk_data,0,count,rows) + call require(count.eq.0 .and. all(rows.eq.'untouched'),'zero capacity leaves output untouched') + + callers(1)%nsec=now + call q65_save_callers(path,callers,Q65_MAX_CALLERS,status) + call require(status.eq.0,'save full history') + call read_bytes(path,before) + call get_q3list(path,disk_data,Q65_MAX_CALLERS,count,rows) + call require(count.eq.Q65_MAX_CALLERS,'display includes full caller capacity') + call require_unchanged(path,before,'full display preserves history bytes') + + loaded=q3list('','',0,0,0) + loaded(1)=q3list('K1ABC','FN42',now,1500,0) + call q65_save_callers(other,loaded,1,status) + call require(status.eq.0,'save separate removal history') + call rm_q3list(other,'K1ABC') + call q65_load_callers(other,loaded,count,status) + call require(status.eq.0 .and. count.eq.0,'remove final caller using explicit path') + call require_unchanged(path,before,'removal leaves previously displayed history untouched') + + open(newunit=unit,file=malformed,form='unformatted',status='replace') + write(unit) Q65_MAX_CALLERS+1 + close(unit) + call read_bytes(malformed,before) + call get_q3list(malformed,disk_data,Q65_MAX_CALLERS,count,rows) + call require(count.eq.0,'malformed history displays empty') + call rm_q3list(malformed,'K1ABC') + call require_unchanged(malformed,before,'failed load never overwrites malformed history') + + call delete_file(path) + call delete_file(other) + call delete_file(malformed) + deallocate(before,after) + print *, 'PASS Q65 caller display and removal' + +contains + + subroutine require(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if(.not.condition) then + print *, 'FAIL: '//message + stop 1 + endif + end subroutine require + + subroutine read_bytes(filename,bytes) + character(len=*), intent(in) :: filename + integer(int8), allocatable, intent(out) :: bytes(:) + integer :: n,u + inquire(file=filename,size=n) + allocate(bytes(n)) + open(newunit=u,file=filename,status='old',access='stream',form='unformatted',action='read') + read(u) bytes + close(u) + end subroutine read_bytes + + subroutine require_unchanged(filename,expected,message) + character(len=*), intent(in) :: filename,message + integer(int8), intent(in) :: expected(:) + call read_bytes(filename,after) + call require(size(after).eq.size(expected),message) + call require(all(after.eq.expected),message) + end subroutine require_unchanged + + subroutine delete_file(filename) + character(len=*), intent(in) :: filename + integer :: u + open(newunit=u,file=filename,status='old') + close(u,status='delete') + end subroutine delete_file +end program test_q65_caller_display diff --git a/tests/unit/q65/test_q65_callers.f90 b/tests/unit/q65/test_q65_callers.f90 new file mode 100644 index 00000000..935337b0 --- /dev/null +++ b/tests/unit/q65/test_q65_callers.f90 @@ -0,0 +1,163 @@ +program test_q65_callers + use types, only: q3list + use q65_callers + use, intrinsic :: iso_fortran_env, only: int16 + implicit none + integer, parameter :: now=1000000 + character(len=*), parameter :: filename='test_q65_callers.dat' + type(q3list) :: callers(Q65_MAX_CALLERS),loaded(Q65_MAX_CALLERS) + integer :: count,status,n,unit,i + character(len=6) :: callsign + + call remove_file() + call q65_load_callers(filename,loaded,n,status) + call expect(status.eq.0 .and. n.eq.0,'missing history is empty') + call expect(all(loaded%call.eq.'') .and. all(loaded%nsec.eq.0),'empty history is initialized') + call check_expiry() + call check_capacity() + call check_persistence() + call remove_file() + print *, 'Q65 caller history tests passed' + +contains + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if(condition) return + print *, message + error stop 1 + end subroutine expect + + subroutine check_expiry() + callers=q3list('','',0,0,0) + callers(1)=q3list('K1AAA','FN42',now-86401,1000,0) + callers(2)=q3list('K1BBB','FN42',now-86401,1100,0) + callers(3)=q3list('K1CCC','FN42',now,1200,0) + count=3 + call q65_expire_callers(callers,count,now) + call expect(count.eq.1 .and. callers(1)%call.eq.'K1CCC','adjacent expired entries are removed') + call q65_expire_callers(callers,count,now) + call expect(count.eq.1 .and. callers(1)%call.eq.'K1CCC','expiry is idempotent') + callers(1)=q3list('K1AAA','FN42',now-86401,1000,0) + callers(2)=q3list('K1BBB','FN42',now,1100,0) + callers(3)=q3list('K1CCC','FN42',now-86401,1200,0) + count=3 + call q65_expire_callers(callers,count,now) + call expect(count.eq.1 .and. callers(1)%call.eq.'K1BBB','fresh caller survives expired neighbors') + callers(1)=q3list('K1AAA','FN42',now-86400,1000,0) + callers(2)=q3list('K1BBB','FN42',now+1,1100,0) + count=2 + call q65_expire_callers(callers,count,now) + call expect(count.eq.2,'24-hour boundary and future timestamps are retained') + call q65_expire_callers(callers,count,now+86402) + call expect(count.eq.0 .and. all(callers%call.eq.''),'all-expired history is empty') + end subroutine check_expiry + + subroutine check_capacity() + callers=q3list('','',0,0,0) + count=0 + do i=1,Q65_MAX_CALLERS + write(callsign,'(a2,i4.4)') 'K1',i + call q65_record_caller(callers,count,1000+i,'K1ABC '//callsign//' FN42',now+i) + enddo + call expect(count.eq.Q65_MAX_CALLERS,'history reaches full capacity') + call q65_record_caller(callers,count,2000,'K1ABC K10001 R EM10',now+100) + call expect(count.eq.Q65_MAX_CALLERS .and. callers(1)%nsec.eq.now+100,'refresh does not add a caller') + call expect(callers(1)%grid.eq.'FN42' .and. callers(1)%nfreq.eq.2000,'refresh preserves grid and updates frequency') + call q65_record_caller(callers,count,2100,'K1ABC K19999 FN42',now+101) + call expect(count.eq.Q65_MAX_CALLERS,'overflow retains capacity') + call expect(callers(1)%call.eq.'K10001' .and. callers(2)%call.eq.'K10003', & + 'least recently heard caller is evicted after refresh') + call expect(callers(count)%call.eq.'K19999','new caller enters full history') + call q65_save_callers(filename,callers,count,status) + call expect(status.eq.0,'full history saves') + call q65_load_callers(filename,loaded,n,status) + call expect(status.eq.0 .and. n.eq.count,'full history reloads') + call expect(all(loaded%call.eq.callers%call) .and. all(loaded%nsec.eq.callers%nsec), & + 'eviction and refresh survive reload') + + callers%nsec=now + call q65_record_caller(callers,count,2200,'K1ABC K18888 FN42',now+1) + call expect(callers(1)%call.eq.'K10003','equal timestamps evict first stored caller') + call q65_record_caller(callers,count,2300,'K1ABC K17777/P FN42',now+2) + call expect(.not.any(callers%call.eq.'K17777'),'compound calls are ignored') + call q65_record_caller(callers,count,2300,'K1ABC K17777 RR73',now+2) + call expect(.not.any(callers%call.eq.'K17777'),'RR73 does not introduce a caller') + call q65_remove_caller(callers,count,'K18888') + call expect(count.eq.Q65_MAX_CALLERS-1,'final caller can be removed at capacity') + call q65_remove_caller(callers,count,'K18888') + call expect(count.eq.Q65_MAX_CALLERS-1,'absent caller removal is harmless') + do while(count.gt.0) + callsign=callers(1)%call + call q65_remove_caller(callers,count,callsign) + enddo + call q65_save_callers(filename,callers,count,status) + call expect(status.eq.0,'empty history saves') + call q65_load_callers(filename,loaded,n,status) + call expect(status.eq.0 .and. n.eq.0,'empty history reloads') + + callers(1)=q3list('K1OLD','FN42',now-86401,1000,0) + count=1 + call q65_record_caller(callers,count,1500,'K1ABC K1NEW FN42',now) + call expect(count.eq.1 .and. callers(1)%call.eq.'K1NEW','recording expires old callers first') + end subroutine check_capacity + + subroutine check_persistence() + integer :: legacy_count,saved_count + + callers=q3list('K1ABC','FN42',now,1500,0) + do legacy_count=40,50,10 + open(newunit=unit,file=filename,status='replace',form='unformatted') + write(unit) legacy_count + write(unit) callers(1:legacy_count) + close(unit) + call q65_load_callers(filename,loaded,n,status) + call expect(status.eq.0 .and. n.eq.legacy_count,'legacy binary history loads') + call expect(all(loaded(1:n)%call.eq.'K1ABC'),'legacy caller records are preserved') + enddo + + do saved_count=-1,Q65_MAX_CALLERS+1,Q65_MAX_CALLERS+2 + open(newunit=unit,file=filename,status='replace',form='unformatted') + write(unit) saved_count + close(unit) + call q65_load_callers(filename,loaded,n,status) + call expect(status.ne.0 .and. n.eq.0 .and. all(loaded%call.eq.''),'invalid count is rejected safely') + open(newunit=unit,file=filename,status='old',form='unformatted') + read(unit) legacy_count + close(unit) + call expect(legacy_count.eq.saved_count,'failed load leaves malformed file unchanged') + enddo + + open(newunit=unit,file=filename,status='replace',form='unformatted') + write(unit) 2 + write(unit) callers(1:1) + close(unit) + call q65_load_callers(filename,loaded,n,status) + call expect(status.ne.0 .and. n.eq.0 .and. all(loaded%nsec.eq.0),'short caller record is rejected safely') + call q65_save_callers(filename,callers,Q65_MAX_CALLERS+1,status) + call expect(status.ne.0,'over-capacity save is rejected') + open(newunit=unit,file=filename,status='old',form='unformatted') + read(unit) saved_count + close(unit) + call expect(saved_count.eq.2,'rejected save does not replace existing file') + + open(newunit=unit,file=filename,status='replace',form='unformatted') + close(unit) + call q65_load_callers(filename,loaded,n,status) + call expect(status.eq.0 .and. n.eq.0,'legacy empty file is a normal empty history') + open(newunit=unit,file=filename,status='replace',form='unformatted',access='stream') + write(unit) 1_int16 + close(unit) + call q65_load_callers(filename,loaded,n,status) + call expect(status.ne.0 .and. n.eq.0,'truncated count is rejected safely') + end subroutine check_persistence + + subroutine remove_file() + logical :: exists + inquire(file=filename,exist=exists) + if(.not.exists) return + open(newunit=unit,file=filename,status='old') + close(unit,status='delete') + end subroutine remove_file +end program test_q65_callers diff --git a/tests/unit/q65/test_q65_decode_pipeline.f90 b/tests/unit/q65/test_q65_decode_pipeline.f90 index 84b34dc0..a4c93c7f 100644 --- a/tests/unit/q65/test_q65_decode_pipeline.f90 +++ b/tests/unit/q65/test_q65_decode_pipeline.f90 @@ -44,6 +44,7 @@ program test_q65_decode_pipeline use q65_decode, only: q65_decoder,cq0,msg0,nsnr0,nfreq0,xdt0 use q65_test_fixture, only: make_q65_wave,q65_nsamples,q65_ntrperiod use types, only: q3list + use q65_callers, only: Q65_MAX_CALLERS,Q65_MAX_CODEWORDS implicit none integer(int16), allocatable :: iwave(:) @@ -74,6 +75,14 @@ program test_q65_decode_pipeline call run_direct_decode(decoder,iwave,nsubmode,1,want_iflagdec=0) enddo + iwave=0_int16 + call run_direct_decode(decoder,iwave,0,0,ntrperiod=30) + if(decoder%state%jz0.ne.(30*12000-30*120)/(30*120/8)+1) then + error stop 'Q65 spectra do not cover every complete input window' + endif + + call check_q65_drift_compensation() + ! The direct decoder loop owns exhaustive submode coverage. MAP65 is a thin ! handoff, so exercise both ends of its forwarded submode range. do isubmode=1,size(map65_submodes) @@ -87,16 +96,67 @@ program test_q65_decode_pipeline iwave=0_int16 call run_map65_decode(iwave,0,.false.) + call decoder%destroy() + deallocate(iwave) write(*,'(a)') 'Q65 raw decoder and MAP65 handoff tests passed' contains + subroutine check_q65_drift_compensation() + use q65, only: q65_dec0,q65_select,q65_work,q65_state, & + s1a,s1w,iseq,iz0,j0,NSTEP,df,ncw,max_drift,drift + type(q65_state), pointer :: previous_state + integer, parameter :: drift_cases(3)=[-50,0,50] + integer :: case_number,want_drift,k,i,j,peak_min,peak_max,dat4(13),idec + real :: xdt,f0,snr1,width,snr2 + + iwave=0_int16 + call run_direct_decode(decoder,iwave,0,0) + previous_state=>q65_work + call q65_select(decoder%state) + ncw=0 + max_drift=50 + do case_number=1,size(drift_cases) + want_drift=drift_cases(case_number) + s1a(:,:,iseq)=0.0 + do k=1,85 + j=j0+NSTEP*(k-1)+1 + i=nint(1000.0/df)+nint(real(want_drift)*(k-43)/85.0) + s1a(i,j,iseq)=100.0 + enddo + if(associated(s1w)) deallocate(s1w) + nullify(q65_work%s1w) + ! Averaged spectra without list candidates reach stage 5 without an earlier decode. + call q65_dec0(1,iwave,q65_ntrperiod,1000,20,lclearave,2.5, & + xdt,f0,snr1,width,dat4,snr2,idec,5) + ! Integer bin rounding makes zero drift indistinguishable from a one-bin sweep. + if(abs(nint(drift/df)-want_drift).gt.1) then + error stop 'Q65 synchronization missed the planted drift' + endif + if(.not.associated(s1w)) error stop 'Q65 stage-5 drift compensation did not run' + peak_min=iz0 + peak_max=1 + do k=1,85 + j=j0+NSTEP*(k-1)+1 + if(maxval(s1w(:,j)).lt.99.0) error stop 'Q65 drift compensation lost a symbol' + i=maxloc(s1w(:,j),dim=1) + peak_min=min(peak_min,i) + peak_max=max(peak_max,i) + enddo + if(peak_max-peak_min.gt.1) then + error stop 'Q65 drift compensation depends on the receive horizon' + endif + enddo + call q65_select(previous_state) + lclearave=.true. + end subroutine check_q65_drift_compensation + subroutine check_q65_ap_flag_masks() integer :: apsym0(58),apmask(78),apsymbols(78),iaptype - integer :: codewords(63,411),ncw,j + integer :: codewords(63,Q65_MAX_CODEWORDS),ncw,j character(len=12) :: list_mycall,list_hiscall character(len=6) :: list_hisgrid - type(q3list) :: callers(50) + type(q3list) :: callers(Q65_MAX_CALLERS) apsym0=0 call q65_ap(5,1,0,.false.,.false.,iaptype,apsym0,apmask,apsymbols) @@ -112,19 +172,75 @@ contains list_mycall='K1ABC' list_hiscall='W9XYZ' list_hisgrid='FN42' - do j=1,40 - write(callers(j)%call,'(a2,i4.4)') 'K1',j + do j=1,Q65_MAX_CALLERS + callers(j)%call='K1'//achar(65+(j-1)/26)//achar(65+mod(j-1,26))//'A' callers(j)%grid='FN42' enddo - call q65_set_list2(list_mycall,list_hiscall,list_hisgrid,callers,40,codewords,ncw) - if(ncw.ne.411) error stop 'Q65 Pileup full AP list truncated at 40 callers' + call q65_set_list2(list_mycall,list_hiscall,list_hisgrid,callers, & + Q65_MAX_CALLERS,codewords,ncw) + if(ncw.ne.511) error stop 'Q65 Pileup full AP list omitted a stored or current caller' + if(any(codewords(:,1).ne.0)) error stop 'Q65 Pileup all-zero candidate changed' + call check_caller_codewords(codewords(:,ncw-19:ncw-10),list_mycall, & + callers(Q65_MAX_CALLERS)%call,callers(Q65_MAX_CALLERS)%grid) + call check_caller_codewords(codewords(:,ncw-9:ncw),list_mycall, & + list_hiscall,list_hisgrid) + + list_hiscall=callers(Q65_MAX_CALLERS)%call + call q65_set_list2(list_mycall,list_hiscall,list_hisgrid,callers, & + Q65_MAX_CALLERS,codewords,ncw) + if(ncw.ne.501) error stop 'Q65 Pileup duplicated a stored current caller' + call check_caller_codewords(codewords(:,ncw-9:ncw),list_mycall, & + callers(Q65_MAX_CALLERS)%call,callers(Q65_MAX_CALLERS)%grid) + + list_hiscall=' ' + call q65_set_list2(list_mycall,list_hiscall,list_hisgrid,callers, & + Q65_MAX_CALLERS,codewords,ncw) + if(ncw.ne.501) error stop 'Q65 Pileup added an invalid current caller' + call check_caller_codewords(codewords(:,ncw-9:ncw),list_mycall, & + callers(Q65_MAX_CALLERS)%call,callers(Q65_MAX_CALLERS)%grid) + + call q65_set_list2(list_mycall,list_hiscall,list_hisgrid,callers,-1,codewords,ncw) + if(ncw.ne.0) error stop 'Q65 Pileup accepted a negative caller count' + call q65_set_list2(list_mycall,list_hiscall,list_hisgrid,callers, & + Q65_MAX_CALLERS+1,codewords,ncw) + if(ncw.ne.0) error stop 'Q65 Pileup accepted an oversized caller count' end subroutine check_q65_ap_flag_masks - subroutine run_direct_decode(decoder,samples,nsubmode,want_callback,want_iflagdec) + subroutine check_caller_codewords(codewords,mycall,dxcall,grid) + integer, intent(in) :: codewords(63,10) + character(len=*), intent(in) :: mycall,dxcall,grid + integer, parameter :: sync_positions(22)=[ & + 1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85] + character(len=6) :: tails(5) + character(len=37) :: message,msgsent + integer :: tones(85),expected(63),kind,flag,i3,n3,j,k,column + + tails=[character(len=6) :: grid(1:4),'R '//grid(1:4),'RRR','RR73','73'] + do kind=1,size(tails) + message=trim(mycall)//' '//trim(dxcall)//' '//trim(tails(kind)) + do flag=0,1 + call genq65(message,0,msgsent,tones,i3,n3,flag) + if(msgsent.ne.message) error stop 'Q65 Pileup test message failed to encode' + j=0 + do k=1,size(tones) + if(any(sync_positions.eq.k)) cycle + j=j+1 + expected(j)=tones(k)-1 + enddo + column=2*(kind-1)+flag+1 + if(any(codewords(:,column).ne.expected)) then + error stop 'Q65 Pileup lost a message form or flag at the caller boundary' + endif + enddo + enddo + end subroutine check_caller_codewords + + subroutine run_direct_decode(decoder,samples,nsubmode,want_callback,want_iflagdec,ntrperiod) type(q65_decoder), intent(inout) :: decoder integer(int16), intent(in) :: samples(:) integer, intent(in) :: nsubmode,want_callback - integer, intent(in), optional :: want_iflagdec + integer, intent(in), optional :: want_iflagdec,ntrperiod + integer :: decode_period logical :: want_success callback_count=0 @@ -139,7 +255,9 @@ contains callback_freq=0.0 callback_iflagdec=-1 want_success=want_callback.ne.0 - call decoder%decode(capture_callback,samples,1,100,q65_ntrperiod,nsubmode, & + decode_period=q65_ntrperiod + if(present(ntrperiod)) decode_period=ntrperiod + call decoder%decode(capture_callback,samples,1,100,decode_period,nsubmode, & 1000,150,3,850,1150,lclearave,single_decode,lagain,0,lnewdat,2.5, & mycall,hiscall,hisgrid,0,0,.false.,lapcqonly,navg0,nqf) if(want_success) then @@ -147,7 +265,7 @@ contains if(trim(callback_message).ne.'K1ABC W9XYZ FN42') then error stop 'direct Q65 decoder returned the wrong message' endif - if(callback_idec.lt.0 .or. callback_ntrperiod.ne.q65_ntrperiod) then + if(callback_idec.lt.0 .or. callback_ntrperiod.ne.decode_period) then error stop 'direct Q65 callback metadata changed' endif if(abs(callback_freq-1000.0).gt.8.0) error stop 'direct Q65 frequency changed' diff --git a/tests/unit/q65/test_q65_llh_contracts.c b/tests/unit/q65/test_q65_llh_contracts.c index 888674bd..d99883e9 100644 --- a/tests/unit/q65/test_q65_llh_contracts.c +++ b/tests/unit/q65/test_q65_llh_contracts.c @@ -1,8 +1,10 @@ #include "q65.h" +#include "qra15_65_64_irr_e23.h" #include #include #include +#include static void require (int condition, char const * message) { @@ -13,6 +15,73 @@ static void require (int condition, char const * message) } } +static void set_candidate_probabilities (float * intrinsics, int const * codeword, + float probability) +{ + for (int symbol = 0; symbol < 63; ++symbol) + { + for (int tone = 0; tone < 64; ++tone) + intrinsics[symbol * 64 + tone] = (1.0f - probability) / 63.0f; + intrinsics[symbol * 64 + codeword[symbol]] = probability; + } +} + +static void check_full_ap_list (void) +{ + q65_codec_ds codec; + int (*codewords)[63] = calloc (Q65_FULLAPLIST_SIZE, sizeof *codewords); + float intrinsics[63 * 64]; + int decoded[63], message[13], expected[13] = {0}; + + require (codewords != NULL, "full AP list allocation failed"); + require (q65_init (&codec, &qra15_65_64_irr_e23) >= 0, + "Q65 codec initialization failed"); + require (Q65_FULLAPLIST_SIZE == 511, "Q65 full AP list capacity changed"); + for (int index = 0; index < Q65_FULLAPLIST_SIZE; ++index) + { + expected[0] = index % 64; + expected[1] = index / 64; + require (q65_encode (&codec, codewords[index], expected) >= 0, + "full AP candidate encoding failed"); + } + + int last = Q65_FULLAPLIST_SIZE - 1; + set_candidate_probabilities (intrinsics, codewords[last], 0.9f); + require (q65_decode_fullaplist (&codec, decoded, message, intrinsics, + codewords[0], Q65_FULLAPLIST_SIZE) == last, + "full AP decoder did not reach the final current-DX candidate"); + require (memcmp (decoded, codewords[last], sizeof decoded) == 0 && + memcmp (message, expected, sizeof message) == 0, + "full AP decoder returned the wrong final candidate payload"); + + int last_stored = last - 10; + set_candidate_probabilities (intrinsics, codewords[last_stored], 0.9f); + require (q65_decode_fullaplist (&codec, decoded, message, intrinsics, + codewords[0], Q65_FULLAPLIST_SIZE) == last_stored, + "full AP decoder did not reach the final stored-caller candidate"); + + for (int index = 0; index < 63 * 64; ++index) + intrinsics[index] = 1.0f / 64.0f; + require (q65_decode_fullaplist (&codec, decoded, message, intrinsics, + codewords[0], Q65_FULLAPLIST_SIZE) == Q65_DECODE_FAILED, + "full AP decoder accepted uniform evidence at maximum capacity"); + require (q65_decode_fullaplist (&codec, decoded, message, intrinsics, + codewords[0], Q65_FULLAPLIST_SIZE + 1) == Q65_DECODE_INVPARAMS, + "full AP decoder accepted a list beyond capacity"); + + // This likelihood lies between the admission thresholds for 411 and 511 entries. + set_candidate_probabilities (intrinsics, codewords[0], expf (-255.0f / 63.0f)); + require (q65_decode_fullaplist (&codec, decoded, message, intrinsics, + codewords[0], 411) == 0, + "full AP decoder rejected the smaller-list boundary fixture"); + require (q65_decode_fullaplist (&codec, decoded, message, intrinsics, + codewords[0], Q65_FULLAPLIST_SIZE) == Q65_DECODE_FAILED, + "growing the full AP list failed to tighten admission"); + + q65_free (&codec); + free (codewords); +} + int main (void) { float intrinsics[64] = {0}; @@ -38,5 +107,6 @@ int main (void) require (isinf (llh) && llh < 0.0f, "out-of-range codeword symbol left LLH undefined"); + check_full_ap_list (); return 0; } diff --git a/tests/unit/qmap/CMakeLists.txt b/tests/unit/qmap/CMakeLists.txt index 0d0b73ac..2feeef62 100644 --- a/tests/unit/qmap/CMakeLists.txt +++ b/tests/unit/qmap/CMakeLists.txt @@ -43,3 +43,25 @@ add_executable (test_qmap_decode_click_coalescer ) target_link_libraries (test_qmap_decode_click_coalescer Qt5::Test Qt5::Widgets) add_test (NAME test_qmap_decode_click_coalescer COMMAND test_qmap_decode_click_coalescer) + +add_executable (test_qmap_candidates test_qmap_candidates.f90) +target_include_directories (test_qmap_candidates PRIVATE ${CMAKE_BINARY_DIR}/qmap/libqmap) +target_link_libraries (test_qmap_candidates PRIVATE qmap_impl) +add_test (NAME test_qmap_candidates COMMAND test_qmap_candidates) + +add_executable (test_qmap_symspec_contract test_qmap_symspec_contract.f90) +target_link_libraries (test_qmap_symspec_contract PRIVATE qmap_impl) +add_test (NAME test_qmap_symspec_contract COMMAND test_qmap_symspec_contract) + +add_executable (test_qmap_q65_handoff test_qmap_q65_handoff.f90) +target_include_directories (test_qmap_q65_handoff PRIVATE ${CMAKE_BINARY_DIR}/qmap/libqmap) +target_link_libraries (test_qmap_q65_handoff PRIVATE qmap_impl) +add_test (NAME test_qmap_q65_handoff COMMAND test_qmap_q65_handoff) + +add_executable (test_qmap_q65_connection + ${CMAKE_SOURCE_DIR}/tests/unit/q65/q65_test_fixture.f90 + test_qmap_q65_connection.f90) +target_include_directories (test_qmap_q65_connection PRIVATE ${CMAKE_BINARY_DIR}/qmap/libqmap) +target_link_libraries (test_qmap_q65_connection PRIVATE qmap_impl) +add_test (NAME test_qmap_q65_connection COMMAND test_qmap_q65_connection) +add_test (NAME test_qmap_q65_connection_30_second_half COMMAND test_qmap_q65_connection 30) diff --git a/tests/unit/qmap/test_livecq_parser.cpp b/tests/unit/qmap/test_livecq_parser.cpp index 4f0ff9ea..e3fc7f23 100644 --- a/tests/unit/qmap/test_livecq_parser.cpp +++ b/tests/unit/qmap/test_livecq_parser.cpp @@ -77,6 +77,58 @@ private slots: {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "DX", "N5", "1200.0"}, 100, record)); } + + void spotTimeUsesTodaysUtcDate() + { + QDateTime const now {QDate {2026, 9, 30}, QTime {18, 7, 10}, Qt::UTC}; + QCOMPARE(QMapLiveCQ::spotTime("180630", now), + QDateTime(QDate {2026, 9, 30}, QTime {18, 6, 30}, Qt::UTC)); + QCOMPARE(QMapLiveCQ::spotTime("1806", now), + QDateTime(QDate {2026, 9, 30}, QTime {18, 6}, Qt::UTC)); + QCOMPARE(QMapLiveCQ::spotTime("180630", now).toString("yyyy-MM-ddTHH:mm:ss") + "Z", + QString {"2026-09-30T18:06:30Z"}); + } + + void spotTimeIsIndependentOfLocale() + { + QDateTime const now {QDate {2026, 9, 30}, QTime {18, 7, 10}, Qt::UTC}; + auto const previous = QLocale {}; + for (auto const name : {"cs_CZ", "es_AR", "hu_HU", "fr_FR", "de_DE", "zh_TW", "ru_RU"}) { + QLocale::setDefault(QLocale {name}); + QCOMPARE(QMapLiveCQ::spotTime("180630", now).toString("yyyy-MM-ddTHH:mm:ss") + "Z", + QString {"2026-09-30T18:06:30Z"}); + } + QLocale::setDefault(previous); + } + + void spotTimeAcrossMidnight() + { + // Early decode of the last period before midnight: still the same day. + QCOMPARE(QMapLiveCQ::spotTime("235930", QDateTime(QDate {2026, 9, 30}, QTime {23, 59, 52}, Qt::UTC)), + QDateTime(QDate {2026, 9, 30}, QTime {23, 59, 30}, Qt::UTC)); + // Decoded just after midnight: the period began yesterday. + QCOMPARE(QMapLiveCQ::spotTime("235900", QDateTime(QDate {2026, 10, 1}, QTime {0, 0, 5}, Qt::UTC)), + QDateTime(QDate {2026, 9, 30}, QTime {23, 59}, Qt::UTC)); + QCOMPARE(QMapLiveCQ::spotTime("235930", QDateTime(QDate {2026, 10, 1}, QTime {0, 0, 22}, Qt::UTC)), + QDateTime(QDate {2026, 9, 30}, QTime {23, 59, 30}, Qt::UTC)); + // First period of the new day. + QCOMPARE(QMapLiveCQ::spotTime("000000", QDateTime(QDate {2026, 10, 1}, QTime {0, 0, 52}, Qt::UTC)), + QDateTime(QDate {2026, 10, 1}, QTime {0, 0}, Qt::UTC)); + // Clock a few seconds behind the decoder: not pushed back a day. + QCOMPARE(QMapLiveCQ::spotTime("120000", QDateTime(QDate {2026, 9, 30}, QTime {11, 59, 58}, Qt::UTC)), + QDateTime(QDate {2026, 9, 30}, QTime {12, 0}, Qt::UTC)); + } + + void spotTimeRejectsMalformedTimes() + { + QDateTime const now {QDate {2026, 9, 30}, QTime {18, 7, 10}, Qt::UTC}; + for (auto const& decodeTime : {QString {}, QString {"123"}, QString {"1234567"}, + QString {"2460"}, QString {"1260"}, QString {"126099"}, + QString {"12x4"}, QString {"12:34"}}) { + QVERIFY(!QMapLiveCQ::spotTime(decodeTime, now).isValid()); + } + QVERIFY(!QMapLiveCQ::spotTime("123456", QDateTime {}).isValid()); + } }; QTEST_APPLESS_MAIN(TestQMapLiveCQParser) diff --git a/tests/unit/qmap/test_qmap_candidates.f90 b/tests/unit/qmap/test_qmap_candidates.f90 new file mode 100644 index 00000000..17b29bdc --- /dev/null +++ b/tests/unit/qmap/test_qmap_candidates.f90 @@ -0,0 +1,185 @@ +program test_qmap_candidates + use qmap_candidates_mod, only: candidate, getcand2 + implicit none + + integer, parameter :: nfft=32768, first_bin=10000, second_bin=10200 + integer, parameter :: sync_symbols(22) = [1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85] + real, parameter :: df=96000.0/nfft + real, allocatable :: ss(:,:), savg(:) + type(candidate) :: found(50), original(50) + integer :: ncand, original_count + + allocate(ss(400,nfft),savg(nfft)) + + call clear_spectra() + call add_sync(first_bin,60,0,11,35.0) + call search(390,10,10,.false.,found,ncand) + call require(ncand==1,'one Q65-60 candidate') + call expect_candidate(found(1),first_bin,60,0,11) + original_count=ncand + original(1:ncand)=found(1:ncand) + + call clear_spectra() + call add_sync(second_bin,60,0,7,35.0) + call search(390,10,10,.false.,found,ncand) + call require(ncand==1,'alternate Q65-60 candidate') + call expect_candidate(found(1),second_bin,60,0,7) + + call clear_spectra() + call add_sync(first_bin,60,0,11,35.0) + call search(390,10,10,.false.,found,ncand) + call require(ncand==original_count,'A-B-A count is stable') + call same_candidate(found(1),original(1)) + + ! A missing final average-spectrum bin is the searcher's empty-input sentinel. + ss=0.0 + savg=0.0 + call search(390,10,10,.false.,found,ncand) + call require(ncand==0,'empty spectrum clears the previous candidate count') + + call clear_spectra() + call add_sync(first_bin,60,0,11,35.0) + call add_sync(second_bin,60,0,7,30.0) + call search(390,10,10,.false.,found,ncand) + call require(ncand==2,'separated Q65 signals survive') + call require(has_candidate(found,ncand,first_bin,60,0) .and. & + has_candidate(found,ncand,second_bin,60,0),'both separated frequencies survive') + + call clear_spectra() + call add_sync(first_bin,60,0,11,35.0) + call add_sync(first_bin+2,60,0,11,12.0) + call search(390,10,10,.false.,found,ncand) + call require(ncand==1,'nearby bins form one candidate') + call expect_candidate(found(1),first_bin,60,0,11) + + call clear_spectra() + ss(:,first_bin)=ss(:,first_bin)+40.0 + savg(first_bin)=sum(ss(:,first_bin)) + call search(390,10,10,.false.,found,ncand) + call require(ncand==0,'continuous carrier is not a Q65 candidate') + + call clear_spectra() + call add_sync(first_bin,30,0,9,35.0) + call search(130,0,10,.true.,found,ncand) + call require(ncand==1,'first Q65-30 half is admitted') + call expect_candidate(found(1),first_bin,30,0,9) + call search(130,6,10,.true.,found,ncand) + call require(ncand==0,'first transmit-half gate suppresses reception') + call search(201,0,10,.true.,found,ncand) + call require(ncand==0,'first half is unavailable after its row boundary') + + call clear_spectra() + call add_sync(first_bin,30,1,8,35.0) + call search(390,10,0,.true.,found,ncand) + call require(ncand==1,'second Q65-30 half is admitted') + call expect_candidate(found(1),first_bin,30,1,8) + call search(390,10,6,.true.,found,ncand) + call require(ncand==0,'second transmit-half gate suppresses reception') + call search(329,10,0,.true.,found,ncand) + call require(ncand==0,'second half is unavailable before its row boundary') + + call clear_spectra() + call add_sync(first_bin,60,0,11,35.0) + call search(199,10,10,.false.,found,ncand) + call require(ncand==0,'Q65-60 requires its available-row gate') + call search(200,10,10,.false.,found,ncand) + call require(ncand==1,'Q65-60 opens at its available-row boundary') + call search_selected(first_bin,found,ncand) + call require(ncand==1,'selected search includes its frequency bin') + call search_selected(second_bin,found,ncand) + call require(ncand==0,'selected search excludes a distant frequency bin') + + print '(a)', 'QMAP candidate contracts passed' + +contains + + subroutine clear_spectra() + integer :: bin,row + real :: floor(400) + do row=1,400 + floor(row)=1.0+0.002*real(mod(17*row,23)) + enddo + do bin=1,nfft + ss(:,bin)=floor+0.0002*real(mod(bin,17)) + savg(bin)=sum(ss(:,bin)) + enddo + end subroutine clear_spectra + + subroutine add_sync(bin,period,sequence,lag,power) + integer, intent(in) :: bin,period,sequence,lag + real, intent(in) :: power + integer :: i,row,rows,stride + rows=4 + stride=4 + if(period==30) then + rows=2 + stride=2 + endif + do i=1,size(sync_symbols) + row=stride*(sync_symbols(i)-1)+1+lag+sequence*200 + ss(row:row+rows-1,bin)=ss(row:row+rows-1,bin)+power + enddo + savg(bin)=sum(ss(:,bin)) + end subroutine add_sync + + subroutine search(nhsym,ntx30a,ntx30b,also30,candidates,count) + integer, intent(in) :: nhsym,ntx30a,ntx30b + logical, intent(in) :: also30 + type(candidate), intent(out) :: candidates(50) + integer, intent(out) :: count + real :: fresh_savg(nfft) + logical(kind=1) :: search30 + fresh_savg=savg + search30=also30 + count=-1 + call getcand2(ss,fresh_savg,2,0,nhsym,ntx30a,ntx30b,100,0.0,search30,candidates,count) + end subroutine search + + subroutine search_selected(selected_bin,candidates,count) + integer, intent(in) :: selected_bin + type(candidate), intent(out) :: candidates(50) + integer, intent(out) :: count + real :: fresh_savg(nfft) + logical(kind=1) :: search30 + fresh_savg=savg + search30=.false. + count=-1 + call getcand2(ss,fresh_savg,2,1,390,10,10,0,selected_bin*df/1000.0, & + search30,candidates,count) + end subroutine search_selected + + logical function has_candidate(candidates,count,bin,period,sequence) + type(candidate), intent(in) :: candidates(50) + integer, intent(in) :: count,bin,period,sequence + integer :: i + has_candidate=.false. + do i=1,count + if(abs(candidates(i)%f-bin*df/1000.0)0) then + if(trim(period_arg)/='30') error stop 'Expected a 30-second Q65 period' + period=30 + endif + iseq=0 + nts_q65=1 + if(period==30) then + iseq=1 + nts_q65=2 + endif + symbol_samples=period*sample_rate/100 + first_sample=(1+30*iseq)*sample_rate + + call random_seed(size=seed_size) + allocate(seed(seed_size)) + seed=104729 + call random_seed(put=seed) + call random_number(dd) + dd=2.0*(dd-0.5) + ss=0.0 + savg=0.0 + fcenter=144.125_real64 + nutc=100 + + phase=0.0_real64 + amplitude=160.0_real64 + do symbol=1,q65_nsymbols + frequency=sync_hz+real(q65_tones(symbol),real64)*real(sample_rate,real64)/real(symbol_samples,real64) + omega=twopi*frequency/real(sample_rate,real64) + do i=1,symbol_samples + k=first_sample+(symbol-1)*symbol_samples+i + phase=phase+omega + if(phase>twopi) phase=phase-twopi + dd(1,k)=dd(1,k)+real(amplitude*cos(phase)) + dd(2,k)=dd(2,k)-real(amplitude*sin(phase)) + enddo + enddo + + call init_timer() + nb=0 + nbslider=40 + slimit=0.0 + ihsym=0 + do i=1,390 + k=28800+(i-1)*14400 + call symspec(k,1,nb,nbslider,sample_rate,pxdb,display,nkh,ihsym,nzap,slimit,lstrong) + enddo + call require(ihsym==390, 'complete QMAP symbol spectra') + + savg_fresh=savg + also30=period==30 + call getcand2(ss,savg_fresh,nts_q65,1,ihsym,0,0,15,real(sync_hz/1000.0_real64), & + also30,cand,ncand) + selected=0 + do i=1,ncand + if(cand(i)%ntrperiod/=period .or. cand(i)%iseq/=iseq) cycle + if(abs(1000.0*cand(i)%f-real(sync_hz))>10.0) cycle + selected=i + exit + enddo + call require(selected>0, 'find generated Q65 sync candidate') + + call fftbig(dd,nsmax) + ndecodes=0 + open(unit=12,status='scratch') + datetime='2026-09-23 12:00:00 ' + click=.false. + idec=-1 + call q65b(nutc,0,fcenter,0,sample_rate,125,0,100,period,iseq, & + 'N0CALL ',' ',' ',1,cand(selected)%f,1.270,125, & + 1,0,click,0,0,3,datetime,0,0,ihsym,idec) + call require(nsnr0 > -99, 'decode generated Q65 signal') + call require(trim(msg0)=='K1ABC W9XYZ FN42', 'recover generated Q65 message') + call require(abs(nfreq0-1000)<20, 'QMAP decoder reports centered audio frequency') + call require(abs(xdt0)<0.5, 'QMAP decoder reports generated timing') + call require(ndecodes==1 .and. index(result(1),'K1ABC W9XYZ FN42')>0, & + 'QMAP publishes decoded message') + if(period==30) call require(result(1)(1:6)=='010030', 'second-half decode uses the :30 time') + call fini_timer() + print '(a,i0,a)', 'QMAP generated Q65 ',period,'-second connection passed.' + +contains + + subroutine require(condition,description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine require +end program test_qmap_q65_connection diff --git a/tests/unit/qmap/test_qmap_q65_handoff.f90 b/tests/unit/qmap/test_qmap_q65_handoff.f90 new file mode 100644 index 00000000..96d68775 --- /dev/null +++ b/tests/unit/qmap/test_qmap_q65_handoff.f90 @@ -0,0 +1,116 @@ +program test_qmap_q65_handoff + use iso_fortran_env, only: int16, real64 + use cacb_mod, only: ca, init_cacb + use qmap_q65_samples_mod, only: build_q65_samples + implicit none + + integer, parameter :: nfft2=336000, nfft1=5376000, k0=2600000, sample_rate=12000 + real, parameter :: df=96000.0/nfft1 + real, parameter :: filter_amplitude=100000000.0 + integer(int16), allocatable :: desired(:), wave(:) + complex, allocatable :: spectrum(:) + integer :: i,j + real(real64) :: t, filter_reference_rms + + allocate(desired(720000),wave(720000),spectrum(0:nfft2)) + desired=0 + do i=1,27*sample_rate + t=real(i-1,real64)/real(sample_rate,real64) + desired(i)=int(nint(100.0_real64*sin(2.0_real64*acos(-1.0_real64)*1000.0_real64*t)),int16) + enddo + do i=31*sample_rate+1,55*sample_rate + t=real(i-1,real64)/real(sample_rate,real64) + desired(i)=int(nint(100.0_real64*sin(2.0_real64*acos(-1.0_real64)*1200.0_real64*t)),int16) + enddo + + do i=0,nfft2-1 + j=nfft2-1-i + spectrum(j)=cmplx(real(desired(2*i+2)),real(desired(2*i+1))) + enddo + spectrum(nfft2)=0. + call four2a(spectrum,2*nfft2,1,-1,0) + call init_cacb(nfft1) + ca=0. + ca(k0:k0+nfft2-1)=0.5*spectrum(0:nfft2-1) + + call build_q65_samples(k0,nfft2,df,0,wave) + call expect_samples(wave,desired,2*sample_rate+1,3*sample_rate,0, & + 'first half preserves 1000 Hz level and phase') + call require(mean_power(wave,27*sample_rate+1,30*sample_rate) < 1.0_real64, & + 'first-half guard is quiet') + call require(all(wave(2*nfft2+1:)==0), '56-second extraction has a zero tail') + call require(maxval(abs(int(wave))) < 1000, 'samples do not clip') + + call build_q65_samples(k0,nfft2,df,1,wave) + call require(mean_power(wave,sample_rate/4+1,3*sample_rate/4) < 1.0_real64, & + 'second-half onset begins with quiet samples') + call expect_samples(wave,desired,sample_rate+sample_rate/4+1,sample_rate+3*sample_rate/4, & + 30*sample_rate,'second-half selection preserves 1200 Hz level, phase, and timing') + call require(mean_power(wave,25*sample_rate+1,30*sample_rate) < 1.0_real64, & + 'second-half tail is quiet') + call require(maxval(abs(int(wave))) < 1000, 'selected samples do not clip') + + call set_filter_tone(1000) + call build_q65_samples(k0,nfft2,df,0,wave) + filter_reference_rms=sqrt(mean_power(wave,1,sample_rate)) + call expect_filter(250,0.5_real64) + call expect_filter(2750,0.5_real64) + call expect_filter(3500,0.0_real64) + + print '(a)', 'QMAP Q65 sample handoff contracts passed.' + +contains + + subroutine expect_samples(actual,expected,first,last,offset,description) + integer(int16), intent(in) :: actual(:),expected(:) + integer, intent(in) :: first,last,offset + character(len=*), intent(in) :: description + integer :: index + + do index=first,last + if(abs(int(actual(index))-int(expected(index+offset)))>2) then + print '(a,i0)', 'FAIL: '//description//' at sample ',index + error stop 1 + endif + enddo + end subroutine expect_samples + + subroutine set_filter_tone(frequency) + integer, intent(in) :: frequency + ca=0. + ca(k0+nint(real(frequency)/df))=cmplx(filter_amplitude,0.0) + end subroutine set_filter_tone + + subroutine expect_filter(frequency,expected_ratio) + integer, intent(in) :: frequency + real(real64), intent(in) :: expected_ratio + real(real64) :: ratio + character(len=16) :: label + + call set_filter_tone(frequency) + call build_q65_samples(k0,nfft2,df,0,wave) + ratio=sqrt(mean_power(wave,1,sample_rate))/filter_reference_rms + write(label,'(i0,a)') frequency,' Hz' + call require(abs(ratio-expected_ratio)<0.01_real64,'filter response at '//trim(label)) + end subroutine expect_filter + + real(real64) function mean_power(samples,first,last) + integer(int16), intent(in) :: samples(:) + integer, intent(in) :: first,last + integer :: index + mean_power=0.0_real64 + do index=first,last + mean_power=mean_power+real(samples(index),real64)**2 + enddo + mean_power=mean_power/real(last-first+1,real64) + end function mean_power + + subroutine require(condition,description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine require +end program test_qmap_q65_handoff diff --git a/tests/unit/qmap/test_qmap_symspec_contract.f90 b/tests/unit/qmap/test_qmap_symspec_contract.f90 new file mode 100644 index 00000000..2373185b --- /dev/null +++ b/tests/unit/qmap/test_qmap_symspec_contract.f90 @@ -0,0 +1,67 @@ +program test_qmap_symspec_contract + use iso_fortran_env, only: real32, real64 + implicit none + + integer, parameter :: nfft = 32768, sample_rate = 96000 + integer, parameter :: bins(3) = [4000, 4300, 4600] + real(real32), parameter :: pi = 3.14159265358979323846_real32 + real(real32) :: dd(2,60*sample_rate), ss(400,nfft), savg(nfft), junk(42) + real(real64) :: fcenter + integer :: nutc + common /datcom/ dd, ss, savg, fcenter, nutc, junk + real(real32) :: waterfall(nfft), pxdb, slimit, phase, powers(3) + complex(real32) :: x + logical(kind=1) :: lstrong(0:1023) + integer :: i, k, ihsym, nzap, nkhz + + dd = 0.0 + ss = 0.0 + savg = 0.0 + fcenter = 144.125_real64 + do i = 1, nfft + 512 + phase = 2.0_real32*pi*real(i-1, real32)/real(nfft, real32) + x = tone(bins(1), phase) + 2.0_real32*tone(bins(2), phase) & + + tone(bins(3), phase + 0.71_real32) + dd(1,i) = real(x) + dd(2,i) = aimag(x) + end do + + k = nfft + ihsym = 0 + nzap = 0 + slimit = 0.0 + call symspec(k, 1, 0, 40, sample_rate, pxdb, waterfall, nkhz, ihsym, nzap, slimit, lstrong) + call require(ihsym == 1, 'first completed row') + call require(abs(maxloc(ss(1,:), dim=1) - (bins(2) + 1)) <= 1, 'strongest frequency bin') + do i = 1, 3 + powers(i) = ss(1,bins(i)+1) + call require(powers(i) > 0.0_real32, 'tone power') + call require(abs(savg(bins(i)+1) / powers(i) - 1.0_real32) < 0.001_real32, & + 'savg accumulates completed row') + end do + call require(abs(powers(2) / powers(1) - 4.0_real32) < 0.12_real32, 'amplitude squared power') + call require(abs(powers(3) / powers(1) - 1.0_real32) < 0.03_real32, 'phase preserves power') + print '(a)', 'QMAP symspec contract passed.' + +contains + + function tone(bin, angle) result(value) + integer, intent(in) :: bin + real(real32), intent(in) :: angle + complex(real32) :: value + real(real32) :: theta + + theta = real(bin, real32) * angle + value = 300.0_real32 * cmplx(cos(theta), -sin(theta), real32) + end function tone + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require +end program test_qmap_symspec_contract diff --git a/tests/unit/streaming/CMakeLists.txt b/tests/unit/streaming/CMakeLists.txt index 5a367f45..4db80617 100644 --- a/tests/unit/streaming/CMakeLists.txt +++ b/tests/unit/streaming/CMakeLists.txt @@ -1,16 +1,35 @@ add_executable (test_streaming_consumers test_streaming_consumers.cpp) +add_dependencies (test_streaming_consumers test_decoder_engine_q65 test_decoder_engine_fst4) target_link_libraries (test_streaming_consumers Qt5::Test) target_compile_definitions (test_streaming_consumers PRIVATE JT9_EXECUTABLE="$" WSPRD_EXECUTABLE="$" + FST4_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/fst4-engine.wav" + FST4W_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/fst4w-engine.wav" + Q65_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/q65-engine.wav" ) add_test (NAME test_streaming_consumers COMMAND test_streaming_consumers) set_tests_properties (test_streaming_consumers PROPERTIES LABELS "streaming;runtime" - TIMEOUT 120 + TIMEOUT 360 + FIXTURES_REQUIRED "q65_engine_wav;fst4_engine_wav;fst4w_engine_wav" ) if (WSJT_ENABLE_TSAN) set_tests_properties (test_streaming_consumers PROPERTIES ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_fortran_options}") endif () + +add_executable (test_streaming_period test_streaming_period.f90) +wsjt_link_common_fortran (test_streaming_period) +add_test (NAME test_streaming_period COMMAND test_streaming_period) +set_tests_properties (test_streaming_period PROPERTIES LABELS "streaming") + +add_executable (test_streaming_apply ${PROJECT_SOURCE_DIR}/test/apply_routing_test.f90) +wsjt_link_common_fortran (test_streaming_apply) +add_test (NAME test_streaming_apply COMMAND test_streaming_apply) +set_tests_properties (test_streaming_apply PROPERTIES LABELS "streaming") +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_streaming_apply PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_fortran_options}") +endif () diff --git a/tests/unit/streaming/test_streaming_consumers.cpp b/tests/unit/streaming/test_streaming_consumers.cpp index ba605fe1..91ed0e2e 100644 --- a/tests/unit/streaming/test_streaming_consumers.cpp +++ b/tests/unit/streaming/test_streaming_consumers.cpp @@ -1,16 +1,20 @@ #include +#include #include +#include #include #include #include #include +#include namespace { constexpr quint32 Jt9AudioCapacityBytes = 30u * 60u * 12000u * 2u; constexpr quint32 WsprdAudioCapacityBytes = 8u * 114u * 12000u * 2u; -constexpr int Ft4PeriodSamples = 21 * 3456; +// FT4's 7.5 s period at 12 kHz. +constexpr int Ft4PeriodSamples = 90000; constexpr int Jt9TenSecondPeriodSamples = 10 * 12000; struct ProcessResult @@ -158,16 +162,6 @@ ParsedEvents parseEvents (QByteArray const& output) return parsed; } } - if (type == "warning" && - (!event.value ("code").isString () || - event.value ("code").toString ().isEmpty () || - !event.value ("discarded_samples").isDouble () || - event.value ("discarded_samples").toDouble () < 0.0)) - { - parsed.error = QString {"invalid warning event: %1"}.arg ( - QString::fromUtf8 (line)); - return parsed; - } parsed.values.append (event); } return parsed; @@ -244,6 +238,128 @@ class TestStreamingConsumers final : public QObject Q_OBJECT private slots: + void fst4DecodesWaveform_data () + { + QTest::addColumn ("mode"); + QTest::addColumn ("path"); + QTest::addColumn ("period"); + QTest::addColumn ("message"); + QTest::newRow ("fst4-15") << QString {"FST4"} << QString::fromUtf8 (FST4_ENGINE_WAV) + << 15 << QString {"K1ABC W9XYZ FN42"}; + QTest::newRow ("fst4w-120") << QString {"FST4W"} << QString::fromUtf8 (FST4W_ENGINE_WAV) + << 120 << QString {"K1ABC FN42 37"}; + } + + void fst4DecodesWaveform () + { + QFETCH (QString, mode); + QFETCH (QString, path); + QFETCH (int, period); + QFETCH (QString, message); + QFile recording {path}; + QVERIFY2 (recording.open (QIODevice::ReadOnly), qPrintable (recording.errorString ())); + auto const wav = recording.readAll (); + QCOMPARE (wav.size (), 44 + period * 12000 * 2); + QCOMPARE (wav.left (4), QByteArray {"RIFF"}); + QCOMPARE (wav.mid (36, 4), QByteArray {"data"}); + QJsonObject configuration {{"t", "configure"}, {"mode", mode}, {"trperiod", period}, + {"depth_level", 1}, {"nfa", 1300}, {"nfb", 1700}, {"rxfreq", 1500}, + {"noise_blanker_level", 0}, {"utc", "00:15:00"}}; + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const input = sessionHeader () + controlFrame ( + QJsonDocument {configuration}.toJson (QJsonDocument::Compact)) + frame (0x01u, wav.mid (44)); + auto const result = runProcess (QString::fromUtf8 (JT9_EXECUTABLE), + {"-a", directory.path (), "-t", directory.path (), "--stream"}, input, directory.path (), 360000); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + bool found = false; + for (auto const& decode : eventsMatching (events.values, "decode")) + { + QCOMPARE (decode.value ("mode").toString (), QString {"FST4"}); + found |= decode.value ("message").toString ().trimmed () == message; + } + QVERIFY2 (found, result.standardOutput.constData ()); + QCOMPARE (eventsMatching (events.values, "decode_finished").size (), 1); + } + + void fst4PartialEofCompletesOnce () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const input = sessionHeader () + controlFrame ( + R"({"t":"configure","mode":"FST4W","trperiod":120,"depth_level":1,"nutc":15})") + + silentAudioFrame (12001); + auto const result = runProcess (QString::fromUtf8 (JT9_EXECUTABLE), + {"-a", directory.path (), "-t", directory.path (), "--stream"}, input, directory.path ()); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + QCOMPARE (eventsMatching (events.values, "decode").size (), 0); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), QString {"001500"}); + } + + void q65DecodesWaveform () + { + QFile recording {QString::fromUtf8 (Q65_ENGINE_WAV)}; + QVERIFY2 (recording.open (QIODevice::ReadOnly), qPrintable (recording.errorString ())); + auto const wav = recording.readAll (); + constexpr quint32 sampleBytes = 15 * 12000 * 2; + QCOMPARE (wav.size (), int (44 + sampleBytes)); + QCOMPARE (wav.left (4), QByteArray {"RIFF"}); + QCOMPARE (wav.mid (8, 8), QByteArray {"WAVEfmt "}); + QCOMPARE (qFromLittleEndian (wav.constData () + 16), quint32 (16)); + QCOMPARE (qFromLittleEndian (wav.constData () + 20), quint16 (1)); + QCOMPARE (qFromLittleEndian (wav.constData () + 22), quint16 (1)); + QCOMPARE (qFromLittleEndian (wav.constData () + 24), quint32 (12000)); + QCOMPARE (qFromLittleEndian (wav.constData () + 34), quint16 (16)); + QCOMPARE (wav.mid (36, 4), QByteArray {"data"}); + QCOMPARE (qFromLittleEndian (wav.constData () + 40), sampleBytes); + + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const input = sessionHeader () + controlFrame ( + R"({"t":"configure","mode":"Q65","trperiod":15,"submode":0,"depth_level":1,"nfa":1300,"nfb":1700,"rxfreq":1500,"utc":"00:15:00"})") + + frame (0x01u, wav.mid (44)) + controlFrame (R"({"t":"halt"})"); + auto const result = runProcess (QString::fromUtf8 (JT9_EXECUTABLE), + {"-a", directory.path (), "-t", directory.path (), "--stream"}, input, directory.path ()); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + auto const decodes = eventsMatching (events.values, "decode"); + QVERIFY2 (!decodes.isEmpty (), result.standardOutput.constData ()); + bool found = false; + for (auto const& decode : decodes) + { + QCOMPARE (decode.value ("mode").toString (), QString {"Q65"}); + QCOMPARE (decode.value ("time").toString (), QString {"001500"}); + found |= decode.value ("message").toString ().trimmed () == "K1ABC W9XYZ FN42"; + } + QVERIFY2 (found, result.standardOutput.constData ()); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), QString {"001500"}); + + QFile curves {directory.filePath ("red.dat")}; + QVERIFY2 (curves.open (QIODevice::ReadOnly), qPrintable (curves.errorString ())); + auto const rows = curves.readAll ().trimmed ().split ('\n'); + QVERIFY (rows.size () > 1); + for (auto const& row : rows) + { + auto const values = row.simplified ().split (' '); + QCOMPARE (values.size (), 3); + for (auto const& value : values) + { + bool ok; + auto const number = value.toDouble (&ok); + QVERIFY (ok && std::isfinite (number)); + } + } + } + void jt9RejectsOversizedFrames_data () { QTest::addColumn ("declaredLength"); @@ -280,10 +396,8 @@ private slots: verifyCompleted (result, 0); auto const events = verifyEvents (result); QCOMPARE (eventsMatching (events.values, "error", "unknown_mode").size (), 1); - auto const warnings = eventsMatching ( - events.values, "warning", "period_boundary_discard"); - QCOMPARE (warnings.size (), 1); - QCOMPARE (warnings.front ().value ("discarded_samples").toInt (), 2); + // The two samples past the 10 s period open the next period, drained at EOF. + QCOMPARE (eventsMatching (events.values, "decode_finished").size (), 2); } void jt9RejectsOutOfRangeTrperiod_data () @@ -306,22 +420,59 @@ private slots: QCOMPARE (eventsMatching (events.values, "decode").size (), 0); } - void jt9ReportsBoundaryDiscardOnce () + // A straddling frame carries its remainder into the next period. + void jt9CarriesStraddlingFrameIntoNextPeriod () { auto const exact = runJt9 (sessionHeader () + silentAudioFrame (Ft4PeriodSamples), {"--ft4"}); verifyCompleted (exact, 0); auto const exactEvents = verifyEvents (exact); - QCOMPARE (eventsMatching (exactEvents.values, "warning").size (), 0); + QCOMPARE (eventsMatching (exactEvents.values, "decode_finished").size (), 1); - auto const overflow = runJt9 ( + auto const straddle = runJt9 ( sessionHeader () + silentAudioFrame (Ft4PeriodSamples + 2), {"--ft4"}); - verifyCompleted (overflow, 0); - auto const overflowEvents = verifyEvents (overflow); - auto const warnings = eventsMatching ( - overflowEvents.values, "warning", "period_boundary_discard"); - QCOMPARE (warnings.size (), 1); - QCOMPARE (warnings.front ().value ("discarded_samples").toInt (), 2); + verifyCompleted (straddle, 0); + auto const straddleEvents = verifyEvents (straddle); + QCOMPARE (eventsMatching (straddleEvents.values, "decode_finished").size (), 2); + + // The decoder's share alone is not a period; the EOF drain reports it. + auto const decoderOnly = runJt9 ( + sessionHeader () + silentAudioFrame (21 * 3456), {"--ft4"}); + verifyCompleted (decoderOnly, 0); + auto const decoderOnlyEvents = verifyEvents (decoderOnly); + QCOMPARE (eventsMatching (decoderOnlyEvents.values, "decode_finished").size (), 1); + } + + // A configure that changes the period starts a new one; nothing of the + // old period drains at the new length. + void jt9StartsANewPeriodOnATrperiodChange () + { + // Half a 10 s period, a change to 20 s, then exactly one 20 s period. + auto const result = runJt9 ( + sessionHeader () + + controlFrame (R"({"t":"configure","trperiod":10})") + + silentAudioFrame (Jt9TenSecondPeriodSamples / 2) + + controlFrame (R"({"t":"configure","trperiod":20})") + + silentAudioFrame (2 * Jt9TenSecondPeriodSamples), {"-9"}); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "decode_finished").size (), 1); + } + + // Repeating the current configuration mid-period leaves the period alone. + void jt9KeepsThePeriodOnAnUnchangedConfigure () + { + // Half a 10 s period, the same configuration again, then the other half + // plus two samples: one full period, and the two samples open the next. + auto const result = runJt9 ( + sessionHeader () + + controlFrame (R"({"t":"configure","mode":"JT9","trperiod":10})") + + silentAudioFrame (Jt9TenSecondPeriodSamples / 2) + + controlFrame (R"({"t":"configure","mode":"JT9","trperiod":10})") + + silentAudioFrame (Jt9TenSecondPeriodSamples / 2 + 2), {"-9"}); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "decode_finished").size (), 2); } void wsprdRejectsOversizedFrames_data () diff --git a/tests/unit/streaming/test_streaming_period.f90 b/tests/unit/streaming/test_streaming_period.f90 new file mode 100644 index 00000000..6ac3ed0b --- /dev/null +++ b/tests/unit/streaming/test_streaming_period.f90 @@ -0,0 +1,116 @@ +program test_streaming_period + use streaming_period, only: period_state, period_begin, period_room, & + period_take, period_full, period_ready + implicit none + + integer, parameter :: NMAX = 1800 * 12000 + integer :: nfail = 0 + + call sizes() + call frames_of_128('FT8', 8, 15.d0, 180000, 50 * 3456) + call frames_of_128('FT4', 5, 7.5d0, 90000, 21 * 3456) + call straddle() + call short_periods() + + if (nfail .eq. 0) then + print '(a)', 'ALL STREAMING PERIOD CHECKS PASSED' + else + print '(a,i0,a)', 'STREAMING PERIOD: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + print '(a,a)', ' PASS ', label + else + print '(a,a)', ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + subroutine sizes() + type(period_state) :: st + call period_begin(st, 15.d0, 8, NMAX) + call ok('FT8: period 180000, decoder 172800', & + st%nperiod .eq. 180000 .and. st%npts .eq. 50 * 3456) + call period_begin(st, 7.5d0, 5, NMAX) + call ok('FT4: period 90000, decoder 72576', & + st%nperiod .eq. 90000 .and. st%npts .eq. 21 * 3456) + call period_begin(st, 60.d0, 9, NMAX) + call ok('JT9: period 720000, decoder 720000', & + st%nperiod .eq. 720000 .and. st%npts .eq. 720000) + call period_begin(st, 30.d0, 8, NMAX) + call ok('FT8 at 30 s: decoder still 172800, period 360000', & + st%nperiod .eq. 360000 .and. st%npts .eq. 50 * 3456) + end subroutine sizes + + subroutine frames_of_128(name, mode, tr, nperiod, npts) + character(len=*), intent(in) :: name + integer, intent(in) :: mode, nperiod, npts + real(8), intent(in) :: tr + type(period_state) :: st + integer :: left, ntake, nacc, iperiod, consumed, fed, ready_at + logical :: good + good = .true. + left = 0 + do iperiod = 1, 3 + call period_begin(st, tr, mode, NMAX) + consumed = 0; fed = 0; ready_at = -1 + do while (.not. period_full(st)) + if (left .eq. 0) left = 128 + ntake = period_room(st, left) + call period_take(st, ntake, nacc) + left = left - ntake + consumed = consumed + ntake + fed = fed + nacc + if (ready_at .lt. 0 .and. period_ready(st)) ready_at = consumed + end do + ! `left` is what the frame crossing this boundary owes the next period. + good = good .and. consumed .eq. nperiod .and. fed .eq. npts & + .and. ready_at .ge. npts .and. ready_at .lt. npts + 128 & + .and. left .eq. mod(128 - mod(iperiod * nperiod, 128), 128) + end do + call ok(name // ': three periods of 128-sample frames — nperiod consumed,' & + // ' npts to the decoder, ready within a frame of npts, remainder carried', good) + end subroutine frames_of_128 + + subroutine straddle() + type(period_state) :: st + integer :: ntake, nacc, left + call period_begin(st, 7.5d0, 5, NMAX) + call period_take(st, 90000 - 100, nacc) + left = 128 + ntake = period_room(st, left) + call ok('straddle: a 128-sample frame 100 short of the boundary yields 100', & + ntake .eq. 100) + call period_take(st, ntake, nacc) + left = left - ntake + call ok('straddle: the period is full and 28 samples remain', & + period_full(st) .and. left .eq. 28) + call period_begin(st, 7.5d0, 5, NMAX) + ntake = period_room(st, left) + call period_take(st, ntake, nacc) + call ok('straddle: the next period opens with those 28, all to the decoder', & + ntake .eq. 28 .and. nacc .eq. 28 .and. st%kperiod .eq. 28 .and. st%k .eq. 28) + call ok('straddle: nothing past the decoder share reaches it', & + period_room(st, 100000) .eq. 90000 - 28) + end subroutine straddle + + subroutine short_periods() + type(period_state) :: st + call period_begin(st, 1.d0, 5, NMAX) + call ok('FT4 at 1 s: period stretched to the decoder share, 72576', & + st%nperiod .eq. st%npts .and. st%npts .eq. 21 * 3456) + call period_begin(st, 15.d0, 8, 100000) + call ok('small buffer: decoder share capped at the buffer, period 180000', & + st%npts .eq. 100000 .and. st%nperiod .eq. 180000) + call period_begin(st, 0.d0, 9, NMAX) + call ok('zero TRperiod: one second of decoder share, period the same', & + st%npts .eq. 12000 .and. st%nperiod .eq. 12000) + end subroutine short_periods + +end program test_streaming_period diff --git a/tests/unit/superfox/test_superfox_unpack.f90 b/tests/unit/superfox/test_superfox_unpack.f90 index 8a243ed4..99e7be01 100644 --- a/tests/unit/superfox/test_superfox_unpack.f90 +++ b/tests/unit/superfox/test_superfox_unpack.f90 @@ -1,14 +1,48 @@ +module superfox_unpack_fixture + use iso_c_binding, only: c_ptr,c_f_pointer,c_int + use decoder_engine_types, only: superfox_observation + implicit none + integer*1 :: xdec(0:49) + type(superfox_observation) :: records(12) +contains + subroutine observe(context,record) + type(c_ptr), intent(in) :: context + type(superfox_observation), intent(in) :: record + integer(c_int), pointer :: count + character(len=160) expected + + call c_f_pointer(context,count) + count=count+1 + if(count.gt.size(records)) error stop 'unexpected extra child' + if(record%child_index.ne.count) error stop 'child order changed' + if(any(record%symbols.ne.xdec)) error stop 'accepted QPC frame not preserved' + write(expected,'(i6.6,i4,f5.1,i5,1x,"~",2x,a)') & + 123456,record%snr_db,record%dt_seconds,nint(record%frequency_hz),trim(record%message) + if(trim(record%legacy_line).ne.trim(expected)) error stop 'legacy formatting changed' + records(count)=record + end subroutine observe +end module superfox_unpack_fixture + program test_superfox_unpack + use iso_c_binding, only: c_loc,c_int + use superfox_unpack_fixture, only: observe,xdec,records + use packjt77, only: pack77_state + use sfox_pack_module, only: sfox_pack_for_state + use sfox_unpack_module, only: sfox_unpack_for_state,sfox_render_legacy + use decoder_engine_types, only: sf_kind_cq,sf_kind_exchange, & + sf_kind_free_text,sf_kind_verification implicit none - integer*1 xin(0:49), xdec(0:49) + integer*1 xin(0:49) logical*1 more_cqs, send_msg character*120 line character*26 free_text character*10 ckey character*13 foxcall integer notp, pack_error + integer(c_int), target :: observed_count=0 + type(pack77_state) :: knowledge line='CQ K1JT FN20' free_text='2S/IZFUZBRXJF ' @@ -16,13 +50,42 @@ program test_superfox_unpack more_cqs=.false. send_msg=.true. - call sfox_pack(line,ckey,more_cqs,send_msg,free_text,xin,pack_error) + call sfox_pack_for_state(knowledge,line,ckey,more_cqs,send_msg,free_text,xin,pack_error) if(pack_error.ne.0) error stop 'sfox_pack failed' xdec=xin(49:0:-1) notp=0 foxcall='' - call sfox_unpack(123456,xdec,0,1500.0,0.0,foxcall,notp) + call sfox_unpack_for_state(knowledge,observe,c_loc(observed_count),123456,xdec,0,1500.0,0.0,foxcall,notp) + if(observed_count.ne.2) error stop 'CQ frame must produce CQ and free-text children' + if(records(1)%kind.ne.sf_kind_cq .or. records(2)%kind.ne.sf_kind_free_text) & + error stop 'incorrect CQ frame child kinds' + if(records(1)%message.ne.'CQ K1JT FN20') error stop 'incorrect CQ rendering' + if(records(2)%message.ne.'2S/IZFUZBRXJF') error stop 'incorrect free-text rendering' + if(records(2)%legacy_line_length.ne.50) error stop 'free-text padding changed' + call sfox_render_legacy(c_loc(observed_count),records(1)) + call sfox_render_legacy(c_loc(observed_count),records(2)) + + observed_count=0 + notp=1 + call sfox_unpack_for_state(knowledge,observe,c_loc(observed_count),123456,xdec,0,1500.0,0.0,foxcall,notp) + if(observed_count.ne.3) error stop 'verification must be a separate child' + if(records(3)%kind.ne.sf_kind_verification) error stop 'verification classified as decoded QSO' + if(index(records(3)%message,'$VERIFY$ K1JT ').ne.1) error stop 'verification text changed' + + line='K1JT W1AW K9AN -12' + send_msg=.false. + free_text=' ' + call sfox_pack_for_state(knowledge,line,ckey,more_cqs,send_msg,free_text,xin,pack_error) + if(pack_error.ne.0) error stop 'exchange pack failed' + xdec=xin(49:0:-1) + notp=0 + observed_count=0 + call sfox_unpack_for_state(knowledge,observe,c_loc(observed_count),123456,xdec,-8,1500.0,0.2,foxcall,notp) + if(observed_count.ne.2) error stop 'exchange frame child count changed' + if(any(records(1:2)%kind.ne.sf_kind_exchange)) error stop 'exchange kind changed' + if(records(1)%message.ne.'W1AW K1JT RR73') error stop 'RR73 exchange changed' + if(records(2)%message.ne.'K9AN K1JT -12') error stop 'report exchange changed' end program test_superfox_unpack diff --git a/tests/unit/superfox/test_superfox_unpack_unsupported.f90 b/tests/unit/superfox/test_superfox_unpack_unsupported.f90 index c4f5d86c..5f52c060 100644 --- a/tests/unit/superfox/test_superfox_unpack_unsupported.f90 +++ b/tests/unit/superfox/test_superfox_unpack_unsupported.f90 @@ -1,5 +1,24 @@ +module superfox_unsupported_fixture + use iso_c_binding, only: c_ptr,c_f_pointer,c_int + use decoder_engine_types, only: superfox_observation + implicit none +contains + subroutine observe(context,record) + type(c_ptr), intent(in) :: context + type(superfox_observation), intent(in) :: record + integer(c_int), pointer :: n + call c_f_pointer(context,n) + n=n+1 + write(*,*) 'unexpected child kind for unsupported frame:',record%kind + end subroutine observe +end module superfox_unsupported_fixture + program test_superfox_unpack_unsupported + use iso_c_binding, only: c_loc,c_int + use superfox_unsupported_fixture, only: observe + use packjt77, only: pack77_state + use sfox_unpack_module, only: sfox_unpack_for_state implicit none integer*1 xin(0:49), xdec(0:49) @@ -10,6 +29,8 @@ program test_superfox_unpack_unsupported character*13 foxcall character*329 msgbits integer notp, pack_error + integer(c_int), target :: count=0 + type(pack77_state) :: knowledge line='K1JT W1AW' free_text=' ' @@ -30,6 +51,7 @@ program test_superfox_unpack_unsupported notp=0 foxcall='' call sfox_unpack(123456,xdec,0,1500.0,0.0,foxcall,notp) + call sfox_unpack_for_state(knowledge,observe,c_loc(count),123456,xdec,0,1500.0,0.0,foxcall,notp) + if(count.ne.0) error stop 'unsupported frame emitted typed children' write(*,*) 'unsupported i3=1 ignored' - end program test_superfox_unpack_unsupported diff --git a/tests/unit/tci/test_tci_receive_ownership.cpp b/tests/unit/tci/test_tci_receive_ownership.cpp index 3f061130..760bf29f 100644 --- a/tests/unit/tci/test_tci_receive_ownership.cpp +++ b/tests/unit/tci/test_tci_receive_ownership.cpp @@ -145,11 +145,11 @@ public: server.close (); } - bool start () + bool start (ReceivePolicy policy = ReceivePolicy::Timed) { if (!server.listen ()) return false; QString const address = QStringLiteral ("127.0.0.1:%1").arg (server.port ()); - QMetaObject::invokeMethod (context_, [this, address] { + QMetaObject::invokeMethod (context_, [this, address, policy] { rig = new TCITransceiver (&logger_, {}, "0", address, true, tci__audio, context_, [this] { return clock.now (); }); QObject::connect (rig, &Transceiver::failure, rig, [this] (QString const&) { @@ -162,6 +162,15 @@ public: [this] (ReceiveAudio audio) { receiver_.accept (audio, storage); }, Qt::QueuedConnection); + QObject::connect (rig, &Transceiver::continuousAudioAvailable, &audioContext_, + [this] (JttyReceiveMailboxPtr mailbox) { + continuousMailbox = std::move (mailbox); + }, Qt::QueuedConnection); + QObject::connect (rig, &Transceiver::continuousReceiveDrained, &audioContext_, + [this] (quint64 request, JttyReceiveMailboxPtr mailbox) { + drainedRequest_ = request; + drainedMailbox_ = std::move (mailbox); + }, Qt::QueuedConnection); // A ready message is an ordered fence behind preceding binary frames. QObject::connect (rig, &TCITransceiver::tci_done7, rig, [this] { std::lock_guard lock {fenceMutex_}; @@ -173,6 +182,8 @@ public: state_.frequency (14074000); state_.mode (Transceiver::USB); state_.period (15); + state_.receive_policy (policy); + state_.receive_context (77); state_.audio (true); state_.volume (0); rig->set (state_, 2); @@ -191,6 +202,39 @@ public: return !failed_.load (); } + bool setReceivePolicy (ReceivePolicy policy) + { + auto done = std::make_shared (false); + QMetaObject::invokeMethod (context_, [this, policy, done] { + state_.receive_policy (policy); + rig->set (state_, ++sequence_); + done->store (true); + }, Qt::QueuedConnection); + return server.wait_for ([done] { return done->load (); }, 10000) && !failed_.load (); + } + + bool setReceiveContext (quint64 context) + { + auto done = std::make_shared (false); + QMetaObject::invokeMethod (context_, [this, context, done] { + state_.receive_context (context); + rig->set (state_, ++sequence_); + done->store (true); + }, Qt::QueuedConnection); + return server.wait_for ([done] { return done->load (); }, 10000) && !failed_.load (); + } + + bool setBlockSize (qint32 size) + { + auto done = std::make_shared (false); + QMetaObject::invokeMethod (context_, [this, size, done] { + state_.blocksize (size); + rig->set (state_, ++sequence_); + done->store (true); + }, Qt::QueuedConnection); + return server.wait_for ([done] { return done->load (); }, 10000) && !failed_.load (); + } + bool fence () { std::unique_lock lock {fenceMutex_}; @@ -223,6 +267,23 @@ public: return sent; } + bool incompleteAudioPacket () + { + QByteArray bytes; + if (!TciStream::prepare_float_frame (&bytes, 2)) return false; + auto * header = TciStream::header (&bytes); + header->receiver = 0; + header->sampleRate = 48000; + header->format = TciStream::Float32Format; + header->type = TciStream::RxAudioStream; + header->length = 2; + header->channels = 2; + bytes.chop (sizeof (float)); + bool const sent = server.send_binary (bytes); + server.flush (); + return sent && fence (); + } + bool feed (std::vector const& pcm, std::vector const& chunks = {4096}, int receiver = 0) { @@ -243,6 +304,16 @@ public: return {storage.d2, storage.d2 + storage.params.kin}; } int notifications () const { return notifications_.load (); } + void deliverContinuous () { QCoreApplication::sendPostedEvents (&audioContext_, QEvent::MetaCall); } + bool drainContinuous (quint64 request) + { + QMetaObject::invokeMethod (context_, [this, request] { + static_cast (rig)->requestContinuousReceiveDrain (request); + }, Qt::QueuedConnection); + return server.wait_for ([this, request] { return drainedRequest_ == request; }, 10000) + && drainedMailbox_ == continuousMailbox; + } + JttyReceiveMailboxPtr continuousMailbox; TciSimServer server; ReceiveClock clock; @@ -253,6 +324,8 @@ private: QObject * context_ = nullptr; QObject audioContext_; ReceiveAudioConsumer receiver_; + quint64 drainedRequest_ = 0; + JttyReceiveMailboxPtr drainedMailbox_; Transceiver::TransceiverState state_; unsigned sequence_ = 2; std::atomic_bool started_ {false}, failed_ {false}; @@ -294,6 +367,131 @@ class TestTciReceiveOwnership : public QObject { Q_OBJECT private Q_SLOTS: + void block_size_changes_preserve_captured_partial_audio () + { + Harness h; + QVERIFY (h.start (ReceivePolicy::ContinuousJtty)); + QVERIFY (h.feed (signal (100, 0.125f))); + h.deliverContinuous (); + QVERIFY (h.continuousMailbox); + QVERIFY (h.setBlockSize (-1)); + QVERIFY (h.setBlockSize (0)); + QVERIFY (h.setBlockSize (7 * 512 + 1)); + QVERIFY (h.setBlockSize (block)); + JttyReceiveEvent event; + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + auto const firstSession = event.session; + QVERIFY (!h.continuousMailbox->take (event)); + QVERIFY (h.setBlockSize (256)); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QCOMPARE (event.session, firstSession); + QCOMPARE (event.samples.size (), std::size_t {100}); + QVERIFY (std::any_of (event.samples.begin (), event.samples.end (), + [] (short sample) { return sample != 0; })); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::End); + QCOMPARE (event.firstSample, qint64 {100}); + QVERIFY (!h.continuousMailbox->take (event)); + QVERIFY (h.feed (signal (256, 0.25f))); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QVERIFY (event.session != firstSession); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QCOMPARE (event.firstSample, qint64 {0}); + QCOMPARE (event.samples.size (), std::size_t {256}); + QVERIFY (!h.continuousMailbox->take (event)); + } + + void continuous_audio_retains_partial_packet_across_clock_wrap () + { + Harness h; + QVERIFY (h.start (ReceivePolicy::ContinuousJtty)); + QVERIFY (h.feed (signal (block + 100, 0.125f), {511, 1701, 2047})); + h.clock.set (105000); + QVERIFY (h.feed (signal (block, 0.25f), {777, 512})); + QVERIFY (h.enableAudio (false)); + h.deliverContinuous (); + QVERIFY (h.continuousMailbox); + JttyReceiveEvent event; + quint64 session = 0; + qint64 frames = 0; + bool ended = false; + while (h.continuousMailbox->take (event)) + { + if (event.kind == JttyReceiveEvent::Kind::Begin) + { + QCOMPARE (session, quint64 {0}); + session = event.session; + } + QCOMPARE (event.session, session); + QCOMPARE (event.context, quint64 {77}); + if (event.kind == JttyReceiveEvent::Kind::Samples) + { + QCOMPARE (event.firstSample, frames); + frames = event.endSample (); + } + if (event.kind == JttyReceiveEvent::Kind::End) + { + QCOMPARE (event.firstSample, frames); + ended = true; + } + } + QCOMPARE (frames, qint64 (2 * block + 100)); + QVERIFY (ended); + QCOMPARE (h.notifications (), 0); + QVERIFY (h.setReceiveContext (88)); + QVERIFY (h.enableAudio (true)); + QVERIFY (h.feed (signal (block, 0.125f))); + h.deliverContinuous (); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QCOMPARE (event.context, quint64 {88}); + QVERIFY (event.session != session); + auto const interruptedSession = event.session; + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QVERIFY (!h.continuousMailbox->take (event)); + QVERIFY (h.feed (signal (25, 0.125f))); + QVERIFY (h.incompleteAudioPacket ()); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples); + QCOMPARE (event.samples.size (), std::size_t {25}); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::End); + QCOMPARE (event.reason, JttyReceiveReason::InputError); + QVERIFY (!h.continuousMailbox->take (event)); + QVERIFY (h.feed (signal (block, 0.125f))); + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QVERIFY (event.session != interruptedSession); + QCOMPARE (event.firstSample, qint64 {0}); + QVERIFY (h.enableAudio (false)); + QVERIFY (h.setReceivePolicy (ReceivePolicy::Timed)); + QVERIFY (h.drainContinuous (55)); + QVERIFY (h.enableAudio (true)); + QVERIFY (h.feed (signal (block, 0.125f))); + QCOMPARE (h.snapshot ().size (), std::size_t (block)); + QCOMPARE (h.notifications (), 1); + } + + void continuous_anchor_uses_first_packet_sample_time () + { + Harness h; + h.clock.set (200000); + QVERIFY (h.start (ReceivePolicy::ContinuousJtty)); + std::vector pcm (4096, 0.125f); + QVERIFY (h.feed (pcm)); + h.deliverContinuous (); + QVERIFY (h.continuousMailbox); + JttyReceiveEvent event; + QVERIFY (h.continuousMailbox->take (event)); + QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin); + QCOMPARE (event.anchorUtcMs, qint64 {199915}); + } + void packetization_preserves_audio () { Harness h; -- cgit v1.2.3 From c576a4281ef8c87990ae6399393a827dfaccacd5 Mon Sep 17 00:00:00 2001 From: Christoph Berg Date: Wed, 14 Oct 2026 14:39:20 +0200 Subject: New upstream version 3.3.0~beta2+dfsg --- .github/scripts/build-fftw-macos.sh | 15 + .github/scripts/generate-change-list.py | 154 +++ .github/scripts/generate-quick-downloads.py | 9 +- .github/scripts/tests/test_generate_change_list.py | 263 +++++ .../scripts/tests/test_release_workflow_policy.py | 16 + .github/workflows/public-release.yml | 22 +- CMake/Sources.cmake | 6 +- CMakeLists.txt | 29 +- DecoderEngine.h | 46 +- WavDecodeTestController.cpp | 24 +- WavDecodeTestController.hpp | 2 +- ci-cd/DEPLOYMENT_PLAYBOOK.md | 7 +- ci-cd/DEVELOPMENT_WORKFLOW.md | 2 + lib/decode4.f90 | 112 -- lib/decoder.f90 | 40 +- lib/decoder_callbacks.f90 | 107 +- lib/decoder_engine.f90 | 240 ++++- lib/decoder_engine_types.f90 | 18 +- lib/deep4.f90 | 169 --- lib/extract4.f90 | 18 +- lib/jt4.f90 | 26 +- lib/jt4_decode.f90 | 1071 +++++++++++++++----- lib/jt4_host_support.f90 | 112 ++ lib/jt9.f90 | 3 +- lib/jt9_params_init.f90 | 6 + lib/jt9a.f90 | 5 +- lib/lpf1.f90 | 29 - lib/ps4.f90 | 27 - lib/streaming_apply.f90 | 7 +- lib/streaming_control.f90 | 3 +- lib/streaming_emit.f90 | 27 +- lib/streaming_io.f90 | 5 +- lib/sync4.f90 | 146 --- lib/xcor4.f90 | 30 +- main.cpp | 34 +- map65/commons.cpp | 3 - map65/commons.h | 9 +- map65/libm65/CMakeLists.txt | 5 + map65/libm65/datcom_ptrs_mod.f90 | 79 +- map65/libm65/decode0.f90 | 33 +- map65/libm65/npar_ptrs_mod.f90 | 85 +- map65/libm65/run_m65.f90 | 3 +- map65/mainwindow.cpp | 16 +- release-state.txt | 4 +- .../fixtures/jt4_OK1KIR_141105_175700.expected.txt | 2 +- tests/integration/decoder_engine/run_wav_gui.cmake | 5 +- .../jt9/verify_jt4_12000_read_extent.cmake | 39 +- tests/integration/jt9/verify_jt4_engine.cmake | 19 + tests/unit/decoder_engine/CMakeLists.txt | 56 + tests/unit/decoder_engine/jt4_engine_signal.f90 | 47 + tests/unit/decoder_engine/test_decoder_engine.c | 40 +- .../unit/decoder_engine/test_decoder_engine_jt4.c | 470 +++++++++ .../test_decoder_engine_jt4_host.f90 | 213 ++++ .../test_decoder_engine_jt4_state.f90 | 112 ++ tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp | 37 + tests/unit/jtty/test_jtty_messages.cpp | 48 + tests/unit/jtty/test_jtty_structured_decode.f90 | 29 + tests/unit/map65/test_map65_pass_snapshots.f90 | 100 ++ tests/unit/streaming/CMakeLists.txt | 6 +- tests/unit/streaming/test_streaming_consumers.cpp | 162 ++- widgets/JttyMessages.hpp | 17 + widgets/mainwindow.cpp | 3 +- widgets/mainwindow_jtty.cpp | 73 +- 63 files changed, 3465 insertions(+), 1080 deletions(-) create mode 100644 .github/scripts/generate-change-list.py create mode 100644 .github/scripts/tests/test_generate_change_list.py delete mode 100644 lib/decode4.f90 delete mode 100644 lib/deep4.f90 create mode 100644 lib/jt4_host_support.f90 delete mode 100644 lib/lpf1.f90 delete mode 100644 lib/ps4.f90 delete mode 100644 lib/sync4.f90 create mode 100644 tests/integration/jt9/verify_jt4_engine.cmake create mode 100644 tests/unit/decoder_engine/jt4_engine_signal.f90 create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt4.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 create mode 100644 tests/unit/map65/test_map65_pass_snapshots.f90 (limited to 'tests') diff --git a/.github/scripts/build-fftw-macos.sh b/.github/scripts/build-fftw-macos.sh index cbaf0291..00c24a40 100755 --- a/.github/scripts/build-fftw-macos.sh +++ b/.github/scripts/build-fftw-macos.sh @@ -10,6 +10,20 @@ version="$1" deployment_target="$2" prefix="$3" +architecture="${ARCH:-$(uname -m)}" +case "$architecture" in + x86_64) + simd_flags=(--enable-sse2 --enable-avx) + ;; + arm64) + simd_flags=(--enable-neon) + ;; + *) + echo "Unsupported macOS architecture: $architecture" >&2 + exit 2 + ;; +esac + 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}" @@ -19,6 +33,7 @@ cd "fftw-${version}" --enable-single \ --enable-threads \ --enable-shared --disable-static \ + "${simd_flags[@]}" \ CFLAGS="-O3 -mmacosx-version-min=${deployment_target}" \ LDFLAGS="-mmacosx-version-min=${deployment_target}" make -j"$(sysctl -n hw.ncpu)" diff --git a/.github/scripts/generate-change-list.py b/.github/scripts/generate-change-list.py new file mode 100644 index 00000000..19a73db8 --- /dev/null +++ b/.github/scripts/generate-change-list.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Print a GitHub Release change list from the commit subjects of a public release tag. + +Usage: + generate-change-list.py + +Prints nothing when no earlier release tag exists. +""" +import importlib.util +import re +import subprocess +import sys +from pathlib import Path + + +def load_script(name, filename): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +policy = load_script("release_policy", "release-policy.py") + +SUBJECT_RE = re.compile( + r"^(?P[A-Za-z]+)(?:\((?P[^)]*)\))?(?P!)?:\s*(?P\S.*)$" +) +SECTIONS = (("feat", "New features"), ("fix", "Fixes"), ("perf", "Performance")) +INTERNAL_SCOPES = frozenset(("release", "ci", "test", "tests")) +# Pull request numbers in subjects belong to the private repository; on the public +# release page they would link to unrelated items, and @names would notify people. +TRAILING_PR_RE = re.compile(r"\s*\(#\d+\)$") +REFERENCE_RE = re.compile(r"[\w.-]+/[\w.-]+#\d+|\bGH-\d+\b|(? \n") + return 2 + sys.stdout.write(change_list(argv[1], argv[2])) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/.github/scripts/generate-quick-downloads.py b/.github/scripts/generate-quick-downloads.py index 0ba21c36..7a07c6f1 100755 --- a/.github/scripts/generate-quick-downloads.py +++ b/.github/scripts/generate-quick-downloads.py @@ -4,8 +4,7 @@ The release workflow attaches every build artifact to the Release, which makes the assets list long and hard for an end user to navigate (installers sit among the command-line program tarballs, checksums, the manifest, and source). This emits a -short, curated per-platform installer picker to prepend to the auto-generated -release notes. +short, curated per-platform installer picker to put above the change list. It is *asset-driven*: platforms and architectures are derived from the asset filenames passed in, not hard-coded. New build variants (for example an added @@ -13,7 +12,7 @@ Linux architecture such as armhf) therefore appear in Quick Downloads automatically, with no edit to this script. The block is emitted on stdout, ending at the last platform line (no trailing -separator); the caller joins it to the auto-generated notes. +separator); the caller joins it to the change list. Usage: generate-quick-downloads.py ... @@ -108,8 +107,8 @@ def main(argv): if source: out += ["", "### Source", f"- [{source}]({url(source)})"] - # If nothing matched (no installer-grade assets), emit nothing so the - # caller leaves the auto-generated notes untouched. + # If nothing matched (no installer-grade assets), emit nothing; the caller + # then publishes the change list alone. if len(out) == 4: return 0 diff --git a/.github/scripts/tests/test_generate_change_list.py b/.github/scripts/tests/test_generate_change_list.py new file mode 100644 index 00000000..6d2e707c --- /dev/null +++ b/.github/scripts/tests/test_generate_change_list.py @@ -0,0 +1,263 @@ +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).resolve().parents[1] / "generate-change-list.py" +REPO = "WSJTX/wsjtx" + + +class ChangeListTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.repo = Path(self.directory.name) + self.env = { + **{key: value for key, value in os.environ.items() if not key.startswith("GIT_")}, + "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_EMAIL": "author@example.com", + "GIT_COMMITTER_NAME": "Committer", "GIT_COMMITTER_EMAIL": "committer@example.com", + } + self.git("init", "-q", "-b", "develop") + # Background auto-maintenance would race the directory's removal. + self.git("config", "maintenance.auto", "false") + self.commit("chore: start") + + def stamp(self, author="Test Author"): + # Distinct dates, so a cherry-pick onto the same parent is a real copy. + self.clock = getattr(self, "clock", 0) + 1 + date = f"@{1_700_000_000 + self.clock} +0000" + return {**self.env, "GIT_AUTHOR_NAME": author, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} + + def git(self, *args): + return subprocess.run( + ["git", *args], cwd=self.repo, env=self.stamp(), text=True, capture_output=True, check=True, + ).stdout.strip() + + def commit(self, subject, author="Test Author", change=None): + # A distinct change per commit: git treats all empty commits as cherry-picks of each other. + self.changes = getattr(self, "changes", 0) + 1 + change = change or f"change-{self.changes}.txt" + (self.repo / change).write_text(subject + "\n") + self.git("add", change) + subprocess.run( + ["git", "commit", "-qm", subject], + cwd=self.repo, env=self.stamp(author), check=True, capture_output=True, + ) + return self.git("rev-parse", "HEAD") + + def merge(self, ref, subject): + self.git("merge", "--no-ff", "-qm", subject, ref) + + def notes(self, tag): + result = subprocess.run( + [sys.executable, str(SCRIPT), REPO, tag], + cwd=self.repo, env=self.env, text=True, capture_output=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout + + def test_a_later_beta_lists_the_changes_since_the_previous_beta_in_commit_order(self): + self.git("checkout", "-qb", "release/3.3") + self.commit("feat: old feature") + self.git("tag", "v3.3.0-beta1") + self.commit("feat(decoder): new mode", author="Joe Taylor") + self.commit("fix(wav): keep the dial context", author="David Christle") + self.commit("fix: a later fix") + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n")) + self.assertIn("### New features\n- decoder: new mode (Joe Taylor)\n", notes) + self.assertIn("### Fixes\n- wav: keep the dial context (David Christle)\n- a later fix (Test Author)\n", notes) + self.assertNotIn("old feature", notes) + self.assertIn(f"[Full comparison](https://github.com/{REPO}/compare/v3.3.0-beta1...v3.3.0-beta2).", notes) + + def test_a_spent_beta_number_falls_back_to_the_newest_published_tag(self): + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta1") + self.commit("fix: carried by the unpublished beta2") + self.commit("fix: new in beta3") + self.git("tag", "v3.3.0-beta3") + notes = self.notes("v3.3.0-beta3") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n")) + self.assertIn("- carried by the unpublished beta2", notes) + self.assertIn("- new in beta3", notes) + + def test_a_release_candidate_follows_the_last_beta_of_its_line(self): + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta4") + self.commit("fix: freeze-time fix") + self.git("tag", "v3.3.0-rc1") + notes = self.notes("v3.3.0-rc1") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta4\n")) + self.assertIn("- freeze-time fix", notes) + + def test_a_lines_first_release_leaves_out_what_the_previous_line_shipped(self): + self.commit("feat: in 3.2 already") + self.git("tag", "v3.0.2") + self.git("checkout", "-qb", "release/3.0", "HEAD~1") + self.commit("fix: only on the old line") + self.git("tag", "v3.0.3") + self.git("checkout", "-q", "develop") + self.git("checkout", "-qb", "release/3.2") + self.commit("fix: only on release/3.2") + self.git("checkout", "-q", "develop") + picked = self.commit("fix(gui): picked into 3.2", change="gui.txt") + self.git("checkout", "-q", "release/3.2") + self.git("cherry-pick", picked) + self.git("tag", "v3.2.0-rc1") + self.git("checkout", "-q", "develop") + self.merge("v3.0.3", "Merge 3.0.3 into develop") + self.commit("feat: new on develop") + self.git("checkout", "-qb", "release/3.3") + self.commit("build(release): start 3.3 at BETA 1") + self.git("tag", "v3.3.0-beta1") + notes = self.notes("v3.3.0-beta1") + self.assertTrue(notes.startswith("## Changes since v3.2.0-rc1\n")) + self.assertIn("- new on develop", notes) + for shipped in ("in 3.2 already", "only on release/3.2", "picked into 3.2", "only on the old line"): + self.assertNotIn(shipped, notes) + self.assertIn(f"/compare/v3.2.0-rc1...v3.3.0-beta1", notes) + + def test_a_beta_after_the_previous_ga_is_merged_back_lists_only_new_changes(self): + self.git("checkout", "-qb", "release/3.2") + self.git("tag", "v3.2.0-rc1") + self.git("checkout", "-q", "develop") + original = self.commit("fix(gui): first on develop", change="gui.txt") + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta1") + self.git("checkout", "-q", "release/3.2") + self.git("cherry-pick", original) + self.commit("fix: only on release/3.2") + self.git("tag", "v3.2.0") + self.git("checkout", "-q", "develop") + self.merge("v3.2.0", "Merge 3.2.0 into develop") + self.commit("fix: new on develop") + self.git("checkout", "-q", "release/3.3") + self.merge("develop", "Merge develop into release/3.3") + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n")) + self.assertIn("### Fixes\n- new on develop (Test Author)\n\n", notes) + self.assertNotIn("first on develop", notes) + self.assertNotIn("only on release/3.2", notes) + + def test_copies_that_a_merged_back_ga_shipped_are_not_listed_again(self): + self.git("checkout", "-qb", "release/3.2") + self.commit("fix: on release/3.2 before the picks") + self.git("tag", "v3.2.0-rc1") + self.git("checkout", "-q", "develop") + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta1") + self.git("checkout", "-q", "develop") + original = self.commit("fix(gui): develop original shipped in 3.2.0", change="gui.txt") + self.git("checkout", "-q", "release/3.2") + self.git("cherry-pick", original) + port = self.commit("fix(cat): made on release/3.2 first", change="cat.txt") + self.git("tag", "v3.2.0") + self.git("checkout", "-q", "develop") + self.git("cherry-pick", port) + self.merge("v3.2.0", "Merge 3.2.0 into develop") + self.commit("fix: new on develop") + self.git("checkout", "-q", "release/3.3") + self.merge("develop", "Merge develop into release/3.3") + self.git("tag", "v3.3.0-beta2") + self.git("tag", "v3.3.0") + for tag in ("v3.3.0-beta2", "v3.3.0"): + notes = self.notes(tag) + self.assertIn("### Fixes\n- new on develop (Test Author)\n\n", notes, tag) + self.assertNotIn("develop original", notes, tag) + self.assertNotIn("made on release/3.2 first", notes, tag) + + def test_a_ga_lists_everything_since_the_previous_ga(self): + self.git("tag", "v3.2.0") + self.git("checkout", "-qb", "release/3.3") + self.commit("feat: from beta1") + self.git("tag", "v3.3.0-beta1") + self.commit("fix: from rc1") + self.git("tag", "v3.3.0-rc1") + self.commit("fix: from GA") + self.git("tag", "v3.3.0") + notes = self.notes("v3.3.0") + self.assertTrue(notes.startswith("## Changes since v3.2.0\n")) + for change in ("from beta1", "from rc1", "from GA"): + self.assertIn(change, notes) + self.commit("fix: patch") + self.git("tag", "v3.3.1-rc1") + self.git("tag", "v3.3.1") + patch = self.notes("v3.3.1") + self.assertTrue(patch.startswith("## Changes since v3.3.0\n")) + self.assertIn("- patch", patch) + self.assertNotIn("from GA", patch) + self.assertEqual(self.notes("v3.3.0"), notes) + + def test_entries_are_grouped_cleaned_and_counted(self): + self.git("tag", "v3.3.0-beta1") + self.commit("feat(jtty)!: change the macro syntax") + self.commit("Fix(gui): uppercase type (#458)") + self.commit("fix: address PR #569 review for @k1jt") + self.commit("perf(fft): use SIMD") + self.commit("fix(gui): uppercase type (#458)") + self.commit("fix(jtty, tests): user-facing despite a test scope") + self.commit("fix(release): pipeline change") + self.commit("feat(ci, tests): pipeline feature") + self.commit("test: cover the decoder") + self.commit("Untyped subject that mentions fix") + self.git("checkout", "-qb", "topic") + self.commit("docs: topic change") + self.git("checkout", "-q", "develop") + self.merge("topic", "Merge pull request #12 from topic") + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertIn("### New features\n- jtty: change the macro syntax (breaking) (Test Author)\n\n", notes) + self.assertIn( + "### Fixes\n" + "- gui: uppercase type (Test Author)\n" + "- address PR `#569` review for `@k1jt` (Test Author)\n" + "- jtty, tests: user-facing despite a test scope (Test Author)\n\n", + notes, + ) + self.assertIn("### Performance\n- fft: use SIMD (Test Author)\n", notes) + self.assertNotIn("pipeline", notes) + self.assertNotIn("Merge pull request", notes) + self.assertIn("Plus 5 other commits: [full comparison]", notes) + + def test_references_are_neutralized_outside_code_spans_only(self): + self.git("tag", "v3.3.0-beta1") + for subject in ( + "fix: mail ops@example.com about C# and see https://example.com/docs/#anchor", + "fix: link WSJTX/wsjtx-internal#569, GH-12 and Hamlib/Hamlib#1940", + "fix: keep `a #12 @b` and literal", + "fix(@team): scope reference", + "fix: handle a lone ` in macros, see #12 and @k1jt", + ): + self.commit(subject) + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertIn("- mail ops@example.com about C# and see https://example.com/docs/#anchor (Test Author)\n", notes) + self.assertIn("- link `WSJTX/wsjtx-internal#569`, `GH-12` and `Hamlib/Hamlib#1940` (Test Author)\n", notes) + self.assertIn("- keep `a #12 @b` and <CR> literal (Test Author)\n", notes) + self.assertIn("- `@team`: scope reference (Test Author)\n", notes) + self.assertIn("- handle a lone ` in macros, see `#12` and `@k1jt` (Test Author)\n", notes) + + def test_a_range_without_listed_changes_says_so(self): + self.git("tag", "v3.3.0-beta1") + self.commit("test: only tests") + self.git("tag", "v3.3.0-beta2") + self.assertIn("\nNo user-facing changes; 1 other commit: [full comparison]", self.notes("v3.3.0-beta2")) + self.git("tag", "v3.3.0-beta3") + notes = self.notes("v3.3.0-beta3") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta2\n")) + self.assertIn("No source changes since v3.3.0-beta2.", notes) + + def test_no_earlier_release_tag_prints_nothing(self): + for tag in ("not-a-release", "build/v3.2.0-rc1", "v3.2", "v3.2.0-alpha1", "v3.3.0-beta1"): + self.git("tag", tag) + self.assertEqual(self.notes("v3.3.0-beta1"), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_release_workflow_policy.py b/.github/scripts/tests/test_release_workflow_policy.py index 8765cbe1..68e8c23d 100644 --- a/.github/scripts/tests/test_release_workflow_policy.py +++ b/.github/scripts/tests/test_release_workflow_policy.py @@ -150,6 +150,22 @@ class ReleaseWorkflowPolicyTests(unittest.TestCase): self.assertEqual(len(re.findall(r"^\s+continue$", publish, re.M)), 1) self.assertEqual(publish.count('cmp "$file"'), 1) + def test_a_new_release_body_carries_the_change_list_or_keeps_the_generated_notes(self): + self.assertIn("fetch-depth: 0", job(PUBLIC, "publish")) + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertIn("--generate-notes", publish) + notes = publish[publish.index('if [ "$CREATED" = true ]; then'):] + self.assertIn('CHANGES=$(python3 .github/scripts/generate-change-list.py \\\n' + ' "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME" || true)', notes) + self.assertRegex(notes, r'if \[ -z "\$CHANGES" \]; then\s+echo "::warning::[^"]*"\s+' + r'CHANGES=\$\(gh release view "\$GITHUB_REF_NAME" --json body --jq \.body \|\| true\)') + # Notes never fail a publication, and a body without changes never replaces GitHub's notes. + edit = notes.index("gh release edit") + self.assertRegex(notes[:edit], r'if \[ -z "\$CHANGES" \]; then\s+echo "::warning::[^"]*"\s+else\s+NOTES=\$CHANGES\s') + self.assertRegex(notes[edit:], r'^gh release edit "\$GITHUB_REF_NAME" --notes-file "\$RUNNER_TEMP/release-notes.md" \\\n' + r'\s+\|\| echo "::warning::[^"]*"\n\s+fi\n') + self.assertEqual(notes.count("gh release edit"), 1) + def test_windows_signing_guard_admits_only_rc_and_ga(self): guard = step(SIGN, "Require a public RC or GA invocation") self.assertIn('test "$(jq -r .channel <<<"$IDENTITY")" = "$CHANNEL"', guard) diff --git a/.github/workflows/public-release.yml b/.github/workflows/public-release.yml index f515a6fd..2792f7ee 100644 --- a/.github/workflows/public-release.yml +++ b/.github/workflows/public-release.yml @@ -455,11 +455,23 @@ jobs: if [ "$CREATED" = true ]; then QUICK_DOWNLOADS=$(python3 .github/scripts/generate-quick-downloads.py \ "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME" "${FILES[@]}" || true) - if [ -n "$QUICK_DOWNLOADS" ]; then - GENERATED_NOTES=$(gh release view "$GITHUB_REF_NAME" --json body --jq .body) - printf '%s\n\n---\n\n%s\n' "$QUICK_DOWNLOADS" "$GENERATED_NOTES" > "$RUNNER_TEMP/release-notes.md" - gh release edit "$GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/release-notes.md" + CHANGES=$(python3 .github/scripts/generate-change-list.py \ + "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME" || true) + if [ -z "$CHANGES" ]; then + echo "::warning::No change list was generated; keeping GitHub's generated notes." + CHANGES=$(gh release view "$GITHUB_REF_NAME" --json body --jq .body || true) + fi + if [ -z "$CHANGES" ]; then + echo "::warning::The release notes could not be read; the release body was left unchanged." else - echo "::warning::Quick Downloads picker was empty; generated notes were left unchanged." + NOTES=$CHANGES + if [ -n "$QUICK_DOWNLOADS" ]; then + NOTES=$(printf '%s\n\n---\n\n%s' "$QUICK_DOWNLOADS" "$CHANGES") + else + echo "::warning::Quick Downloads picker was empty." + fi + printf '%s\n' "$NOTES" > "$RUNNER_TEMP/release-notes.md" + gh release edit "$GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/release-notes.md" \ + || echo "::warning::The release notes could not be updated." fi fi diff --git a/CMake/Sources.cmake b/CMake/Sources.cmake index bd30d0e9..1965bb4d 100644 --- a/CMake/Sources.cmake +++ b/CMake/Sources.cmake @@ -273,6 +273,7 @@ set (wsjt_FSRCS lib/streaming_apply.f90 lib/jt4.f90 lib/jt4_decode.f90 + lib/jt4_host_support.f90 lib/jt65_decode.f90 lib/jt65_host_support.f90 lib/jt65_mod.f90 @@ -356,7 +357,6 @@ set (wsjt_FSRCS lib/ft8/compress.f90 lib/coord.f90 lib/db.f90 - lib/decode4.f90 lib/decode65a.f90 lib/decode65b.f90 lib/decode9w.f90 @@ -369,7 +369,6 @@ set (wsjt_FSRCS lib/decoder_engine.f90 lib/decoder.f90 lib/env_module.f90 - lib/deep4.f90 lib/deg2grid.f90 lib/degrade_snr.f90 lib/demod64a.f90 @@ -461,7 +460,6 @@ set (wsjt_FSRCS lib/libration.f90 lib/lorentzian.f90 lib/fst4/lorentzian_fading.f90 - lib/lpf1.f90 lib/map65_mmdec.f90 lib/mixlpf.f90 lib/makepings.f90 @@ -497,7 +495,6 @@ set (wsjt_FSRCS lib/pltanh.f90 lib/polyfit.f90 lib/prog_args.f90 - lib/ps4.f90 lib/qra/q65/q65_ap.f90 lib/qra/q65/q65_loops.f90 lib/qra/q65/q65_set_list.f90 @@ -529,7 +526,6 @@ set (wsjt_FSRCS lib/symspec.f90 lib/symspec2.f90 lib/symspec65.f90 - lib/sync4.f90 lib/sync65.f90 lib/ft4/getcandidates4.f90 lib/ft4/get_ft4_bitmetrics.f90 diff --git a/CMakeLists.txt b/CMakeLists.txt index 80ce9d86..9b64cbb2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -885,19 +885,6 @@ if (WSJT_ENABLE_TESTS) samples/JT4/JT4F/OK1KIR_141105_175700.WAV test/fixtures/jt4_OK1KIR_141105_175700.expected.txt --jt4 -b F -f 1200 -d 3) - if (TARGET jt4sim) - set (jt4_read_extent_work_dir - "${CMAKE_BINARY_DIR}/Testing/JT4/test_jt4_12000_read_extent") - add_test (NAME test_jt4_12000_read_extent - COMMAND ${CMAKE_COMMAND} - -DJT9=$ - -DJT4SIM=$ - -DWORK_DIR=${jt4_read_extent_work_dir} - -P ${CMAKE_SOURCE_DIR}/tests/integration/jt9/verify_jt4_12000_read_extent.cmake) - set_tests_properties (test_jt4_12000_read_extent PROPERTIES - LABELS "decoder;jt4;integration" - TIMEOUT 120) - endif () # WSPR decodes via the standalone wsprd binary, not jt9. -a isolates its # writable side files (wspr_wisdom.dat, ALL_WSPR.TXT, wspr_spots.txt, @@ -1280,6 +1267,20 @@ if (WSJT_ENABLE_TESTS AND WSJT_ENABLE_GUI_SMOKE_TESTS LABELS "gui;decoder;jt9;integration" PROCESSORS 1 TIMEOUT 90) + add_test ( + NAME test_wsjtx_jt4_wav + COMMAND ${CMAKE_COMMAND} + "-DWSJTX=$" + "-DMODE=JT4" + "-DSAMPLE=${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/jt4-engine.wav" + "-DEXPECTED_MESSAGE=K1ABC W9XYZ FN42" + "-DWORK_DIR=${CMAKE_BINARY_DIR}/Testing/Jt4Wav" + -P ${CMAKE_SOURCE_DIR}/tests/integration/decoder_engine/run_wav_gui.cmake) + set_tests_properties (test_wsjtx_jt4_wav PROPERTIES + FIXTURES_REQUIRED jt4_engine_wav + LABELS "gui;decoder;jt4;integration" + PROCESSORS 1 + TIMEOUT 90) add_test ( NAME test_wsjtx_jt65_wav COMMAND ${CMAKE_COMMAND} @@ -1331,7 +1332,7 @@ if (WSJT_ENABLE_TESTS AND WSJT_ENABLE_GUI_SMOKE_TESTS TIMEOUT 390) endforeach () if (WSJT_ENABLE_TSAN) - set_tests_properties (test_wsjtx_jt9_wav test_wsjtx_jt65_wav test_wsjtx_q65_wav + set_tests_properties (test_wsjtx_jt4_wav test_wsjtx_jt9_wav test_wsjtx_jt65_wav test_wsjtx_q65_wav test_wsjtx_fst4_wav test_wsjtx_fst4w_wav PROPERTIES ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_gui_options}") endif () diff --git a/DecoderEngine.h b/DecoderEngine.h index 08c3b7c0..25cfcce3 100644 --- a/DecoderEngine.h +++ b/DecoderEngine.h @@ -6,11 +6,11 @@ extern "C" { #endif typedef void *decoder_engine_handle; -enum { DECODER_ENGINE_ABI = 7, DECODER_MODE_FT4 = 5, DECODER_MODE_FT8 = 8, +enum { DECODER_ENGINE_ABI = 8, DECODER_MODE_JT4 = 4, DECODER_MODE_FT4 = 5, DECODER_MODE_FT8 = 8, DECODER_MODE_JT9 = 9, DECODER_MODE_JT65 = 65, DECODER_MODE_Q65 = 66, DECODER_MODE_FST4 = 240, DECODER_MODE_FST4W = 241 }; enum { DECODER_SUPPORT_FT8 = 1, DECODER_SUPPORT_FT4 = 2, DECODER_SUPPORT_JT9 = 4, - DECODER_SUPPORT_JT65 = 8, DECODER_SUPPORT_Q65 = 16, DECODER_SUPPORT_FST4 = 32, DECODER_SUPPORT_FST4W = 64 }; + DECODER_SUPPORT_JT65 = 8, DECODER_SUPPORT_Q65 = 16, DECODER_SUPPORT_FST4 = 32, DECODER_SUPPORT_FST4W = 64, DECODER_SUPPORT_JT4 = 128 }; enum { DECODER_JT65_SYNC = 0, DECODER_JT65_MESSAGE = 1 }; enum { DECODER_JT65_METHOD_NONE = 0, DECODER_JT65_METHOD_FEC = 1, DECODER_JT65_METHOD_DEEP_SEARCH = 2 }; @@ -102,6 +102,25 @@ typedef struct { char hiscall[12]; } decoder_ft4_options; +/* JT4A-G use one-minute periods. UTC is HHMMSS; submode 0..6 selects A..G. + One signal is searched within receive_frequency_hz +/- tolerance_hz. + minimum_width_profile is 0..submode; depth is effort 1..3. */ +typedef struct { + int32_t utc, submode, receive_frequency_hz, tolerance_hz, depth, min_sync; + int32_t minimum_width_profile, averaging, deep_search; + char mycall[12], hiscall[12], hisgrid[6]; +} decoder_jt4_options; + +enum { DECODER_JT4_NO_SYNC = 0, DECODER_JT4_SYNC = 1, DECODER_JT4_MESSAGE = 2 }; +enum { DECODER_JT4_METHOD_NONE = 0, DECODER_JT4_METHOD_FANO = 1, + DECODER_JT4_METHOD_DEEP_SEARCH = 2 }; +enum { DECODER_JT4_AVERAGE_CAPACITY = 64, DECODER_JT4_CALL_CAPACITY = 6999 }; +typedef struct { char call[12], grid[4]; } decoder_jt4_call; +typedef struct { + int32_t utc, frequency_hz, polarity, used; + float sync, dt_seconds; +} decoder_jt4_average_entry; + /* Slow JT9A-H use one-minute periods; submode 0..7 selects A..H. Decoding spectra are prepared internally, independently of display settings. */ typedef struct { @@ -189,11 +208,14 @@ typedef struct { decoder_jt65_options jt65; decoder_q65_options q65; decoder_fst4_options fst4; + decoder_jt4_options jt4; } decoder_attempt_request; /* Borrowed read-only mono signed PCM. Only sample_count samples are read. All modes accept 12000 Hz. FT8 accepts 1..180000 samples; FT4 accepts 1..72576 samples (its analysis window within a 7.5-second period). + JT4 accepts 11025 or 12000 Hz and 1..sample_rate_hz * 60 samples, + analyzing the first 52 seconds. Its PCM, rate and extent stay fixed until release. Slow JT9 and JT65 accept 1..720000 samples (a one-minute period). JT65 analyzes up to 52 seconds and retains its silence-block rejection; short or gapped input may complete without observations. @@ -250,6 +272,13 @@ typedef struct { float drift_hz_per_minute; } decoder_jt9_result; +/* No-sync and synchronization-only observations have no message. width_profile + is a zero-based profile index, meaningful for decoded messages only. + average_count is zero for individual messages. */ +typedef struct { + int32_t kind, method, average_count, sync_polarity, width_profile; +} decoder_jt4_result; + /* Synchronization-only observations have no message. Width is available only for VHF processing. Drift describes the estimated frequency change across the AFC input span, not a waveform reconstruction parameter. */ @@ -278,6 +307,7 @@ typedef struct { /* dt_seconds retains the mode's operator-facing DT convention. Use the evidence's waveform_start_seconds for reconstruction when available. mode and variant select the result record; inactive records are zero. + JT4 variant is its submode (0..6 for A..G); JT4 has no waveform evidence. JT9 variant is its submode (0..7 for A..H); JT9 has no 77-bit evidence. JT65 variant is its submode (0..2 for A..C); JT65 has no waveform evidence. Q65 variant is its submode (0..5 for A..F); Q65 has no waveform evidence. @@ -296,10 +326,11 @@ typedef struct { decoder_jt65_result jt65; decoder_q65_result q65; decoder_fst4_result fst4; + decoder_jt4_result jt4; } decoder_observation; typedef struct { - /* Includes synchronization-only JT65 observations. */ + /* Includes JT4 no-sync/synchronization-only and JT65 synchronization observations. */ int32_t status, observation_count, retained_count, evidence_dropped; } decoder_attempt_outcome; @@ -314,12 +345,19 @@ int32_t decoder_engine_decode(decoder_engine_handle, const decoder_attempt_reque const decoder_audio_view *, decoder_observation_callback, void *, decoder_attempt_outcome *); /* Released input IDs may be reused for a new reception. - Release retains JT65/Q65 averages and caller knowledge, including FST4W + Release retains JT4/JT65/Q65 averages and caller knowledge, including FST4W call/grid history. Reset clears reception history while retaining reusable capacity and plans. Incompatible mode configuration clears averages. Hosts clear JT65 averages when changing band or operating context. */ int32_t decoder_engine_release_input(decoder_engine_handle, int64_t input_id); int32_t decoder_engine_reset_session(decoder_engine_handle); +/* Replaces the copied JT4 deep-search call/grid list; count zero clears it. */ +int32_t decoder_engine_set_jt4_calls(decoder_engine_handle, const decoder_jt4_call *, int32_t count); +/* Uses the capacity/query convention of decoder_engine_get_jt65_averages. */ +int32_t decoder_engine_get_jt4_averages(decoder_engine_handle, decoder_jt4_average_entry *, + int32_t capacity, int32_t *count); +/* Clear allows the retained reception to contribute again on its next attempt. */ +int32_t decoder_engine_clear_jt4_averages(decoder_engine_handle); /* Replaces the copied deep-search list; count zero clears it. */ int32_t decoder_engine_set_jt65_calls(decoder_engine_handle, const decoder_jt65_call *, int32_t count); /* Returns the total count, copying up to capacity entries. Insufficient nonzero diff --git a/WavDecodeTestController.cpp b/WavDecodeTestController.cpp index 8e25787c..62d33da2 100644 --- a/WavDecodeTestController.cpp +++ b/WavDecodeTestController.cpp @@ -23,7 +23,8 @@ WavDecodeTestController::WavDecodeTestController ( , m_window {window} , m_mode {mode} , m_period {mode == Mode::Fst4 ? 15 : mode == Mode::Fst4w ? 120 : 60} - , m_modeName {mode == Mode::Jt9 ? QStringLiteral ("JT9") + , m_modeName {mode == Mode::Jt4 ? QStringLiteral ("JT4") + : mode == Mode::Jt9 ? QStringLiteral ("JT9") : mode == Mode::Jt65 ? QStringLiteral ("JT65") : mode == Mode::Q65 ? QStringLiteral ("Q65") : mode == Mode::Fst4 ? QStringLiteral ("FST4") : QStringLiteral ("FST4W")} @@ -35,6 +36,8 @@ WavDecodeTestController::WavDecodeTestController ( connect (&m_timeout, &QTimer::timeout, this, [this] { finish (tr ("Timed out waiting for %1 WAV decoding.").arg (m_modeName)); }); + // Windows dispatches coarse timers separately from the mode restore's precise timers. + m_prepareTimer.setTimerType (Qt::PreciseTimer); m_prepareTimer.setSingleShot (true); connect (&m_prepareTimer, &QTimer::timeout, this, &WavDecodeTestController::prepareWhenReady); @@ -72,9 +75,11 @@ WavDecodeTestController::WavDecodeTestController ( finish (tr ("A short silent %1 WAV displayed a stale decode: %2").arg (m_modeName, message)); return; } - if (m_activeGeneration && message.simplified () == m_expectedMessage) + auto const expectedDisplayedMessage = m_mode == Mode::Jt4 + ? m_expectedMessage + QStringLiteral (" f") : m_expectedMessage; + if (m_activeGeneration && message.simplified () == expectedDisplayedMessage) { - if (m_mode != Mode::Jt9 && m_mode != Mode::Jt65) + if (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65) { auto * display = m_window->findChild ("decodedTextBrowser"); bool found = false; @@ -125,6 +130,7 @@ void WavDecodeTestController::prepareWhenReady () auto * fast = m_window->findChild ("cbFast9"); auto * cqOnly = m_window->findChild ("cbCQonly"); auto * frequency = m_window->findChild ("RxFreqSpinBox"); + auto const fixtureFrequency = m_mode == Mode::Jt4 ? 1000 : 1500; auto * decode = m_window->findChild ("DecodeButton"); auto * rigStatus = m_window->findChild ("readFreq"); auto * period = m_window->findChild (m_mode == Mode::Fst4w ? "sbTR_FST4W" : "sbTR"); @@ -147,10 +153,9 @@ void WavDecodeTestController::prepareWhenReady () mode->trigger (); quick->trigger (); submode->setValue (0); - if (m_mode != Mode::Jt9 && m_mode != Mode::Jt65) period->setValue (m_period); + if (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65) period->setValue (m_period); if (fast->isChecked ()) fast->click (); cqOnly->setChecked (false); - frequency->setValue (1500); if (m_mode == Mode::Fst4 || m_mode == Mode::Fst4w) { auto * blanker = m_window->findChild ("sbNB"); @@ -169,7 +174,7 @@ void WavDecodeTestController::prepareWhenReady () { auto * receive = m_window->findChild ("sbFST4W_RxFreq"); if (!receive) { finish (tr ("The FST4W frequency control was not found.")); return; } - receive->setValue (1500); + receive->setValue (fixtureFrequency); } m_configured = true; m_prepareTimer.start (100); @@ -177,12 +182,13 @@ void WavDecodeTestController::prepareWhenReady () } if (!mode->isChecked () || !quick->isChecked () || submode->value () != 0 || fast->isChecked () - || (m_mode != Mode::Jt9 && m_mode != Mode::Jt65 && period->value () != m_period) + || (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65 && period->value () != m_period) || !m_window->configureLiveAudioTestDecodeRange ()) { finish (tr ("Unable to configure ordinary %1A decoding.").arg (m_modeName)); return; } + frequency->setValue (fixtureFrequency); m_started = true; loadShortWav (); } @@ -310,7 +316,7 @@ void WavDecodeTestController::completeCycle (quint64 generation) } if (m_stage == Stage::Repeat) { - m_stage = m_mode == Mode::Jt9 || m_mode == Mode::Jt65 + m_stage = m_mode == Mode::Jt4 || m_mode == Mode::Jt9 || m_mode == Mode::Jt65 ? Stage::ShortReplacement : Stage::ShortBeforeMonitoring; loadShortWav (); return; @@ -328,7 +334,7 @@ void WavDecodeTestController::completeCycle (quint64 generation) finish (); return; } - if (m_mode != Mode::Jt9 && m_mode != Mode::Jt65) + if (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65) { auto * period = m_window->findChild (m_mode == Mode::Fst4w ? "sbTR_FST4W" : "sbTR"); period->setValue (m_mode == Mode::Fst4w ? 300 : m_period == 15 ? 30 : 15); diff --git a/WavDecodeTestController.hpp b/WavDecodeTestController.hpp index 39336a59..a23acc15 100644 --- a/WavDecodeTestController.hpp +++ b/WavDecodeTestController.hpp @@ -11,7 +11,7 @@ class MainWindow; class WavDecodeTestController final : public QObject { public: - enum class Mode {Jt9, Jt65, Q65, Fst4, Fst4w}; + enum class Mode {Jt4, Jt9, Jt65, Q65, Fst4, Fst4w}; WavDecodeTestController (MainWindow * window, QString wavPath, QString expectedMessage, Mode mode, QObject * parent = nullptr); diff --git a/ci-cd/DEPLOYMENT_PLAYBOOK.md b/ci-cd/DEPLOYMENT_PLAYBOOK.md index 1e41d2dd..e305ed84 100644 --- a/ci-cd/DEPLOYMENT_PLAYBOOK.md +++ b/ci-cd/DEPLOYMENT_PLAYBOOK.md @@ -252,6 +252,8 @@ Each published public `v*` tag yields, on the public GitHub Release, one install The project-created source tarball is assembled from the public tag. GitHub also generates its own zip and tar.gz source archives for that tag; they contain the tagged tree but may have different compressed hashes. `SHA256SUMS` covers immutable payload assets uploaded by the workflow. For an RC or GA in manual macOS signing mode it excludes each macOS package, which the release manifest identifies as replaceable; a beta's macOS packages are not replaceable, so `SHA256SUMS` covers them. The manifest also records the tag, source commit, workflow run, builder provenance, and both signing modes. Checksums detect changed bytes; platform signatures establish signer identity and must be verified separately. +The release body is a Quick Downloads list of the installers and the source tarball, then the change list that `generate-change-list.py` builds from the promoted commit subjects. It lists features, fixes, and performance changes by their Conventional Commits type, each with its author, except those whose scopes are all among `release`, `ci`, `test`, and `tests`; it counts the other commits and links the full comparison. A beta or RC lists the changes since the newest earlier public tag on its `X.Y` line, or, for a line's first release, since the newest earlier public tag of any line. A GA lists the changes since the newest earlier GA. Commits that an earlier public release already contains are left out, and so are commits whose patch matches one in an earlier release of the same line or the line before it; for a GA, only earlier GAs count. A trailing pull request number in a subject is dropped, and any other `#` or `@` reference is shown as code: the numbers belong to the private repository, and an `@` name would notify that account. If the script fails, or prints nothing because no earlier public tag exists, the publish step warns and keeps GitHub's generated notes, which hold only a comparison link because release commits merge in the private repository. Only the run that creates a release writes its body. + ### All-Platforms-Ready Gate Before publishing, the release workflow requires each platform build to produce its expected installer and release tarball artifacts. This prevents a structurally successful build job from creating a partial release. @@ -915,7 +917,7 @@ Rerun jobs against the immutable tag for transient signing, notarization, or ser ## 10. Scheduled Beta Releases -Betas are unattended weekly prereleases of `develop`, published from the single `release/X.Y` in `BETA` state. The beta scheduler is two workflows. `beta-cut.yml` (Scheduled Beta Cut) applies the [state machine](#state-machine); each of its runs is a cut. `beta-continue.yml` (Scheduled Beta Continue) is the continuation, which chains the runs that follow. A beta's GitHub Release body holds GitHub's generated release notes, preceded by a Quick Downloads list. The channel model is in [Release channels](#release-channels). +Betas are unattended weekly prereleases of `develop`, published from the single `release/X.Y` in `BETA` state. The beta scheduler is two workflows. `beta-cut.yml` (Scheduled Beta Cut) applies the [state machine](#state-machine); each of its runs is a cut. `beta-continue.yml` (Scheduled Beta Continue) is the continuation, which chains the runs that follow. A beta's GitHub Release body is the one [What the Release Produces](#what-the-release-produces) describes. The channel model is in [Release channels](#release-channels). > **Unattended publication.** No person reviews a beta before it is public. Each beta carries the newest green `develop`, including its workflow changes, which the release-bot App merges onto the release line. @@ -999,7 +1001,7 @@ A patch release on an existing line never uses `BETA` state. It uses `RC N` meta ### Starting a release line -Cut `release/X.Y` from a green `develop`. Then land the line-start commit, a reviewed commit that changes only `release-state.txt` and `release-linux-images.json`. The state is `BETA 1` for the line's version (`channel=BETA`, `prerelease=1`, `windows_signing=unsigned`), and the selection is the one prepared as [Prepared Linux release images](#prepared-linux-release-images) describes. For that preparation, choose a `validated-build-YYYYMMDD-RUN-ATTEMPT` generation that all four `ghcr.io/wsjtx/wsjtx-internal/` images carry, from a Refresh Build Caches or Publish Linux CI Images run on `develop` built for the line's recipes. List a package's tags with a token that has the `read:packages` scope: +Cut `release/X.Y` from a green `develop`. Then land the line-start commit, which changes only `release-state.txt` and `release-linux-images.json`. The state is `BETA 1` for the line's version (`channel=BETA`, `prerelease=1`, `windows_signing=unsigned`), and the selection is the one prepared as [Prepared Linux release images](#prepared-linux-release-images) describes. For that preparation, choose a `validated-build-YYYYMMDD-RUN-ATTEMPT` generation that all four `ghcr.io/wsjtx/wsjtx-internal/` images carry, from a Refresh Build Caches or Publish Linux CI Images run on `develop` built for the line's recipes. List a package's tags with a token that has the `read:packages` scope: ```bash # Tags of one internal image package, here linux-noble: @@ -1225,6 +1227,7 @@ gh secret set CROSS_REPO_TOKEN --repo WSJTX/wsjtx-internal --env source-promotio | `.github/scripts/beta-scheduler.py` | Beta scheduler state machine, dispatches, and failure alerts | None | | `.github/scripts/release-linux-images.py` | Linux image selection preparation, validation, and provenance | None | | `.github/scripts/generate-quick-downloads.py` | Quick Downloads list in the GitHub Release body | None | +| `.github/scripts/generate-change-list.py` | Change list in the GitHub Release body | None | ### Secrets Required on `wsjtx-internal` diff --git a/ci-cd/DEVELOPMENT_WORKFLOW.md b/ci-cd/DEVELOPMENT_WORKFLOW.md index 555fb93f..73f07361 100644 --- a/ci-cd/DEVELOPMENT_WORKFLOW.md +++ b/ci-cd/DEVELOPMENT_WORKFLOW.md @@ -244,6 +244,8 @@ git add -A git commit -m "fix: resolve audio dropout on macOS Sequoia" ``` +Commit subjects typed `feat`, `fix`, or `perf` become lines in the public release notes with the author's name, unless their scopes are all among `release`, `ci`, `test`, and `tests`; other subjects are only counted ([What the Release Produces](DEPLOYMENT_PLAYBOOK.md#what-the-release-produces)). + #### 4. Push and open a PR ```bash diff --git a/lib/decode4.f90 b/lib/decode4.f90 deleted file mode 100644 index e0596ed1..00000000 --- a/lib/decode4.f90 +++ /dev/null @@ -1,112 +0,0 @@ -subroutine decode4(dat,npts,dtx,nfreq,flip,mode4,ndepth,neme,minw, & - mycall,hiscall,hisgrid,decoded,nfano,deepbest,qbest,ichbest) - -! Decodes JT4 data, assuming that DT and DF have already been determined. -! Input dat(npts) has already been downsampled by 2: rate = 11025/2. -! ### NB: this initial downsampling should be removed in WSJT-X, since -! it restricts the useful bandwidth to < 2.7 kHz. - - use jt4 - real dat(npts) !Raw data - character decoded*22,deepmsg*22,deepbest*22 - character*12 mycall,hiscall - character*6 hisgrid - real*8 dt,df,phi,f0,dphi,twopi,phi1,dphi1 - complex*16 cz,cz1,c0,c1 - real*4 sym(207) - - twopi=8*atan(1.d0) - dt=2.d0/11025 !Sample interval (2x downsampled data) - df=11025.d0/2520.d0 !Tone separation for JT4A mode - nsym=206 - amp=15.0 - istart=nint((dtx+0.8)/dt) !Start index for synced FFTs - if(istart.lt.0) istart=0 - nchips=0 - qbest=0. - qtop=0. - deepmsg=' ' - ichbest=-1 - c0=0. - k=istart - phi=0.d0 - phi1=0.d0 - - ich1=minw+1 - do ich=1,7 - if(nch(ich).le.mode4) ich2=ich - enddo - - do ich=ich1,ich2 - nchips=min(nch(ich),70) - nspchip=1260/nchips - k=istart - phi=0.d0 - phi1=0.d0 - fac2=1.e-8 * sqrt(float(mode4)) - do j=1,nsym+1 - if(flip.gt.0.0) then - f0=nfreq + (npr(j))*mode4*df - f1=nfreq + (2+npr(j))*mode4*df - else - f0=nfreq + (1-npr(j))*mode4*df - f1=nfreq + (3-npr(j))*mode4*df - endif - dphi=twopi*dt*f0 - dphi1=twopi*dt*f1 - sq0=0. - sq1=0. - do nc=1,nchips - phi=0.d0 - phi1=0.d0 - c0=0. - c1=0. - do i=1,nspchip - k=k+1 - phi=phi+dphi - phi1=phi1+dphi1 - cz=dcmplx(cos(phi),-sin(phi)) - cz1=dcmplx(cos(phi1),-sin(phi1)) - if(k.le.npts) then - c0=c0 + dat(k)*cz - c1=c1 + dat(k)*cz1 - endif - enddo - sq0=sq0 + real(c0)**2 + aimag(c0)**2 - sq1=sq1 + real(c1)**2 + aimag(c1)**2 - enddo - sq0=fac2*sq0 - sq1=fac2*sq1 - rsym=amp*(sq1-sq0) - if(j.ge.1) then - rsymbol(j,ich)=rsym - sym(j)=rsym - endif - enddo - - call extract4(sym,ncount,decoded) !Do the convolutional decode - nfano=0 - if(ncount.ge.0) then - nfano=1 - ichbest=ich - exit - endif - - qual=0. !Now try deep search -! if(ndepth.ge.1) then - if(iand(ndepth,32).eq.32) then - call deep4(sym(2),neme,flip,mycall,hiscall,hisgrid,deepmsg,qual) - if(qual.gt.qbest) then - qbest=qual - deepbest=deepmsg - ichbest=ich - endif - endif - enddo - if(qbest.gt.qtop) then - qtop=qbest - endif - qual=qbest - - return -end subroutine decode4 diff --git a/lib/decoder.f90 b/lib/decoder.f90 index 4bcbe87f..6f6b9075 100644 --- a/lib/decoder.f90 +++ b/lib/decoder.f90 @@ -3,14 +3,12 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen !$ use omp_lib use prog_args use timer_module, only: timer - use jt4_decode use jt65_decode use jt65_host_support, only: load_jt65_calls use jt9_decode use decoder_callbacks, only: decoder_callback_context, & - counting_jt4_decoder, counting_jt65_decoder, counting_jt9_decoder, & - jt4_decoded, & - jt4_average, jt65_decoded, jt9_decoded + counting_jt65_decoder, counting_jt9_decoder, & + jt65_decoded, jt9_decoded use streaming_emit, only: streaming_emit_enabled, & streaming_emit_decode use decode_completion_module, only: decode_completion_result, & @@ -48,15 +46,16 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen character(len=4), allocatable :: jt65_grids(:) data ntr0/-1/ save - type(counting_jt4_decoder) :: my_jt4 type(counting_jt65_decoder) :: my_jt65 type(counting_jt9_decoder) :: my_jt9 - if(params%nmode.eq.8.or.params%nmode.eq.5.or.params%nmode.eq.9.or.params%nmode.eq.65.or. & + if(params%nmode.eq.4.or.params%nmode.eq.8.or.params%nmode.eq.5.or.params%nmode.eq.9.or. & + params%nmode.eq.65.or. & params%nmode.eq.66.or.params%nmode.eq.240.or.params%nmode.eq.241.or.params%nmode.eq.242) then call run_decoder_engine(id2,params,nfsample,completion,progress_generation, & 0_c_int64_t,0_c_int64_t,0_c_int, & - merge(params%kin,0_c_int,params%nmode==5.or.params%nmode==9.or.params%nmode==65.or.params%nmode==66.or. & + merge(params%kin,0_c_int,params%nmode==4.or.params%nmode==5.or.params%nmode==9.or. & + params%nmode==65.or.params%nmode==66.or. & params%nmode==240.or.params%nmode==241.or.params%nmode==242)) return endif @@ -64,7 +63,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen call reset_decode_completion(completion) active_progress_generation=progress_generation - my_jt4%decoded = 0 my_jt65%decoded = 0 my_jt9%decoded = 0 nsynced=0 @@ -125,7 +123,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen callback_context%bVHF = bVHF callback_context%b_superfox = params%b_superfox callback_context%mycall = mycall - my_jt4%context = callback_context my_jt65%context = callback_context my_jt9%context = callback_context @@ -151,25 +148,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen ! id2(1:nz)=0 ! temporarily disabled as it can breaak the JT9 decoder, maybe others endif - if(params%nmode.eq.4) open(14,file=trim(temp_dir)// & - '/avemsg.txt',status='unknown') - - if(params%nmode.eq.4) then - jz=52*nfsample - if(params%newdat) then - if(nfsample.eq.12000) call wav11(id2,jz,dd) - if(nfsample.eq.11025) dd(1:jz)=id2(1:jz) - else - jz=52*11025 - endif - call my_jt4%decode(jt4_decoded,dd,jz,params%nutc,params%nfqso, & - params%ntol,params%emedelay,params%dttol,logical(params%nagain), & - params%ndepth,logical(params%nclearave),params%minsync, & - params%minw,params%nsubmode,mycall,hiscall, & - hisgrid,params%nlist,params%listutc,jt4_average) - go to 800 - endif - npts65=52*12000 if(baddata(id2,npts65)) then nsynced=0 @@ -239,11 +217,10 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen ! JT65 is not yet producing info for nsynced, ndecoded. -800 ndecoded = my_jt4%decoded + my_jt65%decoded + my_jt9%decoded +800 ndecoded = my_jt65%decoded + my_jt9%decoded call set_decode_completion(completion,nsynced,ndecoded,navg0) call write_decode_progress(active_progress_generation) close(13) - if(params%nmode.eq.4) close(14) return end subroutine multimode_decoder_core @@ -265,7 +242,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample) if (.not. completion%available) return if (streaming_emit_enabled()) then - call streaming_emit_decode_finished(params%nutc,params%nmode==66.or.params%nmode==240.or. & + call streaming_emit_decode_finished(params%nutc,params%nmode==4.or.params%nmode==66.or. & + params%nmode==240.or. & params%nmode==241.or.params%nmode==242) else if (.not. lquiet) then call write_decode_completion(completion) diff --git a/lib/decoder_callbacks.f90 b/lib/decoder_callbacks.f90 index 186290c7..3c5821de 100644 --- a/lib/decoder_callbacks.f90 +++ b/lib/decoder_callbacks.f90 @@ -99,69 +99,79 @@ contains logical, intent(in) :: is_average integer, intent(in) :: ave - character*22 decoded - character*3 cflags - integer context_nutc + character(len=22) :: decoded + character(len=3) :: cflags + type(decoder_callback_context) :: context + type(engine_observation) :: observation + integer :: i,display_utc select type (typed_this => this) type is (counting_jt4_decoder) - context_nutc = typed_this%context%nutc + context=typed_this%context class default return end select - if(ich.eq.-99) stop - if (have_sync) then - decoded=decoded0 - cflags=' ' - if(decoded.ne.' ') then - cflags='f ' - if(is_deep) then - cflags='d ' - write(cflags(2:2),'(i1)') min(int(qual),9) - if(qual.ge.10.0) cflags(2:2)='*' - if(qual.lt.3.0) decoded(22:22)='?' + observation=engine_observation() + observation%mode=engine_mode_jt4 + observation%variant=context%submode + observation%snr_db=snr + observation%frequency_hz=real(freq) + observation%dt_seconds=dt + observation%sync=this%sync_strength + observation%quality=qual + if(have_sync) then + observation%jt4%kind=1 + observation%jt4%sync_polarity=merge(-1,1,sync=='#') + if(len_trim(decoded0)>0) then + observation%jt4%kind=2 + observation%jt4%method=merge(2,1,is_deep) + observation%jt4%width_profile=max(0,ich-1) + if(is_average) observation%jt4%average_count=ave + do i=1,len_trim(decoded0) + observation%message(i)=decoded0(i:i) + enddo + endif + endif + if(associated(context%sink)) call context%sink(context%sink_user,observation) + + display_utc=context%nutc + if(context%utc_is_hhmmss) display_utc=display_utc/100 + if(context%render_legacy) then + if(have_sync) then + decoded=decoded0 + cflags=' ' + if(len_trim(decoded)>0) then + cflags='f ' + if(is_deep) then + cflags='d ' + write(cflags(2:2),'(i1)') min(int(qual),9) + if(qual>=10.0) cflags(2:2)='*' + if(qual<3.0) decoded(22:22)='?' + endif + if(is_average) then + write(cflags(3:3),'(i1)') min(ave,9) + if(ave>=10) cflags(3:3)='*' + if(cflags(1:1)=='f') cflags=cflags(1:1)//cflags(3:3)//' ' + endif endif - if(is_average) then - write(cflags(3:3),'(i1)') min(ave,9) - if(ave.ge.10) cflags(3:3)='*' - if(cflags(1:1).eq.'f') cflags=cflags(1:1)//cflags(3:3)//' ' + if(streaming_emit_enabled()) then + call streaming_emit_decode('JT4',context%nutc,snr,dt,freq,decoded,context%utc_is_hhmmss) + else + write(*,1000) display_utc,snr,dt,freq,sync,decoded,cflags endif - endif - if (streaming_emit_enabled()) then - call streaming_emit_decode("JT4", context_nutc, snr, dt, freq, decoded) else - write(*,1000) context_nutc,snr,dt,freq,sync,decoded,cflags - end if - else - if (.not. streaming_emit_enabled()) write(*,1000) context_nutc,snr,dt,freq - end if -1000 format(i4.4,i4,f5.1,i5,1x,'$',a1,1x,a22,1x,a3) + if(.not.streaming_emit_enabled()) write(*,1000) display_utc,snr,dt,freq + endif +1000 format(i4.4,i4,f5.1,i5,1x,'$',a1,1x,a22,1x,a3) + endif select type (typed_this => this) type is (counting_jt4_decoder) - typed_this%decoded = typed_this%decoded + 1 + if(observation%jt4%kind==2) typed_this%decoded=typed_this%decoded+1 end select end subroutine jt4_decoded - subroutine jt4_average (this, used, utc, sync, dt, freq, flip) - implicit none - class(jt4_decoder), intent(inout) :: this - logical, intent(in) :: used - integer, intent(in) :: utc - real, intent(in) :: sync - real, intent(in) :: dt - integer, intent(in) :: freq - logical, intent(in) :: flip - character(len=1) :: cused, csync - - cused = '.' - csync = '*' - if (used) cused = '$' - if (flip) csync = '$' - write(14,1000) cused,utc,sync,dt,freq,csync -1000 format(a1,i5.4,f6.1,f6.2,i6,1x,a1) - end subroutine jt4_average subroutine jt65_decoded(this,sync,snr,dt,freq,drift,nflip,width, & decoded0,ft,qual,nsmo,nsum,minsync) @@ -788,7 +798,8 @@ contains endif if (streaming_emit_enabled()) then - call streaming_emit_decode("FST4", nutc, nsnr, dt, nint(freq), decoded0,context%utc_is_hhmmss) + call streaming_emit_decode(merge('FST4W','FST4 ',context%mode==engine_mode_fst4w), & + nutc, nsnr, dt, nint(freq), decoded0,context%utc_is_hhmmss) else write(*,1005) line end if diff --git a/lib/decoder_engine.f90 b/lib/decoder_engine.f90 index eee39e74..fd49af0d 100644 --- a/lib/decoder_engine.f90 +++ b/lib/decoder_engine.f90 @@ -6,6 +6,7 @@ module decoder_engine use ft8_engine_kernel, only: ft8_kernel_state,params_block,run_ft8_kernel,reset_ft8_kernel,release_ft8_input use decoder_callbacks, only: decoder_callback_context,counting_ft4_decoder,ft4_decoded, & counting_jt9_decoder,jt9_decoded,counting_jt65_decoder,jt65_decoded, & + counting_jt4_decoder,jt4_decoded, & counting_q65_decoder,q65_decoded,counting_fst4_decoder,fst4_decoded use q65_decode, only: q65_options use fst4_decode, only: fst4_options @@ -13,11 +14,15 @@ module decoder_engine use q65_host_support, only: load_q65_history,save_q65_history,write_q65_curves,write_q65_diagnostic use q65_callers, only: Q65_MAX_CALLERS use types, only: q3list + use jt4_decode, only: jt4_options,jt4_call,jt4_average_entry + use jt4_host_support, only: convert_jt4_host_options,load_jt4_calls,write_jt4_averages, & + prepare_jt4_host,write_jt4_diagnostic use jt65_decode, only: jt65_options,jt65_average_entry use jt65_host_support, only: load_jt65_calls,write_jt65_averages use decode_completion_module, only: decode_completion_result,set_decode_completion,write_decode_progress use prog_args, only: temp_dir use timer_module, only: timer + use streaming_emit, only: streaming_emit_enabled implicit none private public :: engine_host_decode @@ -141,6 +146,13 @@ module decoder_engine type, bind(C) :: engine_fst4w_call character(c_char) :: call_grid(20) end type + type, bind(C) :: engine_jt4_call + character(c_char) :: call(12),grid(4) + end type + type, bind(C) :: engine_jt4_average_entry + integer(c_int) :: utc,frequency_hz,polarity,used + real(c_float) :: sync,dt_seconds + end type type, bind(C) :: attempt_request integer(c_int64_t) :: input_id=0,analysis_id=0 integer(c_int) :: attempt_no=0,mode=8,phase=2,source=0 @@ -150,6 +162,7 @@ module decoder_engine type(engine_jt65_options) :: jt65 type(engine_q65_options) :: q65 type(engine_fst4_options) :: fst4 + type(engine_jt4_options) :: jt4 end type type, bind(C) :: audio_view type(c_ptr) :: samples @@ -171,6 +184,7 @@ module decoder_engine type(counting_ft4_decoder) :: ft4 ! GCC 13 can finalize an uninitialized temporary for an embedded finalizable extension. type(counting_jt9_decoder), allocatable :: jt9 + type(counting_jt4_decoder), allocatable :: jt4 type(counting_jt65_decoder), allocatable :: jt65 type(counting_q65_decoder), allocatable :: q65 type(counting_fst4_decoder), allocatable :: fst4 @@ -178,7 +192,7 @@ module decoder_engine type(engine_observation), allocatable :: evidence(:) integer(c_short), allocatable :: audio(:) integer(c_int64_t) :: input_id=0,analysis_id=0 - integer :: input_mode=0,input_sample_count=0 + integer :: input_mode=0,input_sample_count=0,input_sample_rate=0 integer :: last_attempt=0,retained=0,dropped=0,emitted=0 logical :: running=.false.,render_legacy=.false. type(c_funptr) :: callback=c_null_funptr @@ -193,14 +207,17 @@ module decoder_engine contains - pure integer function analysis_extent(mode,period) result(samples) + pure integer function analysis_extent(mode,period,sample_rate) result(samples) integer, intent(in) :: mode - integer, optional, intent(in) :: period + integer, optional, intent(in) :: period,sample_rate select case(mode) case(engine_mode_ft4) samples=72576 case(engine_mode_ft8) samples=180000 + case(engine_mode_jt4) + samples=720000 + if(present(sample_rate)) samples=60*sample_rate case(engine_mode_jt9,engine_mode_jt65) samples=720000 case(engine_mode_q65) @@ -221,6 +238,7 @@ contains subroutine initialize_session(state) type(engine_session), intent(inout) :: state allocate(state%jt9) + allocate(state%jt4) allocate(state%jt65) allocate(state%q65) allocate(state%fst4) @@ -256,7 +274,7 @@ contains caps=engine_capabilities(engine_abi, & ior(ior(engine_support_ft8,engine_support_ft4), & ior(ior(ior(engine_support_jt9,engine_support_jt65),engine_support_q65), & - ior(engine_support_fst4,engine_support_fst4w))), & + ior(ior(engine_support_fst4,engine_support_fst4w),engine_support_jt4))), & 0,0,evidence_capacity) status=invalid if(valid_handle(handle)) status=ok @@ -281,7 +299,8 @@ contains logical, intent(in) :: render integer, intent(in) :: progress integer(c_short), pointer :: samples(:) - integer :: analysis_samples + integer :: analysis_samples,allocation_status + integer(c_short), allocatable :: grown_audio(:) type(params_block) :: params type(decoder_callback_context) :: context outcome=attempt_outcome() @@ -290,21 +309,28 @@ contains status=busy if(session%running) go to 900 status=unsupported - if(request%mode/=engine_mode_ft8.and.request%mode/=engine_mode_ft4.and. & + if(request%mode/=engine_mode_jt4.and.request%mode/=engine_mode_ft8.and.request%mode/=engine_mode_ft4.and. & request%mode/=engine_mode_jt9.and.request%mode/=engine_mode_jt65.and.request%mode/=engine_mode_q65.and. & request%mode/=engine_mode_fst4.and.request%mode/=engine_mode_fst4w) go to 900 - if(audio%sample_rate_hz/=12000) go to 900 + if(request%mode==engine_mode_jt4) then + if(audio%sample_rate_hz/=11025.and.audio%sample_rate_hz/=12000) go to 900 + else + if(audio%sample_rate_hz/=12000) go to 900 + endif status=invalid if(request%input_id<=0.or.request%analysis_id<=0.or.request%attempt_no<=0) go to 900 if(request%phase<1.or.request%phase>3.or.request%source<0.or.request%source>1) go to 900 if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) then analysis_samples=analysis_extent(request%mode,request%fst4%period_seconds) else - analysis_samples=analysis_extent(request%mode,request%q65%period_seconds) + analysis_samples=analysis_extent(request%mode,request%q65%period_seconds,audio%sample_rate_hz) endif if(audio%sample_count<1.or.audio%sample_count>analysis_samples) go to 900 if(.not.c_associated(audio%samples)) go to 900 - if(request%mode==engine_mode_ft4) then + if(request%mode==engine_mode_jt4) then + if(request%phase==1) go to 900 + if(.not.valid_jt4_options(request%jt4)) go to 900 + else if(request%mode==engine_mode_ft4) then if(request%phase==1) go to 900 if(request%ft4%search_low_hz<0.or.request%ft4%search_high_hz>6000.or. & request%ft4%search_low_hz>request%ft4%search_high_hz) go to 900 @@ -338,6 +364,9 @@ contains endif if(session%input_id/=0.and.session%input_id/=request%input_id) go to 900 if(session%input_id/=0.and.session%input_mode/=request%mode) go to 900 + if(request%mode==engine_mode_jt4.and.session%input_id/=0) then + if(audio%sample_count/=session%input_sample_count.or.audio%sample_rate_hz/=session%input_sample_rate) go to 900 + endif if(request%mode==engine_mode_q65.and.session%input_id/=0) then if(audio%sample_count/=session%input_sample_count) go to 900 endif @@ -348,14 +377,19 @@ contains if(session%analysis_id==request%analysis_id.and.request%attempt_no<=session%last_attempt) go to 900 if(size(session%audio)collect_superfox context%sink_user=handle context%render_legacy=render - if(request%mode==engine_mode_ft4) then + if(request%mode==engine_mode_jt4) then + call run_jt4_attempt(request%jt4,request%phase,audio%sample_count,audio%sample_rate_hz,context,progress,status) + else if(request%mode==engine_mode_ft4) then call run_ft4_attempt(request%ft4,request%phase,context,progress) else if(request%mode==engine_mode_jt9) then call run_jt9_attempt(request%jt9,request%phase,audio%sample_count,context,progress) @@ -464,6 +500,151 @@ contains call write_decode_progress(progress) end subroutine + pure logical function valid_hhmmss(utc) result(valid) + integer, intent(in) :: utc + valid=utc>=0.and.utc<=235959.and.mod(utc/100,100)<=59.and.mod(utc,100)<=59 + end function + + logical function valid_jt4_options(options) result(valid) + type(engine_jt4_options), intent(in) :: options + valid=.false. + if(.not.valid_hhmmss(options%utc)) return + if(options%submode<0.or.options%submode>6) return + if(options%minimum_width_profile<0.or.options%minimum_width_profile>options%submode) return + if(options%depth<1.or.options%depth>3) return + if(options%receive_frequency_hz<0.or.options%receive_frequency_hz>5000) return + if(options%tolerance_hz<0.or.options%tolerance_hz>5000) return + if(any([options%averaging,options%deep_search]<0).or.any([options%averaging,options%deep_search]>1)) return + valid=.true. + end function + + subroutine run_jt4_attempt(options,phase,sample_count,sample_rate,callback_context,progress,status) + type(engine_jt4_options), intent(in) :: options + integer, intent(in) :: phase,sample_count,sample_rate,progress + type(decoder_callback_context), intent(in) :: callback_context + integer(c_int), intent(out) :: status + type(decoder_callback_context) :: context + type(jt4_options) :: kernel_options + integer :: kernel_status + + context=callback_context + context%nutc=options%utc + context%utc_is_hhmmss=.true. + context%nfqso=options%receive_frequency_hz + context%submode=options%submode + context%ios13=-1 + context%ios14=-1 + if(context%render_legacy) then + call open_legacy_output(phase,context%ios13) + open(14,file=trim(temp_dir)//'/avemsg.txt',status='unknown',iostat=context%ios14) + call prepare_jt4_host(session%jt4) + endif + session%jt4%context=context + session%jt4%decoded=0 + kernel_options%utc=options%utc + kernel_options%submode=options%submode + kernel_options%receive_frequency_hz=options%receive_frequency_hz + kernel_options%tolerance_hz=options%tolerance_hz + kernel_options%depth=options%depth + kernel_options%min_sync=options%min_sync + kernel_options%minimum_width_profile=options%minimum_width_profile + kernel_options%averaging=options%averaging/=0 + kernel_options%deep_search=options%deep_search/=0 + kernel_options%mycall=transfer(options%mycall,kernel_options%mycall) + kernel_options%hiscall=transfer(options%hiscall,kernel_options%hiscall) + kernel_options%hisgrid=transfer(options%hisgrid,kernel_options%hisgrid) + call timer('decjt4 ',0) + if(context%render_legacy) then + call session%jt4%decode_pcm(kernel_options,session%audio(:sample_count),sample_rate,jt4_decoded, & + kernel_status,write_jt4_diagnostic) + else + call session%jt4%decode_pcm(kernel_options,session%audio(:sample_count),sample_rate,jt4_decoded,kernel_status) + endif + call timer('decjt4 ',1) + if(context%ios14==0) then + call write_jt4_averages(session%jt4,14) + close(14) + endif + if(context%ios13==0) close(13) + call set_decode_completion(session%completion,0,session%jt4%decoded,0) + call write_decode_progress(progress) + status=ok + if(kernel_status/=0) status=internal_error + end subroutine + + integer(c_int) function engine_set_jt4_calls(handle,entries,count) & + bind(C,name='decoder_engine_set_jt4_calls') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: count + type(engine_jt4_call), pointer :: records(:) + type(jt4_call), allocatable :: calls(:) + integer :: i,allocation_status,kernel_status + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(count<0.or.count>6999) return + if(count>0.and..not.c_associated(entries)) return + allocate(calls(count),stat=allocation_status) + status=internal_error + if(allocation_status/=0) return + if(count>0) then + call c_f_pointer(entries,records,[count]) + do i=1,count + calls(i)%call=transfer(records(i)%call,calls(i)%call) + calls(i)%grid=transfer(records(i)%grid,calls(i)%grid) + enddo + endif + call session%jt4%set_calls(calls,kernel_status) + if(kernel_status/=0) return + status=ok + end function + + integer(c_int) function engine_get_jt4_averages(handle,entries,entry_capacity,count) & + bind(C,name='decoder_engine_get_jt4_averages') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: entry_capacity + integer(c_int), intent(out) :: count + type(engine_jt4_average_entry), pointer :: records(:) + type(jt4_average_entry) :: averages(64) + integer :: i,n + count=0 + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(entry_capacity<0) return + if(entry_capacity>0.and..not.c_associated(entries)) return + call session%jt4%get_averages(averages,n) + count=n + if(entry_capacity>0) then + call c_f_pointer(entries,records,[entry_capacity]) + do i=1,min(entry_capacity,n) + records(i)%utc=averages(i)%utc + records(i)%frequency_hz=averages(i)%frequency_hz + records(i)%polarity=averages(i)%polarity + records(i)%used=merge(1,0,averages(i)%used) + records(i)%sync=averages(i)%sync + records(i)%dt_seconds=averages(i)%dt_seconds + enddo + endif + status=ok + if(entry_capacity>0.and.entry_capacity3) return @@ -628,10 +808,7 @@ contains if(options%eme_delay_seconds<0.or.options%eme_delay_seconds>real(options%period_seconds)) return if(any([options%single_decode,options%ap_cq_only,options%measure_doppler]<0)) return if(any([options%single_decode,options%ap_cq_only,options%measure_doppler]>1)) return - hours=options%utc/10000 - minutes=mod(options%utc/100,100) - seconds=mod(options%utc,100) - if(options%utc<0.or.hours>23.or.minutes>59.or.seconds>59) return + if(.not.valid_hhmmss(options%utc)) return valid=.true. end function @@ -742,7 +919,6 @@ contains logical function valid_q65_options(options) result(valid) type(engine_q65_options), intent(in) :: options - integer :: hours,minutes,seconds valid=.false. if(.not.any(options%period_seconds==[15,30,60,120,300])) return if(options%submode<0.or.options%submode>5) return @@ -758,10 +934,7 @@ contains options%pileup,options%ap_cq_only]<0)) return if(any([options%averaging,options%auto_clear,options%single_decode,options%extended_eme_search, & options%pileup,options%ap_cq_only]>1)) return - hours=options%utc/10000 - minutes=mod(options%utc/100,100) - seconds=mod(options%utc,100) - if(options%utc<0.or.hours>23.or.minutes>59.or.seconds>59) return + if(.not.valid_hhmmss(options%utc)) return valid=.true. end function @@ -982,11 +1155,13 @@ contains if(input_id<=0.or.session%input_id/=input_id) return call release_ft8_input(session%kernel) call session%jt9%release_input() + call session%jt4%release_input() call session%jt65%release_input() call session%q65%release_input() session%input_id=0 session%input_mode=0 session%input_sample_count=0 + session%input_sample_rate=0 session%analysis_id=0 session%last_attempt=0 session%retained=0 @@ -1003,6 +1178,7 @@ contains call reset_ft8_kernel(session%kernel) call session%ft4%reset() call session%jt9%reset() + call session%jt4%reset() call session%jt65%reset() call session%q65%reset() call session%fst4%reset() @@ -1010,6 +1186,7 @@ contains session%input_id=0 session%input_mode=0 session%input_sample_count=0 + session%input_sample_rate=0 session%analysis_id=0 session%last_attempt=0 session%retained=0 @@ -1105,11 +1282,18 @@ contains type(attempt_outcome) :: outcome type(engine_options) :: options integer(c_int) :: status - integer :: time,history_status,blanker,period_samples + integer :: time,history_status,blanker,period_samples,gate_samples character(len=12), allocatable :: calls(:) character(len=4), allocatable :: grids(:) options%abi_version=engine_abi completion=decode_completion_result(.true.,0,0,0) + if(params%nmode==engine_mode_jt4) then + if(params%nclearave.and.valid_handle(host_handle)) call session%jt4%clear_averages() + gate_samples=min(180000,max(0,valid_samples)) + if(gate_samples>0) then + if(sqrt(sum(real(id2(1:gate_samples))**2)/180000.0)<0.5) return + endif + endif if(params%nmode==engine_mode_ft4) then ! The legacy host's low-signal gate includes its zero-padded 15-second window. if(sqrt(sum(real(id2(1:180000))**2)/180000.0)<0.5) return @@ -1128,7 +1312,7 @@ contains endif if(input_id<=0.or.analysis_id<=0) then if(session%input_id==0.or.params%nutc/=fallback_utc.or.session%input_mode/=request%mode.or. & - ((params%nmode==engine_mode_ft4.or.params%nmode==engine_mode_jt9.or. & + ((params%nmode==engine_mode_jt4.or.params%nmode==engine_mode_ft4.or.params%nmode==engine_mode_jt9.or. & params%nmode==engine_mode_jt65.or.params%nmode==engine_mode_q65.or. & request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w).and..not.params%nagain).or. & (params%nzhsym==41.and..not.params%nagain)) then @@ -1153,7 +1337,10 @@ contains if(params%nmode==engine_mode_ft8.and.params%nzhsym<50) request%phase=1 if(params%nagain) request%phase=3 request%source=merge(1,0,params%ndiskdat) - if(request%mode==engine_mode_ft4) then + if(request%mode==engine_mode_jt4) then + call convert_jt4_host_options(params,request%jt4,streaming_emit_enabled()) + if(request%jt4%deep_search/=0) call load_jt4_calls(session%jt4) + else if(request%mode==engine_mode_ft4) then request%ft4%utc=params%nutc request%ft4%qso_progress=params%nQSOProgress request%ft4%receive_frequency_hz=params%nfqso @@ -1304,13 +1491,14 @@ contains request%ft8%hisgrid=params%hisgrid endif audio%samples=c_loc(id2(1)) - period_samples=analysis_extent(request%mode,request%q65%period_seconds) + period_samples=analysis_extent(request%mode,request%q65%period_seconds,nfsample) if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) & period_samples=analysis_extent(request%mode,request%fst4%period_seconds) audio%sample_count=min(period_samples,valid_samples) if(valid_samples<=0.and.input_id<=0) then audio%sample_count=period_samples if(request%mode==engine_mode_jt9.or.request%mode==engine_mode_jt65) audio%sample_count=624000 + if(request%mode==engine_mode_jt4) audio%sample_count=52*nfsample endif if(request%mode==engine_mode_ft8) then if(params%lmultift8.and..not.(iand(params%nexp_decode,7)==7.and. & diff --git a/lib/decoder_engine_types.f90 b/lib/decoder_engine_types.f90 index 5c378646..dbf0f2f8 100644 --- a/lib/decoder_engine_types.f90 +++ b/lib/decoder_engine_types.f90 @@ -3,14 +3,14 @@ module decoder_engine_types implicit none private public :: ft8_signal_evidence, ft4_signal_evidence, superfox_evidence, superfox_observation - public :: jt9_result,jt65_result,q65_result,fst4_result + public :: jt9_result,jt65_result,q65_result,fst4_result,jt4_result,engine_jt4_options public :: engine_payload_none,engine_payload_decoded,engine_payload_hypothesis public :: sf_kind_cq,sf_kind_exchange,sf_kind_free_text,sf_kind_verification public :: engine_observation, engine_observation_sink, engine_superfox_sink public :: engine_abi,engine_mode_ft8,engine_mode_ft4,engine_mode_jt9,engine_mode_jt65,engine_mode_q65 public :: engine_support_ft8,engine_support_ft4,engine_support_jt9,engine_support_jt65,engine_support_q65 - integer(c_int), parameter :: engine_abi=7,engine_mode_ft8=8,engine_mode_ft4=5,engine_mode_jt9=9,engine_mode_jt65=65 + integer(c_int), parameter :: engine_abi=8,engine_mode_ft8=8,engine_mode_ft4=5,engine_mode_jt9=9,engine_mode_jt65=65 integer(c_int), parameter :: engine_support_ft8=1,engine_support_ft4=2,engine_support_jt9=4,engine_support_jt65=8 integer(c_int), parameter :: engine_mode_q65=66,engine_support_q65=16 @@ -19,6 +19,19 @@ module decoder_engine_types integer(c_int), parameter :: engine_mode_fst4=240,engine_mode_fst4w=241 integer(c_int), parameter :: engine_support_fst4=32,engine_support_fst4w=64 + public :: engine_mode_jt4,engine_support_jt4 + integer(c_int), parameter :: engine_mode_jt4=4,engine_support_jt4=128 + + type, bind(C) :: engine_jt4_options + integer(c_int) :: utc=0,submode=0,receive_frequency_hz=1500,tolerance_hz=100,depth=1,min_sync=0 + integer(c_int) :: minimum_width_profile=0,averaging=0,deep_search=0 + character(c_char) :: mycall(12)=' ',hiscall(12)=' ',hisgrid(6)=' ' + end type + + type, bind(C) :: jt4_result + integer(c_int) :: kind=0,method=0,average_count=0,sync_polarity=0,width_profile=0 + end type + integer, parameter :: engine_payload_none=0,engine_payload_decoded=1,engine_payload_hypothesis=2 integer, parameter :: sf_kind_cq=1,sf_kind_exchange=2,sf_kind_free_text=3,sf_kind_verification=4 @@ -82,6 +95,7 @@ module decoder_engine_types type(jt65_result) :: jt65 type(q65_result) :: q65 type(fst4_result) :: fst4 + type(jt4_result) :: jt4 end type abstract interface diff --git a/lib/deep4.f90 b/lib/deep4.f90 deleted file mode 100644 index 05f6732d..00000000 --- a/lib/deep4.f90 +++ /dev/null @@ -1,169 +0,0 @@ -subroutine deep4(sym0,neme,flip,mycall,hiscall,hisgrid,decoded,qual) - -! Deep search routine for JT4 - - use prog_args - parameter (MAXCALLS=7000,MAXRPT=63) - real*4 sym0(206),sym(206) - character callsign*12,grid*4,message*22,hisgrid*6,ceme*3 - character*12 mycall,hiscall - character mycall0*12,hiscall0*12,hisgrid0*6 - character*22 decoded - character*22 testmsg(2*MAXCALLS + 2 + MAXRPT) - character*15 callgrid(MAXCALLS) - character*180 line - character*4 rpt(MAXRPT) - integer ncode(206) - real*4 code(206,2*MAXCALLS + 2 + MAXRPT) - real pp(2*MAXCALLS + 2 + MAXRPT) - data neme0/-99/ - data rpt/'-01','-02','-03','-04','-05', & - '-06','-07','-08','-09','-10', & - '-11','-12','-13','-14','-15', & - '-16','-17','-18','-19','-20', & - '-21','-22','-23','-24','-25', & - '-26','-27','-28','-29','-30', & - 'R-01','R-02','R-03','R-04','R-05', & - 'R-06','R-07','R-08','R-09','R-10', & - 'R-11','R-12','R-13','R-14','R-15', & - 'R-16','R-17','R-18','R-19','R-20', & - 'R-21','R-22','R-23','R-24','R-25', & - 'R-26','R-27','R-28','R-29','R-30', & - 'RO','RRR','73'/ - save mycall0,hiscall0,hisgrid0,neme0,ntot,code,testmsg - - sym=sym0 - if(mycall.eq.mycall0 .and. hiscall.eq.hiscall0 .and. & - hisgrid.eq.hisgrid0 .and. neme.eq.neme0) go to 30 - - open(23,file=trim(data_dir)//'/CALL3.TXT',status='unknown') - k=0 - icall=0 - do n=1,MAXCALLS - if(n.eq.1) then - callsign=hiscall - do i=4,12 - if(ichar(callsign(i:i)).eq.0) callsign(i:i)=' ' - enddo - grid=hisgrid(1:4) - if(ichar(grid(3:3)).eq.0) grid(3:3)=' ' - if(ichar(grid(4:4)).eq.0) grid(4:4)=' ' - else - read(23,1002,end=20) line -1002 format (A80) - if(line(1:4).eq.'ZZZZ') go to 20 - if(line(1:2).eq.'//') go to 10 - i1=index(line,',') - if(i1.lt.4) go to 10 - i2=index(line(i1+1:),',') - if(i2.lt.5) go to 10 - i2=i2+i1 - i3=index(line(i2+1:),',') - if(i3.lt.1) i3=index(line(i2+1:),' ') - i3=i2+i3 - callsign=line(1:i1-1) - grid=line(i1+1:i2-1) - ceme=line(i2+1:i3-1) - if(neme.eq.1 .and. ceme.ne.'EME') go to 10 - endif - - icall=icall+1 - j1=index(mycall,' ') - 1 - if(j1.le.-1) j1=12 - if(j1.lt.3) j1=6 - j2=index(callsign,' ') - 1 - if(j2.le.-1) j2=12 - if(j2.lt.3) j2=6 - j3=index(mycall,'/') ! j3>0 means compound mycall - j4=index(callsign,'/') ! j4>0 means compound hiscall - callgrid(icall)=callsign(1:j2) - - mz=1 -! Allow MyCall + HisCall + rpt (?) - if(n.eq.1 .and. j3.lt.1 .and. j4.lt.1 .and. callsign(1:6).ne.' ') & - mz=MAXRPT+1 - do m=1,mz - if(m.gt.1) grid=rpt(m-1) - if(j3.lt.1 .and.j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid - message=mycall(1:j1)//' '//callgrid(icall) - k=k+1 - testmsg(k)=message - call encode4(message,ncode) - code(1:206,k)=2*ncode(1:206)-1 - if(n.ge.2) then -! Insert CQ message - if(j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid - message='CQ '//callgrid(icall) - k=k+1 - testmsg(k)=message - call encode4(message,ncode) - code(1:206,k)=2*ncode(1:206)-1 - endif - enddo -10 continue - enddo - -20 continue - close(23) - ntot=k - -30 mycall0=mycall - hiscall0=hiscall - hisgrid0=hisgrid - neme0=neme - - sq=0. - do j=1,206 - sq=sq + sym(j)**2 - enddo - rms=sqrt(sq/206.0) - sym=sym/rms - - p1=-1.e30 - p2=-1.e30 - do k=1,ntot - pp(k)=0. -! Should re-instate the following: -! if(k.ge.2 .and. k.le.64 .and. flip.gt.0.0) cycle -! Test all messages if flip=+1; skip the CQ messages if flip=-1. - if(flip.gt.0.0 .or. testmsg(k)(1:3).ne.'CQ ') then - p=0. - do j=1,206 - p=p + code(j,k)*sym(j) - enddo - pp(k)=p - if(p.gt.p1) then - p1=p - ip1=k - endif - endif - enddo - - do i=1,ntot - if(pp(i).gt.p2 .and. testmsg(i).ne.testmsg(ip1)) p2=pp(i) - enddo - - qual=p1-max(1.15*p2,70.0) - -! ### DO NOT REMOVE ### - rewind 77 - if(ip1.ge.1 .and. ip1.le.2*MAXCALLS+2+MAXRPT) write(77,1001) p1,p2,ntot, & - rms,qual,ip1,testmsg(ip1) -1001 format(2f8.2,i8,2f8.2,i6,2x,a22) - call flush(77) - - if(qual.gt.1.0) then - decoded=testmsg(ip1) - else - decoded=' ' - qual=0. - endif - -! Make sure everything is upper case. - do i=1,22 - if(decoded(i:i).ge.'a' .and. decoded(i:i).le.'z') & - decoded(i:i)=char(ichar(decoded(i:i))-32) - enddo - - return -end subroutine deep4 diff --git a/lib/extract4.f90 b/lib/extract4.f90 index ce8fb86a..b10d9da9 100644 --- a/lib/extract4.f90 +++ b/lib/extract4.f90 @@ -14,21 +14,23 @@ subroutine extract4(sym0,ncount,decoded) data first/.true./ save first,mettab,ndelta + ncount=-1 + decoded=' ' + ave0=sum(sym0)/207.0 + sym=sym0-ave0 + sq=dot_product(sym,sym) + rms0=sqrt(sq/206.0) + if(rms0<=tiny(rms0)) return + sym=sym/rms0 + if(first) then call getmet4(mettab,ndelta) first=.false. endif -!### Optimize these params: ... amp=30.0 limit=10000 - ave0=sum(sym0)/207.0 - sym=sym0-ave0 - sq=dot_product(sym,sym) - rms0=sqrt(sq/206.0) - sym=sym/rms0 - do j=1,207 n=nint(amp*sym(j)) if(n.lt.-127) n=-127 @@ -38,8 +40,6 @@ subroutine extract4(sym0,ncount,decoded) nbits=72 ncycles=0 - ncount=-1 - decoded=' ' call interleave4(symbol(2),-1) !Remove the interleaving call fano232(symbol(2),nbits+31,mettab,ndelta,limit,data1, & ncycles,metric,ncount) diff --git a/lib/jt4.f90 b/lib/jt4.f90 index 42a2d16b..b88f0242 100644 --- a/lib/jt4.f90 +++ b/lib/jt4.f90 @@ -1,29 +1,13 @@ module jt4 - parameter (MAXAVE=64) - integer iutc(MAXAVE) - integer nfsave(MAXAVE) - integer listutc(10) - real ppsave(207,7,MAXAVE) !Accumulated data for message averaging - real rsymbol(207,7) - real dtsave(MAXAVE) - real syncsave(MAXAVE) - real flipsave(MAXAVE) - real zz(1260,65,7) - - integer nsave,nlist,ich1,ich2 - integer nch(7) - integer npr(207) - data rsymbol/1449*0.0/ - data nch/1,2,4,9,18,36,72/ - data npr/ & + implicit none + integer, parameter :: MAXAVE=64 + integer, parameter :: nch(7)=[1,2,4,9,18,36,72] + integer, parameter :: npr(207)=[ & 0,0,0,0,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0, & 0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,0,0, & 1,0,0,1,0,0,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,1,1,0,0,1, & 0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1,0,1,0,1, & 0,1,1,1,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1,0,0,0,1,1,1, & 0,1,1,1,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,1,1,1,1, & - 1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1/ - - save ppsave,zz - + 1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1 ] end module jt4 diff --git a/lib/jt4_decode.f90 b/lib/jt4_decode.f90 index 8ab48bda..60c2886a 100644 --- a/lib/jt4_decode.f90 +++ b/lib/jt4_decode.f90 @@ -1,13 +1,60 @@ module jt4_decode + use iso_c_binding, only: c_ptr,c_null_ptr,c_associated,c_f_pointer,c_int16_t,c_size_t + use fftw3 + use jt4, only: nch,npr,MAXAVE + + type :: jt4_options + integer :: utc=0,submode=0,receive_frequency_hz=1200,tolerance_hz=100,depth=1 + integer :: min_sync=0,minimum_width_profile=0 + logical :: averaging=.false.,deep_search=.false. + character(len=12) :: mycall='',hiscall='' + character(len=6) :: hisgrid='' + end type + type :: jt4_call + character(len=12) :: call='' + character(len=4) :: grid='' + end type + type :: jt4_average_entry + integer :: utc=0,frequency_hz=0,polarity=1 + logical :: used=.false. + real :: sync=0.,dt_seconds=0. + end type + type, private :: jt4_fft_buffer + type(c_ptr) :: storage=c_null_ptr,forward=c_null_ptr,backward=c_null_ptr + real, pointer :: x(:)=>null() + complex, pointer :: cx(:)=>null() + end type type :: jt4_decoder procedure(jt4_decode_callback), pointer :: decode_callback => null () - procedure(jt4_average_callback), pointer :: average_callback => null () + procedure(jt4_diagnostic_callback), pointer, nopass :: diagnostic_callback => null () + integer :: iutc(MAXAVE)=-1,nfsave(MAXAVE)=0,nsave=0,average_count=0 + real :: dtsave(MAXAVE)=0.,syncsave(MAXAVE)=0.,flipsave(MAXAVE)=0. + logical :: average_used(MAXAVE)=.false. + real, allocatable :: ppsave(:,:,:),rsymbol(:,:) + real, allocatable, private :: dat(:),pcm(:),s2(:,:) + integer, private :: ich1=1,ich2=1,current_submode=-1,current_minimum_profile=-1 + integer, private :: fft_flags=FFTW_ESTIMATE + real :: sync_strength=0. + type(jt4_fft_buffer), private :: transform(4) + type(jt4_call), allocatable :: calls(:) + real, allocatable, private :: code(:,:) + character(len=22), allocatable, private :: testmsg(:) + character(len=12), private :: mycall0='',hiscall0='' + character(len=6), private :: hisgrid0='' + logical, private :: templates_valid=.false.,prepared=.false. + integer, private :: ntot=0,kernel_status=0 contains - procedure :: decode - procedure, private :: wsjt4, avg4 + procedure :: decode_pcm,set_calls,get_averages,clear_averages,release_input,reset,set_fft_flags + procedure :: save_average,select_average + procedure, private :: wsjt4,avg4,decode4,deep4,sync4,lpf1,ps4,getsnr,prepare_workspace,destroy_plans + final :: finalize_jt4 end type jt4_decoder -! Callback function to be called with each decode + abstract interface + subroutine jt4_diagnostic_callback(line) + character(len=*),intent(in) :: line + end subroutine + end interface abstract interface subroutine jt4_decode_callback (this, snr, dt, freq, have_sync, & sync, is_deep, decoded, qual, ich, is_average, ave) @@ -28,136 +75,57 @@ module jt4_decode end subroutine jt4_decode_callback end interface -! Callback function to be called with each average result - abstract interface - subroutine jt4_average_callback (this, used, utc, sync, dt, freq, flip) - import jt4_decoder - implicit none - class(jt4_decoder), intent(inout) :: this - logical, intent(in) :: used - integer, intent(in) :: utc - real, intent(in) :: sync - real, intent(in) :: dt - integer, intent(in) :: freq - logical, intent(in) :: flip - end subroutine jt4_average_callback - end interface contains - subroutine decode(this,decode_callback,dd,jz,nutc,nfqso,ntol0,emedelay, & - dttol,nagain,ndepth,nclearave,minsync,minw,nsubmode,mycall,hiscall, & - hisgrid,nlist0,listutc0,average_callback) + subroutine wsjt4(this,dat,npts,nutc,minsync,ntol,mode4,minw,mycall,hiscall,hisgrid,nfqso,ndepth) - use jt4 - use timer_module, only: timer +! JT4 searches for one signal within the selected frequency tolerance. - class(jt4_decoder), intent(inout) :: this - procedure(jt4_decode_callback) :: decode_callback - integer, intent(in) :: jz,nutc,nfqso,ntol0,ndepth,minsync,minw,nsubmode, & - nlist0,listutc0(10) - real, intent(in) :: dd(jz),emedelay,dttol - logical, intent(in) :: nagain, nclearave - character(len=12), intent(in) :: mycall,hiscall - character(len=6), intent(in) :: hisgrid - procedure(jt4_average_callback), optional :: average_callback - real*4 dat(30*11025) - character*6 cfile6 - save dat - - this%decode_callback => decode_callback - if (present (average_callback)) then - this%average_callback => average_callback - end if - mode4=nch(nsubmode+1) - ntol=ntol0 - neme=0 - lumsg=6 !### temp ? ### - ndiag=1 - nlist=nlist0 - listutc=listutc0 - - ! Lowpass filter and decimate by 2 - call timer('lpf1 ',0) - call lpf1(dd,jz,dat,jz2) - call timer('lpf1 ',1) - - write(cfile6(1:4),1000) nutc -1000 format(i4.4) - cfile6(5:6)=' ' - - call timer('wsjt4 ',0) - call this%wsjt4(dat,jz2,nutc,NClearAve,minsync,ntol,emedelay,dttol,mode4, & - minw,mycall,hiscall,hisgrid,nfqso,NAgain,ndepth,neme) - call timer('wsjt4 ',1) - - return - end subroutine decode - - subroutine wsjt4(this,dat,npts,nutc,NClearAve,minsync,ntol,emedelay,dttol, & - mode4,minw,mycall,hiscall,hisgrid,nfqso,NAgain,ndepth,neme) - -! Orchestrates the process of decoding JT4 messages. Note that JT4 -! always operates as if in "Single Decode" mode; it looks for only one -! decodable signal in the FTol range. - - use jt4 use timer_module, only: timer class(jt4_decoder), intent(inout) :: this integer, intent(in) :: npts,nutc,minsync,ntol,mode4,minw, & - nfqso,ndepth,neme - logical, intent(in) :: NAgain,NClearAve + nfqso,ndepth character(len=12), intent(in) :: mycall,hiscall character(len=6), intent(in) :: hisgrid real, intent(in) :: dat(npts) !Raw data - logical first,prtavg - character decoded*22,special*5 + logical prtavg,have_candidate + character decoded*22 character*22 avemsg,deepmsg,deepave,blank,deepmsg0,deepave1 character csync*1 - data first/.true./,nutc0/-999/,nfreq0/-999999/ - save - - if(first) then - nsave=0 - first=.false. - blank=' ' -! Silence compiler warnings - if(dttol.eq.-99.0 .and. emedelay.eq.-99.0 .and. nagain) stop - endif - zz=0. -! syncmin=3.0 + minsync + blank=' ' + decoded=blank + deepmsg=blank + deepmsg0=blank + deepave1=blank + avemsg=blank + csync=' ' + ich=0 + ich0=-1 + aveich=-1 + nfanoave=0 + ndeepave=0 + dtx0=0. + dtx1=0. + nfreq0=nfqso + nfreq1=nfqso syncmin=1.0+minsync - naggressive=0 - if(iand(ndepth,7).ge.2) naggressive=1 nq1=3 - nq2=6 - if(naggressive.eq.1) nq1=1 - if(NClearAve) then - nsave=0 - iutc=-1 - nfsave=0. - listutc=0 - ppsave=0. - rsymbol=0. - dtsave=0. - syncsave=0. - nfanoave=0 - ndeepave=0 - endif + if(iand(ndepth,7).ge.2) nq1=1 ! Attempt to synchronize: look for sync pattern, get DF and DT. call timer('sync4 ',0) - call sync4(dat,npts,ntol,nfqso,4,mode4,minw+1,dtx,dfx, & - snrx,snrsync,flip,width) + call this%sync4(dat,npts,ntol,nfqso,mode4,minw+1,dtx,dfx,snrsync,flip,have_candidate) sync=snrsync + this%sync_strength=sync dtxz=dtx-0.8 nfreqz=nint(dfx) call timer('sync4 ',1) nsnr=-26 - if(sync.lt.syncmin) then + if(.not.have_candidate.or.sync.lt.syncmin) then if (associated (this%decode_callback)) then call this%decode_callback(nsnr,dtxz,nfreqz,.false.,csync, & .false.,decoded,0.,ich,.false.,0) @@ -169,9 +137,6 @@ contains nsnr=nint(snrsync - 22.9) decoded=blank deepmsg=blank - special=' ' - nsync=sync - nsnrlim=-33 csync='*' if(flip.lt.0.0) csync='#' qbest=0. @@ -185,12 +150,12 @@ contains ! Attempt a single-sequence decode, including deep4 if Fano fails. call timer('decode4 ',0) - call decode4(dat,npts,dtx,nfreq,flip,mode4,ndepth,neme,minw, & + call this%decode4(dat,npts,dtx,nfreq,flip,mode4,ndepth,minw, & mycall,hiscall,hisgrid,decoded,nfano,deepmsg,qual,ich) call timer('decode4 ',1) if(nfano.gt.0) then - call getsnr(dat,npts,mode4,dtx,decoded,nsnr) + call this%getsnr(dat,npts,mode4,dtx,decoded,nsnr) ! Fano succeeded: report the message and return !Fano OK if (associated (this%decode_callback)) then call this%decode_callback(nsnr,dtx,nfreq,.true.,csync, & @@ -213,18 +178,12 @@ contains qave=0. ! If we're doing averaging, call avg4 if(iand(ndepth,16).eq.16 .and. (.not.prtavg)) then - if(nutc.ne.nutc0 .or. abs(nfreq-nfreq0).gt.ntol) then -! This is a new minute or a new frequency, so call avg4. - nutc0=nutc !Try decoding average - nfreq0=nfreq - nsave=nsave+1 - nsave=mod(nsave-1,64)+1 - call timer('avg4 ',0) - call this%avg4(nutc,sync,dtx,flip,nfreq,mode4,ntol,ndepth,neme, & - mycall,hiscall,hisgrid,nfanoave,avemsg,qave,deepave,ich, & - ndeepave) - call timer('avg4 ',1) - endif + call this%save_average(nutc,sync,dtx,flip,nfreq,ntol) + if(this%kernel_status/=0) return + call timer('avg4 ',0) + call this%avg4(nutc,dtx,flip,nfreq,mode4,ntol,ndepth, & + mycall,hiscall,hisgrid,nfanoave,avemsg,qave,deepave,ich,ndeepave) + call timer('avg4 ',1) if(nfanoave.gt.0) then ! Fano succeeded: report the message AVG FANO OK @@ -239,7 +198,7 @@ contains dtx1=dtx nfreq1=nfreq deepave1=deepave - ich1=ich + aveich=ich qabest=qave endif endif @@ -253,7 +212,7 @@ contains qual=qbest if (associated (this%decode_callback)) then - if(qual.gt.0.0) call getsnr(dat,npts,mode4,dtx,deepmsg,nsnr) + if(qual.gt.0.0) call this%getsnr(dat,npts,mode4,dtx,deepmsg,nsnr) if(int(qual).ge.nq1) then call this%decode_callback(nsnr,dtx,nfreqz,.true.,csync,.true., & deepmsg,qual,ich,.false.,0) @@ -266,7 +225,7 @@ contains dtx=dtx1 nfreq=nfreq1 deepave=deepave1 - ich=ich1 + ich=aveich qave=qabest if (associated (this%decode_callback) .and. ndeepave.ge.2) then @@ -279,103 +238,27 @@ contains 990 return end subroutine wsjt4 - subroutine avg4(this,nutc,snrsync,dtxx,flip,nfreq,mode4,ntol,ndepth,neme, & + subroutine avg4(this,nutc,dtxx,flip,nfreq,mode4,ntol,ndepth, & mycall,hiscall,hisgrid,nfanoave,avemsg,qave,deepave,ichbest,ndeepave) ! Decodes averaged JT4 data - use jt4 class(jt4_decoder), intent(inout) :: this character*22 avemsg,deepave,deepbest character mycall*12,hiscall*12,hisgrid*6 - character*1 csync,cused(64) real sym(207,7) - integer iused(64) - logical first - data first/.true./ - save - - if(first) then - iutc=-1 - nfsave=0 - dtdiff=0.2 - first=.false. - nsave=1 ! ### Should this be here? ### - endif - - do i=1,64 - if(nutc.eq.iutc(i) .and. abs(nfreq-nfsave(i)).le.ntol) go to 10 - enddo - -! Save data for message averaging - iutc(nsave)=nutc - syncsave(nsave)=snrsync - dtsave(nsave)=dtxx - nfsave(nsave)=nfreq - flipsave(nsave)=flip - ppsave(1:207,1:7,nsave)=rsymbol(1:207,1:7) - -10 sym=0. - syncsum=0. - dtsum=0. - nfsum=0 - nsum=0 - - do i=1,64 - cused(i)='.' - if(iutc(i).lt.0) cycle - if(mod(iutc(i),2).ne.mod(nutc,2)) cycle !Use only same sequence - if(abs(dtxx-dtsave(i)).gt.dtdiff) cycle !DT must match - if(abs(nfreq-nfsave(i)).gt.ntol) cycle !Freq must match - if(flip.ne.flipsave(i)) cycle !Sync (*/#) must match - sym(1:207,1:7)=sym(1:207,1:7) + ppsave(1:207,1:7,i) - syncsum=syncsum + syncsave(i) - dtsum=dtsum + dtsave(i) - nfsum=nfsum + nfsave(i) - cused(i)='$' - nsum=nsum+1 - iused(nsum)=i - enddo - if(nsum.lt.64) iused(nsum+1)=0 - - syncave=0. - dtave=0. - fave=0. - if(nsum.gt.0) then - sym=sym/nsum - syncave=syncsum/nsum - dtave=dtsum/nsum - fave=float(nfsum)/nsum - endif - - do i=1,nsave - csync='*' - if(flipsave(i).lt.0.0) csync='#' - if (associated (this%average_callback)) then - call this%average_callback(cused(i) .eq. '$',iutc(i), & - syncsave(i),dtsave(i),nfsave(i),flipsave(i).lt.0.) - end if - enddo - - sqt=0. - sqf=0. - do j=1,64 - i=iused(j) - if(i.eq.0) exit - csync='*' - if(flipsave(i).lt.0.0) csync='#' - sqt=sqt + (dtsave(i)-dtave)**2 - sqf=sqf + (nfsave(i)-fave)**2 - enddo - rmst=0. - rmsf=0. - if(nsum.ge.2) then - rmst=sqrt(sqt/(nsum-1)) - rmsf=sqrt(sqf/(nsum-1)) - endif - kbest=ich1 - do k=ich1,ich2 + call this%select_average(nutc,dtxx,flip,nfreq,ntol,sym,nsum) + nfanoave=0 + ndeepave=0 + avemsg=' ' + deepave=' ' + deepbest=' ' + qave=0. + ichbest=-1 + if(nsum==0) return + kbest=this%ich1 + do k=this%ich1,this%ich2 call extract4(sym(1,k),ncount,avemsg) !Do the Fano decode nfanoave=0 if(ncount.ge.0) then @@ -389,12 +272,11 @@ contains deepave=' ' qave=0. -! Possibly should pass nadd=nused, also ? if(iand(ndepth,32).eq.32) then flipx=1.0 !Normal flip not relevant for ave msg qbest=0. - do k=ich1,ich2 - call deep4(sym(2,k),neme,flipx,mycall,hiscall,hisgrid,deepave,qave) + do k=this%ich1,this%ich2 + call this%deep4(sym(2,k),flipx,mycall,hiscall,hisgrid,deepave,qave) if(qave.gt.qbest) then qbest=qave deepbest=deepave @@ -411,35 +293,35 @@ contains 900 return end subroutine avg4 -end module jt4_decode - -subroutine getsnr(dat,npts,mode4,dtx,decoded,nsnr) +subroutine getsnr(this,dat,npts,mode4,dtx,decoded,nsnr) ! Compute SNR using raw data, T, DF, and decoded message. - + + class(jt4_decoder),intent(inout) :: this parameter(NSPS=1260,NH=NSPS/2) real dat(npts) - real x(NSPS) + real,pointer :: x(:) real s(NH),savg(NH) - complex cx(0:NSPS/2) + complex,pointer :: cx(:) integer itone(206) integer ipk(1) character*22 decoded,msgsent - equivalence (x,cx) + x=>this%transform(4)%x + cx=>this%transform(4)%cx call gen4(decoded,0,msgsent,itone,itype) !Get itone values for this message dt=1.0/5512.5 df=5512.5/NSPS istart=(dtx+1.08)/dt - + savg=0. do j=1,206 !Loop over all symbols cx=0. do i=1,NSPS k=(j-1)*NSPS + i + istart if(k.ge.1 .and. k.le.npts) x(i)=dat(k) - enddo - call four2a(cx,NSPS,1,-1,0) !r2c FFT + enddo + call fftwf_execute_dft_r2c(this%transform(4)%forward,x,cx) !r2c FFT do i=1,nh s(i)=real(cx(i))**2 + aimag(cx(i))**2 enddo @@ -449,35 +331,744 @@ subroutine getsnr(dat,npts,mode4,dtx,decoded,nsnr) nskip=mode4/2 call averms(savg,nh,nskip,ave,rms) + if(rms<=tiny(rms)) then + nsnr=-33 + return + endif savg=(savg-ave)/rms do i=1,mode4/4 call smo121(savg,nh) enddo - + ipk=maxloc(savg) psig=0. do i=ipk(1),1,-1 if(savg(i).lt.0) exit psig=psig + savg(i) enddo - i1=i+1 do i=ipk(1),nh if(savg(i).lt.0) exit psig=psig + savg(i) enddo - i2=i-1 pnoise=2500.0*sqrt(206.0)/df snrdb=db(psig/pnoise) nsnr=nint(snrdb) - width=(i2-i1)*df -! rewind(62) -! do i=1,nh -! write(62,1010) i*df,savg(i) -!1010 format(2f10.3) -! enddo -! flush(62) - return end subroutine getsnr + +subroutine decode4(this,dat,npts,dtx,nfreq,flip,mode4,ndepth,minw, & + mycall,hiscall,hisgrid,decoded,nfano,deepbest,qbest,ichbest) + +! Decodes JT4 data, assuming that DT and DF have already been determined. +! Input dat(npts) has already been downsampled by 2: rate = 11025/2. + + class(jt4_decoder),intent(inout) :: this + real dat(npts) !Raw data + character decoded*22,deepmsg*22,deepbest*22 + character*12 mycall,hiscall + character*6 hisgrid + real*8 dt,df,phi,f0,dphi,twopi,phi1,dphi1 + complex*16 cz,cz1,c0,c1 + real*4 sym(207) + + twopi=8*atan(1.d0) + dt=2.d0/11025 !Sample interval (2x downsampled data) + df=11025.d0/2520.d0 !Tone separation for JT4A mode + nsym=206 + amp=15.0 + istart=nint((dtx+0.8)/dt) !Start index for synced FFTs + if(istart.lt.0) istart=0 + nchips=0 + nfano=0 + decoded=' ' + deepbest=' ' + qbest=0. + deepmsg=' ' + ichbest=-1 + c0=0. + k=istart + phi=0.d0 + phi1=0.d0 + + this%ich1=minw+1 + do ich=1,7 + if(nch(ich).le.mode4) this%ich2=ich + enddo + + do ich=this%ich1,this%ich2 + nchips=min(nch(ich),70) + nspchip=1260/nchips + k=istart + phi=0.d0 + phi1=0.d0 + fac2=1.e-8 * sqrt(float(mode4)) + do j=1,nsym+1 + if(flip.gt.0.0) then + f0=nfreq + (npr(j))*mode4*df + f1=nfreq + (2+npr(j))*mode4*df + else + f0=nfreq + (1-npr(j))*mode4*df + f1=nfreq + (3-npr(j))*mode4*df + endif + dphi=twopi*dt*f0 + dphi1=twopi*dt*f1 + sq0=0. + sq1=0. + do nc=1,nchips + phi=0.d0 + phi1=0.d0 + c0=0. + c1=0. + do i=1,nspchip + k=k+1 + phi=phi+dphi + phi1=phi1+dphi1 + cz=dcmplx(cos(phi),-sin(phi)) + cz1=dcmplx(cos(phi1),-sin(phi1)) + if(k.le.npts) then + c0=c0 + dat(k)*cz + c1=c1 + dat(k)*cz1 + endif + enddo + sq0=sq0 + real(c0)**2 + aimag(c0)**2 + sq1=sq1 + real(c1)**2 + aimag(c1)**2 + enddo + sq0=fac2*sq0 + sq1=fac2*sq1 + rsym=amp*(sq1-sq0) + this%rsymbol(j,ich)=rsym + sym(j)=rsym + enddo + + call extract4(sym,ncount,decoded) !Do the convolutional decode + nfano=0 + if(ncount.ge.0) then + nfano=1 + ichbest=ich + exit + endif + + qual=0. !Now try deep search + if(iand(ndepth,32).eq.32) then + call this%deep4(sym(2),flip,mycall,hiscall,hisgrid,deepmsg,qual) + if(qual.gt.qbest) then + qbest=qual + deepbest=deepmsg + ichbest=ich + endif + endif + enddo + +end subroutine decode4 + +subroutine deep4(this,sym0,flip,mycall,hiscall,hisgrid,decoded,qual) + +! Deep search routine for JT4 + + class(jt4_decoder),intent(inout) :: this + parameter (MAXCALLS=7000,MAXRPT=63) + real*4 sym0(206),sym(206) + character callsign*12,grid*4,message*22,hisgrid*6 + character*12 mycall,hiscall + character*22 decoded + character(len=15) :: callgrid + character*180 line + character*4 rpt(MAXRPT) + integer ncode(206) + real :: pp(2*MAXCALLS + 2 + MAXRPT) + integer :: allocation_status + data rpt/'-01','-02','-03','-04','-05', & + '-06','-07','-08','-09','-10', & + '-11','-12','-13','-14','-15', & + '-16','-17','-18','-19','-20', & + '-21','-22','-23','-24','-25', & + '-26','-27','-28','-29','-30', & + 'R-01','R-02','R-03','R-04','R-05', & + 'R-06','R-07','R-08','R-09','R-10', & + 'R-11','R-12','R-13','R-14','R-15', & + 'R-16','R-17','R-18','R-19','R-20', & + 'R-21','R-22','R-23','R-24','R-25', & + 'R-26','R-27','R-28','R-29','R-30', & + 'RO','RRR','73'/ + + sym=sym0 + if(mycall.eq.this%mycall0 .and. hiscall.eq.this%hiscall0 .and. & + hisgrid.eq.this%hisgrid0 .and. this%templates_valid) go to 30 + + if(.not.allocated(this%code)) then + allocate(this%code(206,64+2*size(this%calls)),this%testmsg(64+2*size(this%calls)),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + if(allocated(this%code)) deallocate(this%code) + if(allocated(this%testmsg)) deallocate(this%testmsg) + decoded=' ' + qual=0. + return + endif + endif + k=0 + do n=1,1+size(this%calls) + if(n.eq.1) then + callsign=hiscall + do i=4,12 + if(ichar(callsign(i:i)).eq.0) callsign(i:i)=' ' + enddo + grid=hisgrid(1:4) + if(ichar(grid(3:3)).eq.0) grid(3:3)=' ' + if(ichar(grid(4:4)).eq.0) grid(4:4)=' ' + else + callsign=this%calls(n-1)%call + grid=this%calls(n-1)%grid + endif + + j1=index(mycall,' ') - 1 + if(j1.le.-1) j1=12 + if(j1.lt.3) j1=6 + j2=index(callsign,' ') - 1 + if(j2.le.-1) j2=12 + if(j2.lt.3) j2=6 + j3=index(mycall,'/') ! j3>0 means compound mycall + j4=index(callsign,'/') ! j4>0 means compound hiscall + callgrid=callsign(1:j2) + + mz=1 +! The current contact also supplies report and acknowledgement templates. + if(n.eq.1 .and. j3.lt.1 .and. j4.lt.1 .and. callsign(1:6).ne.' ') & + mz=MAXRPT+1 + do m=1,mz + if(m.gt.1) grid=rpt(m-1) + if(j3.lt.1 .and.j4.lt.1) callgrid=callsign(1:j2)//' '//grid + message=mycall(1:j1)//' '//callgrid + k=k+1 + this%testmsg(k)=message + call encode4(message,ncode) + this%code(1:206,k)=2*ncode(1:206)-1 + if(n.ge.2) then +! Insert CQ message + if(j4.lt.1) callgrid=callsign(1:j2)//' '//grid + message='CQ '//callgrid + k=k+1 + this%testmsg(k)=message + call encode4(message,ncode) + this%code(1:206,k)=2*ncode(1:206)-1 + endif + enddo + enddo + + this%ntot=k + +30 this%mycall0=mycall + this%hiscall0=hiscall + this%hisgrid0=hisgrid + this%templates_valid=.true. + + sq=0. + do j=1,206 + sq=sq + sym(j)**2 + enddo + rms=sqrt(sq/206.0) + decoded=' ' + qual=0. + if(rms<=tiny(rms)) return + sym=sym/rms + ip1=1 + + p1=-1.e30 + p2=-1.e30 + do k=1,this%ntot + pp(k)=0. +! Test all messages if flip=+1; skip the CQ messages if flip=-1. + if(flip.gt.0.0 .or. this%testmsg(k)(1:3).ne.'CQ ') then + p=0. + do j=1,206 + p=p + this%code(j,k)*sym(j) + enddo + pp(k)=p + if(p.gt.p1) then + p1=p + ip1=k + endif + endif + enddo + + do i=1,this%ntot + if(pp(i).gt.p2 .and. this%testmsg(i).ne.this%testmsg(ip1)) p2=pp(i) + enddo + + qual=p1-max(1.15*p2,70.0) + + if(associated(this%diagnostic_callback)) then + write(line,1001) p1,p2,this%ntot,rms,qual,ip1,this%testmsg(ip1) +1001 format(2f8.2,i8,2f8.2,i6,2x,a22) + call this%diagnostic_callback(trim(line)) + endif + + if(qual.gt.1.0) then + decoded=this%testmsg(ip1) + else + decoded=' ' + qual=0. + endif + +! Make sure everything is upper case. + do i=1,22 + if(decoded(i:i).ge.'a' .and. decoded(i:i).le.'z') & + decoded(i:i)=char(ichar(decoded(i:i))-32) + enddo + +end subroutine deep4 + +subroutine sync4(this,dat,jz,ntol,nfqso,mode4,minwidth,dtx,dfx,snrsync,flip,have_candidate) + +! Synchronizes JT4 data, finding the best-fit DT and DF. + + class(jt4_decoder),intent(inout) :: this + parameter (NFFTMAX=2520) !Max length of FFTs + parameter (NHMAX=NFFTMAX/2) !Max length of power spectra + parameter (NSMAX=525) !Max number of half-symbol steps + integer ntol !Range of DF search + real dat(jz) + real ccfblue(-5:540) !CCF with pseudorandom sequence + logical,intent(out) :: have_candidate + +! Do FFTs of twice symbol length, stepped by half symbols. Note that +! we have already downsampled the data by factor of 2. + dtx=0. + dfx=real(nfqso) + snrsync=0. + have_candidate=.false. + flip=1. + nsym=207 + nfft=2520 + nq=nfft/4 + nsteps=jz/nq - 1 + df=0.5*11025.0/nfft + ftop=nfqso + 7*mode4*df + if(ftop.gt.11025.0/4.0) then + go to 900 + endif + + + do j=1,nsteps !Compute spectrum for each step, get average + k=(j-1)*nq + 1 + call this%ps4(dat(k),nfft,this%s2(1,j)) + enddo + +! Set freq and lag ranges + ia=(nfqso-ntol)/df !Index of lowest tone, bottom of search range + ib=(nfqso+ntol)/df !Index of lowest tone, top of search range + iamin=nint(100.0/df) + if(ia.lt.iamin) ia=iamin + ibmax=nint(2700.0/df) - 6*mode4 + if(ib.gt.ibmax) ib=ibmax + + lag1=-5 + lag2=59 + syncbest=-1.e30 + + do ich=minwidth,7 !Find best width + kz=nch(ich)/2 + iaa=ia+kz + ibb=ib-kz + do i=iaa,ibb !Find best frequency channel for CCF + call xcor4(this%s2,i,nsteps,nsym,lag1,lag2,ich,mode4,ccfblue,ccf0, & + lagpk0,flip) + +! Find rms of the CCF, without main peak + call slope(ccfblue(lag1),lag2-lag1+1,lagpk0-lag1+1.0) + sync=abs(ccfblue(lagpk0)) + +! Find best sync value + if(sync.gt.syncbest*1.03) then + ipk=i + ichpk=ich + syncbest=sync + endif + enddo + enddo + if(syncbest<=0.) go to 900 + + dfx=ipk*df + +! Peak up in time, at best whole-channel frequency + call xcor4(this%s2,ipk,nsteps,nsym,lag1,lag2,ichpk,mode4,ccfblue,ccfmax, & + lagpk,flip) + xlag=lagpk + if(lagpk.gt.lag1 .and. lagpk.lt.lag2) then + call peakup(ccfblue(lagpk-1),ccfmax,ccfblue(lagpk+1),dx2) + xlag=lagpk+dx2 + endif + +! Find rms of the CCF, without the main peak + call slope(ccfblue(lag1),lag2-lag1+1,xlag-lag1+1.0) + sq=0. + nsq=0 + do lag=lag1,lag2 + if(abs(lag-xlag).gt.2.0) then + sq=sq+ccfblue(lag)**2 + nsq=nsq+1 + endif + enddo + rms=sqrt(sq/nsq) + if(rms<=tiny(rms)) return + snrsync=max(0.0,db(abs(ccfblue(lagpk)/rms - 1.0)) - 4.5) + dt=2.0/11025.0 + istart=xlag*nq + dtx=istart*dt + have_candidate=.true. + +900 return +end subroutine sync4 + +subroutine lpf1(this,dd,jz,dat,jz2) + + class(jt4_decoder),intent(inout) :: this + parameter (NFFT1=64*11025,NFFT2=32*11025) + real dd(jz) + real dat(jz/2) + real,pointer :: x(:) + complex,pointer :: cx(:) + x=>this%transform(2)%x + cx=>this%transform(2)%cx + + fac=1.0/float(NFFT1) + x(1:jz)=fac*dd(1:jz) + x(jz+1:NFFT1)=0.0 + call fftwf_execute_dft_r2c(this%transform(2)%forward,x,cx) !Forward FFT, r2c + cx(NFFT2/2:)=0.0 + + + call fftwf_execute_dft_c2r(this%transform(2)%backward,cx,x) !Inverse FFT, c2r + jz2=jz/2 + dat(1:jz2)=x(1:jz2) + +end subroutine lpf1 + +subroutine ps4(this,dat,nfft,s) + + class(jt4_decoder),intent(inout) :: this + parameter (NMAX=2520+2) + parameter (NHMAX=NMAX/2-1) + real dat(nfft) + real,pointer :: dat2(:) + real s(NHMAX) + complex,pointer :: c(:) + dat2=>this%transform(3)%x + c=>this%transform(3)%cx + + nh=nfft/2 + do i=1,nh + dat2(i)=dat(i)/128.0 !### Why 128 ?? + enddo + do i=nh+1,nfft + dat2(i)=0. + enddo + + call fftwf_execute_dft_r2c(this%transform(3)%forward,dat2,c) + + fac=1.0/nfft + do i=1,nh + s(i)=fac*(real(c(i))**2 + aimag(c(i))**2) + enddo + +end subroutine ps4 + + subroutine decode_pcm(this,options,input,sample_rate_hz,decode_callback,status,diagnostic_callback) + class(jt4_decoder),intent(inout) :: this + type(jt4_options),intent(in) :: options + integer(c_int16_t),intent(in) :: input(:) + integer,intent(in) :: sample_rate_hz + procedure(jt4_decode_callback) :: decode_callback + integer,intent(out) :: status + procedure(jt4_diagnostic_callback),optional :: diagnostic_callback + integer :: jz,jz2,depth,n + real,pointer :: x(:) + complex,pointer :: cx(:) + + status=-1 + if(sample_rate_hz/=11025.and.sample_rate_hz/=12000) return + if(size(input)<1.or.size(input)>60*sample_rate_hz) return + if(options%submode<0.or.options%submode>6) return + if(options%minimum_width_profile<0.or.options%minimum_width_profile>options%submode) return + call this%prepare_workspace(status,sample_rate_hz==12000) + if(status/=0) return + this%decode_callback=>decode_callback + nullify(this%diagnostic_callback) + if(present(diagnostic_callback)) this%diagnostic_callback=>diagnostic_callback + if(this%current_submode/=options%submode.or.this%current_minimum_profile/=options%minimum_width_profile) & + call this%clear_averages() + this%current_submode=options%submode + this%current_minimum_profile=options%minimum_width_profile + if(.not.this%prepared) then + this%pcm=0. + jz=min(size(input),52*sample_rate_hz) + if(sample_rate_hz==11025) then + this%pcm(1:jz)=real(input(1:jz)) + else + x=>this%transform(1)%x + cx=>this%transform(1)%cx + x=0. + x(1:jz)=real(input(1:jz)) + call fftwf_execute_dft_r2c(this%transform(1)%forward,x,cx) + cx(320000:)=0. + call fftwf_execute_dft_c2r(this%transform(1)%backward,cx,x) + n=int(jz*11025./12000.) + this%pcm(1:n)=1.e-6*x(1:n) + endif + call this%lpf1(this%pcm,52*11025,this%dat,jz2) + this%prepared=.true. + endif + depth=options%depth + if(options%averaging) depth=ior(depth,16) + if(options%deep_search) depth=ior(depth,32) + this%kernel_status=0 + call this%wsjt4(this%dat,26*11025,options%utc,options%min_sync,options%tolerance_hz, & + nch(options%submode+1),options%minimum_width_profile,options%mycall,options%hiscall, & + options%hisgrid,options%receive_frequency_hz,depth) + status=this%kernel_status + nullify(this%decode_callback,this%diagnostic_callback) + end subroutine + + subroutine prepare_workspace(this,status,include_conversion) + class(jt4_decoder),intent(inout) :: this + integer,intent(out) :: status + logical,intent(in),optional :: include_conversion + integer,parameter :: lengths(4)=[64*12000,64*11025,2520,1260] + integer,parameter :: inverse_lengths(4)=[64*11025,32*11025,0,0] + integer :: i,n,allocation_status,first + status=-1 + if(.not.allocated(this%pcm)) then + allocate(this%pcm(52*11025),stat=allocation_status) + if(allocation_status/=0) return + endif + if(.not.allocated(this%dat)) then + allocate(this%dat(30*11025),stat=allocation_status) + if(allocation_status/=0) return + endif + if(.not.allocated(this%s2)) then + allocate(this%s2(1260,525),stat=allocation_status) + if(allocation_status/=0) return + endif + if(.not.allocated(this%ppsave)) then + allocate(this%ppsave(207,7,MAXAVE),stat=allocation_status) + if(allocation_status/=0) return + this%ppsave=0. + endif + if(.not.allocated(this%rsymbol)) then + allocate(this%rsymbol(207,7),stat=allocation_status) + if(allocation_status/=0) return + this%rsymbol=0. + endif + if(.not.allocated(this%calls)) then + allocate(this%calls(0),stat=allocation_status) + if(allocation_status/=0) return + endif + first=2 + if(present(include_conversion)) then + if(include_conversion) first=1 + endif + do i=first,4 + n=lengths(i) + if(.not.c_associated(this%transform(i)%storage)) then + this%transform(i)%storage=fftwf_alloc_complex(int(n/2+1,c_size_t)) + if(.not.c_associated(this%transform(i)%storage)) return + call c_f_pointer(this%transform(i)%storage,this%transform(i)%x,[n+2]) + call c_f_pointer(this%transform(i)%storage,this%transform(i)%cx,[n/2+1]) + this%transform(i)%cx(0:n/2)=>this%transform(i)%cx + endif + if(.not.c_associated(this%transform(i)%forward)) then +!$omp critical(fftw) + this%transform(i)%forward=fftwf_plan_dft_r2c_1d(n,this%transform(i)%x, & + this%transform(i)%cx,this%fft_flags) +!$omp end critical(fftw) + endif + if(.not.c_associated(this%transform(i)%forward)) return + if(inverse_lengths(i)>0.and..not.c_associated(this%transform(i)%backward)) then +!$omp critical(fftw) + this%transform(i)%backward=fftwf_plan_dft_c2r_1d(inverse_lengths(i),this%transform(i)%cx, & + this%transform(i)%x,this%fft_flags) +!$omp end critical(fftw) + endif + if(inverse_lengths(i)>0.and..not.c_associated(this%transform(i)%backward)) return + enddo + status=0 + end subroutine + + subroutine set_fft_flags(this,flags) + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: flags + if(flags==this%fft_flags) return + call this%destroy_plans() + this%fft_flags=flags + this%prepared=.false. + end subroutine + + subroutine destroy_plans(this) + class(jt4_decoder),intent(inout) :: this + integer :: i +!$omp critical(fftw) + do i=1,4 + if(c_associated(this%transform(i)%forward)) call fftwf_destroy_plan(this%transform(i)%forward) + if(c_associated(this%transform(i)%backward)) call fftwf_destroy_plan(this%transform(i)%backward) + this%transform(i)%forward=c_null_ptr + this%transform(i)%backward=c_null_ptr + enddo +!$omp end critical(fftw) + end subroutine + + subroutine finalize_jt4(this) + type(jt4_decoder),intent(inout) :: this + integer :: i + call this%destroy_plans() + do i=1,4 + if(c_associated(this%transform(i)%storage)) call fftwf_free(this%transform(i)%storage) + this%transform(i)%storage=c_null_ptr + nullify(this%transform(i)%x,this%transform(i)%cx) + enddo + end subroutine + + subroutine release_input(this) + class(jt4_decoder),intent(inout) :: this + this%prepared=.false. + this%sync_strength=0. + nullify(this%decode_callback,this%diagnostic_callback) + end subroutine + + subroutine reset(this) + class(jt4_decoder),intent(inout) :: this + call this%release_input() + call this%clear_averages() + if(allocated(this%calls)) deallocate(this%calls) + if(allocated(this%code)) deallocate(this%code) + if(allocated(this%testmsg)) deallocate(this%testmsg) + this%templates_valid=.false. + this%ntot=0 + this%current_submode=-1 + this%current_minimum_profile=-1 + end subroutine + + subroutine set_calls(this,calls,status) + class(jt4_decoder),intent(inout) :: this + type(jt4_call),intent(in) :: calls(:) + integer,intent(out),optional :: status + type(jt4_call),allocatable :: replacement(:) + integer :: i,count,allocation_status + if(present(status)) status=0 + count=min(size(calls),6999) + if(allocated(this%calls)) then + if(size(this%calls)==count) then + do i=1,count + if(this%calls(i)%call/=calls(i)%call.or.this%calls(i)%grid/=calls(i)%grid) exit + enddo + if(i>count) return + endif + endif + allocate(replacement(count),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + if(present(status)) status=-1 + return + endif + replacement=calls(1:count) + call move_alloc(replacement,this%calls) + if(allocated(this%code)) deallocate(this%code) + if(allocated(this%testmsg)) deallocate(this%testmsg) + this%templates_valid=.false. + end subroutine + + subroutine clear_averages(this) + class(jt4_decoder),intent(inout) :: this + this%iutc=-1 + this%nfsave=0 + this%dtsave=0. + this%syncsave=0. + this%flipsave=0. + this%average_used=.false. + this%nsave=0 + this%average_count=0 + if(allocated(this%ppsave)) this%ppsave=0. + if(allocated(this%rsymbol)) this%rsymbol=0. + end subroutine + + subroutine save_average(this,utc,sync,dt,polarity,freq,tolerance) + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: utc,freq,tolerance + real,intent(in) :: sync,dt,polarity + integer :: i,allocation_status + if(.not.allocated(this%ppsave)) then + allocate(this%ppsave(207,7,MAXAVE),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + return + endif + this%ppsave=0. + endif + if(.not.allocated(this%rsymbol)) then + allocate(this%rsymbol(207,7),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + return + endif + this%rsymbol=0. + endif + do i=1,MAXAVE + if(this%iutc(i)/100==utc/100.and.this%iutc(i)>=0.and.abs(this%nfsave(i)-freq)<=tolerance) return + enddo + this%nsave=mod(this%nsave,MAXAVE)+1 + this%average_count=min(this%average_count+1,MAXAVE) + i=this%nsave + this%iutc(i)=utc + this%nfsave(i)=freq + this%syncsave(i)=sync + this%dtsave(i)=dt + this%flipsave(i)=polarity + this%ppsave(:,:,i)=this%rsymbol + this%average_used(i)=.false. + end subroutine + + subroutine select_average(this,utc,dt,polarity,freq,tolerance,sym,nsum) + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: utc,freq,tolerance + real,intent(in) :: dt,polarity + real,intent(out) :: sym(207,7) + integer,intent(out) :: nsum + integer :: i + sym=0. + nsum=0 + this%average_used=.false. + if(.not.allocated(this%ppsave)) return + do i=1,MAXAVE + if(this%iutc(i)<0) cycle + if(mod(this%iutc(i)/100,2)/=mod(utc/100,2)) cycle + if(abs(dt-this%dtsave(i))>0.2) cycle + if(abs(freq-this%nfsave(i))>tolerance) cycle + if(polarity/=this%flipsave(i)) cycle + sym=sym+this%ppsave(:,:,i) + nsum=nsum+1 + this%average_used(i)=.true. + enddo + if(nsum>0) sym=sym/nsum + end subroutine + + subroutine get_averages(this,entries,count) + class(jt4_decoder),intent(in) :: this + type(jt4_average_entry),intent(out) :: entries(:) + integer,intent(out) :: count + integer :: i + count=0 + do i=1,MAXAVE + if(this%iutc(i)<0) cycle + count=count+1 + if(count>size(entries)) cycle + entries(count)%utc=this%iutc(i) + entries(count)%frequency_hz=this%nfsave(i) + entries(count)%polarity=1 + if(this%flipsave(i)<0.) entries(count)%polarity=-1 + entries(count)%used=this%average_used(i) + entries(count)%sync=this%syncsave(i) + entries(count)%dt_seconds=this%dtsave(i) + enddo + end subroutine +end module jt4_decode diff --git a/lib/jt4_host_support.f90 b/lib/jt4_host_support.f90 new file mode 100644 index 00000000..b84e9629 --- /dev/null +++ b/lib/jt4_host_support.f90 @@ -0,0 +1,112 @@ +module jt4_host_support + use jt4_decode, only: jt4_decoder,jt4_call,jt4_average_entry + use decoder_engine_types, only: engine_jt4_options + use prog_args, only: data_dir + use fftw3, only: FFTW_ESTIMATE,FFTW_ESTIMATE_PATIENT,FFTW_MEASURE,FFTW_PATIENT,FFTW_EXHAUSTIVE + include 'jt9com.f90' + private + public :: convert_jt4_host_options,prepare_jt4_host,load_jt4_calls,write_jt4_averages,write_jt4_diagnostic + +contains + + subroutine convert_jt4_host_options(params,options,utc_is_hhmmss) + type(params_block), intent(in) :: params + type(engine_jt4_options), intent(out) :: options + logical, optional, intent(in) :: utc_is_hhmmss + + options=engine_jt4_options() + options%utc=100*params%nutc + if(present(utc_is_hhmmss)) then + if(utc_is_hhmmss) options%utc=params%nutc + endif + options%submode=params%nsubmode + options%receive_frequency_hz=params%nfqso + options%tolerance_hz=params%ntol + options%depth=iand(params%ndepth,7) + options%min_sync=params%minsync + options%minimum_width_profile=params%minw + options%averaging=merge(1_c_int,0_c_int,iand(params%ndepth,16)/=0) + options%deep_search=merge(1_c_int,0_c_int,iand(params%ndepth,32)/=0) + options%mycall=params%mycall + options%hiscall=params%hiscall + options%hisgrid=params%hisgrid + end subroutine convert_jt4_host_options + + subroutine prepare_jt4_host(decoder) + class(jt4_decoder), intent(inout) :: decoder + integer :: flags,npatience,nthreads + common/patience/npatience,nthreads + + flags=FFTW_ESTIMATE + select case(npatience) + case(1) + flags=FFTW_ESTIMATE_PATIENT + case(2) + flags=FFTW_MEASURE + case(3) + flags=FFTW_PATIENT + case(4) + flags=FFTW_EXHAUSTIVE + end select + call decoder%set_fft_flags(flags) + end subroutine prepare_jt4_host + + subroutine load_jt4_calls(decoder) + class(jt4_decoder), intent(inout) :: decoder + type(jt4_call), allocatable :: calls(:) + character(len=180) :: line + integer :: unit,ios,count,i,first,second + + allocate(calls(6999)) + count=0 + open(newunit=unit,file=trim(data_dir)//'/CALL3.TXT',status='old',action='read',iostat=ios) + if(ios==0) then + do i=1,size(calls) + read(unit,'(a80)',iostat=ios) line + if(ios/=0) exit + if(line(:4)=='ZZZZ') exit + if(line(:2)=='//') cycle + first=index(line,',') + if(first<4) cycle + second=index(line(first+1:),',') + if(second<5) cycle + count=count+1 + calls(count)%call=line(:first-1) + calls(count)%grid=line(first+1:first+4) + enddo + close(unit) + endif + call decoder%set_calls(calls(:count)) + end subroutine load_jt4_calls + + subroutine write_jt4_averages(decoder,unit) + class(jt4_decoder), intent(in) :: decoder + integer, intent(in) :: unit + type(jt4_average_entry) :: entries(64) + integer :: count,i + character :: used,polarity + + call decoder%get_averages(entries,count) + rewind(unit) + do i=1,count + used='.' + if(entries(i)%used) used='$' + polarity='*' + if(entries(i)%polarity<0) polarity='$' + write(unit,'(a1,i5.4,f6.1,f6.2,i6,1x,a1)') used,entries(i)%utc/100, & + entries(i)%sync,entries(i)%dt_seconds,entries(i)%frequency_hz,polarity + enddo + endfile(unit) + flush(unit) + end subroutine write_jt4_averages + + subroutine write_jt4_diagnostic(line) + character(len=*), intent(in) :: line + integer :: unit,ios + + open(newunit=unit,file='fort.77',status='replace',iostat=ios) + if(ios/=0) return + write(unit,'(a)') line + close(unit) + end subroutine write_jt4_diagnostic +end module jt4_host_support diff --git a/lib/jt9.f90 b/lib/jt9.f90 index 1e59bd8e..13e0dfb0 100644 --- a/lib/jt9.f90 +++ b/lib/jt9.f90 @@ -394,6 +394,7 @@ program jt9 stop 2 end if call parse_wav_filename_nutc(infile, nutc, wav_utc_has_seconds) + if(mode.eq.4.and.wav_utc_has_seconds) nutc=nutc/100 if((mode.eq.66.or.mode.eq.240.or.mode.eq.241.or.mode.eq.242).and..not.wav_utc_has_seconds) & nutc=100*nutc nsps=6912 @@ -574,7 +575,7 @@ program jt9 endif ! Normal decoding pass - if(mode.eq.8.or.mode.eq.9.or.mode.eq.65.or.mode.eq.66.or. & + if(mode.eq.4.or.mode.eq.8.or.mode.eq.9.or.mode.eq.65.or.mode.eq.66.or. & mode.eq.240.or.mode.eq.241.or.mode.eq.242) then call run_engine_wav(shared_data%id2,engine_valid_samples) else if(mode.eq.5) then diff --git a/lib/jt9_params_init.f90 b/lib/jt9_params_init.f90 index aba14b66..f95c3a58 100644 --- a/lib/jt9_params_init.f90 +++ b/lib/jt9_params_init.f90 @@ -150,6 +150,11 @@ contains ! FST4 60s period uses a larger sample window (jt9.f90:485 in WAV path). if (mode .eq. 240) params%kin = 720000 + if(mode==4) then + params%kin=624000 + params%minw=0 + params%minsync=0 + endif ! JT9 with explicit -S: remap nfa to fsplit (jt9.f90:386, :560). if (mode .eq. 9 .and. args%fsplit .ne. 2700) params%nfa = args%fsplit @@ -185,6 +190,7 @@ contains params%nftx = args%nrxfreq params%minw = 1 + if(params%nmode==4.and.params%nsubmode==0) params%minw=0 params%minsync = 0 params%nlist = 0 params%max_drift = 0 diff --git a/lib/jt9a.f90 b/lib/jt9a.f90 index c1a5a20a..85a02a8e 100644 --- a/lib/jt9a.f90 +++ b/lib/jt9a.f90 @@ -171,11 +171,12 @@ subroutine jt9a() ! MSK144 call decode_msk144_core(shared_memory%payload%id2, local_params, data_dir, & completion) - elseif(local_params%nmode.eq.8.or.local_params%nmode.eq.5.or.local_params%nmode.eq.9.or. & + elseif(local_params%nmode.eq.4.or.local_params%nmode.eq.8.or.local_params%nmode.eq.5.or. & + local_params%nmode.eq.9.or. & local_params%nmode.eq.65.or.local_params%nmode.eq.66.or. & local_params%nmode.eq.240.or.local_params%nmode.eq.241.or.local_params%nmode.eq.242) then pass_valid_samples=min(shared_memory%metadata%valid_samples,180000) - if(local_params%nmode.eq.9.or.local_params%nmode.eq.65) & + if(local_params%nmode.eq.4.or.local_params%nmode.eq.9.or.local_params%nmode.eq.65) & pass_valid_samples=min(shared_memory%metadata%valid_samples,720000) if(local_params%nmode.eq.66.or.local_params%nmode.eq.240.or. & local_params%nmode.eq.241.or.local_params%nmode.eq.242) & diff --git a/lib/lpf1.f90 b/lib/lpf1.f90 deleted file mode 100644 index a620e9a5..00000000 --- a/lib/lpf1.f90 +++ /dev/null @@ -1,29 +0,0 @@ -subroutine lpf1(dd,jz,dat,jz2) - - parameter (NFFT1=64*11025,NFFT2=32*11025) - real dd(jz) - real dat(jz) - real x(NFFT1) - complex cx(0:NFFT1/2) - equivalence (x,cx) - save x,cx - - fac=1.0/float(NFFT1) - x(1:jz)=fac*dd(1:jz) - x(jz+1:NFFT1)=0.0 - call four2a(cx,NFFT1,1,-1,0) !Forwarxd FFT, r2c - cx(NFFT2/2:)=0.0 - -! df=11025.0/NFFT1 -! do i=1,NFFT1/2 -! sx=real(cx(i))**2 + aimag(cx(i))**2 -! write(50,3000) i*df,sx -!3000 format(f15.6,e12.3) -! enddo - - call four2a(cx,NFFT2,1,1,-1) !Inverse FFT, c2r - jz2=jz/2 - dat(1:jz2)=x(1:jz2) - - return -end subroutine lpf1 diff --git a/lib/ps4.f90 b/lib/ps4.f90 deleted file mode 100644 index 782ab50d..00000000 --- a/lib/ps4.f90 +++ /dev/null @@ -1,27 +0,0 @@ -subroutine ps4(dat,nfft,s) - - parameter (NMAX=2520+2) - parameter (NHMAX=NMAX/2-1) - real dat(nfft) - real dat2(NMAX) - real s(NHMAX) - complex c(0:NMAX) - equivalence(dat2,c) - - nh=nfft/2 - do i=1,nh - dat2(i)=dat(i)/128.0 !### Why 128 ?? - enddo - do i=nh+1,nfft - dat2(i)=0. - enddo - - call four2a(c,nfft,1,-1,0) - - fac=1.0/nfft - do i=1,nh - s(i)=fac*(real(c(i))**2 + aimag(c(i))**2) - enddo - - return -end subroutine ps4 diff --git a/lib/streaming_apply.f90 b/lib/streaming_apply.f90 index 0a507481..98573ba4 100644 --- a/lib/streaming_apply.f90 +++ b/lib/streaming_apply.f90 @@ -68,6 +68,9 @@ contains end if if (in_cfg%depth_set) params%ndepth = in_cfg%depth if (in_cfg%submode_set) params%nsubmode = in_cfg%submode + if ((in_cfg%mode_set.or.in_cfg%submode_set).and..not.in_cfg%min_width_set) then + if(params%nmode==4.and.params%nsubmode==0) params%minw=0 + endif if (in_cfg%rxfreq_set) then params%nfqso = in_cfg%rxfreq params%nftx = in_cfg%rxfreq @@ -287,8 +290,8 @@ contains if ((io_mode.eq.240.or.io_mode.eq.241.or.io_mode.eq.242).and.io_TRperiod.ge.60.and. & params%nutc.le.2359) & params%nutc=100*params%nutc - ! Legacy numeric Q65 times may be HHMM. - if (io_mode.eq.66.and.io_TRperiod.ge.60.and.params%nutc.le.2359) & + ! Legacy numeric JT4 and Q65 times may be HHMM. + if ((io_mode.eq.4.or.io_mode.eq.66).and.io_TRperiod.ge.60.and.params%nutc.le.2359) & params%nutc=100*params%nutc endif ! Phase 8 (RFC v1 §6.3/§4.1): utc (ISO "HH:MM:SS") is a SECOND route to nutc, diff --git a/lib/streaming_control.f90 b/lib/streaming_control.f90 index a65915bd..2b02dbac 100644 --- a/lib/streaming_control.f90 +++ b/lib/streaming_control.f90 @@ -61,7 +61,8 @@ module streaming_control integer :: nfa = 0 logical :: nfb_set = .false. integer :: nfb = 0 - ! Per-period UTC as HHMMSS integer. Threaded into + ! Per-period UTC as HHMMSS integer; in periods of a minute or more a + ! value up to 2359 is read as HHMM. Threaded into ! params%nutc so streaming_emit_decode can format the time field ! correctly. Producer should send a fresh nutc in each period's ! configure frame (mirrors WAV-path filename-derived per-invocation diff --git a/lib/streaming_emit.f90 b/lib/streaming_emit.f90 index b3346926..0b6e4590 100644 --- a/lib/streaming_emit.f90 +++ b/lib/streaming_emit.f90 @@ -26,8 +26,11 @@ module streaming_emit private logical, save :: enabled_ = .false. + logical, save :: utc_from_iso_ = .false. + real(8), save :: trperiod_ = 60.d0 public :: streaming_emit_set_enabled + public :: streaming_emit_set_time_form public :: streaming_emit_enabled public :: streaming_emit_ready public :: streaming_emit_decode @@ -44,6 +47,20 @@ contains enabled_ = flag end subroutine streaming_emit_set_enabled + ! Called after each applied configure. An ISO utc is HHMMSS; a numeric nutc + ! is HHMMSS when the period is under a minute or the value exceeds 2359, + ! and HHMM otherwise. + subroutine streaming_emit_set_time_form(utc_set, nutc_set, trperiod) + logical, intent(in) :: utc_set, nutc_set + real(8), intent(in) :: trperiod + if (utc_set) then + utc_from_iso_ = .true. + else if (nutc_set) then + utc_from_iso_ = .false. + end if + trperiod_ = trperiod + end subroutine streaming_emit_set_time_form + pure function streaming_emit_enabled() result(v) logical :: v v = enabled_ @@ -193,15 +210,17 @@ contains logical, optional, intent(in) :: utc_is_hhmmss integer :: hh, mm, ss logical :: full_time - full_time=.false. - if(present(utc_is_hhmmss)) full_time=utc_is_hhmmss + full_time=utc_from_iso_.or.trperiod_.lt.60.d0.or.nutc.gt.2359 + if(present(utc_is_hhmmss)) full_time=full_time.or.utc_is_hhmmss str = '000000' - if (full_time.or.nutc.ge.100000) then + if (nutc .lt. 0) then + return + else if (full_time) then hh = nutc / 10000 mm = mod(nutc/100, 100) ss = mod(nutc, 100) write(str, '(i2.2,i2.2,i2.2)') hh, mm, ss - else if (nutc .ge. 0) then + else hh = nutc / 100 mm = mod(nutc, 100) write(str, '(i2.2,i2.2,a2)') hh, mm, '00' diff --git a/lib/streaming_io.f90 b/lib/streaming_io.f90 index a2c9fa28..ed1ac923 100644 --- a/lib/streaming_io.f90 +++ b/lib/streaming_io.f90 @@ -52,7 +52,7 @@ subroutine jt9_stream(shared_data, mode, TRperiod) use streaming_emit, only: streaming_emit_ready, & streaming_emit_decode_finished, streaming_emit_error, & streaming_emit_error_code, streaming_emit_error_version, & - streaming_emit_error_type + streaming_emit_error_type, streaming_emit_set_time_form use streaming_control, only: parse_control_frame, configure_fields, & control_type_error, CTRL_CONFIGURE, CTRL_HALT, CTRL_PARSE_ERR use streaming_apply, only: apply_configure_fields @@ -327,6 +327,7 @@ subroutine jt9_stream(shared_data, mode, TRperiod) prev_TRperiod = TRperiod call apply_configure_fields(cfg, mode, TRperiod, & shared_data%params, baseline_nfa, baseline_nfb) + call streaming_emit_set_time_form(cfg%utc_set, cfg%nutc_set, TRperiod) ! A configure that changes the applied mode or period starts a ! new period; what was in flight is discarded. Repeating the ! current configuration leaves the period alone. @@ -381,7 +382,7 @@ contains shared_data%params%nzhsym = 181 end if shared_data%params%kin = 64800 - if (mode .eq. 5 .or. mode .eq. 9 .or. mode .eq. 65 .or. mode .eq. 66 .or. & + if (mode .eq. 4 .or. mode .eq. 5 .or. mode .eq. 9 .or. mode .eq. 65 .or. mode .eq. 66 .or. & mode .eq. 240 .or. mode .eq. 241 .or. mode .eq. 242) & shared_data%params%kin = period%k diff --git a/lib/sync4.f90 b/lib/sync4.f90 deleted file mode 100644 index 9f7ceefc..00000000 --- a/lib/sync4.f90 +++ /dev/null @@ -1,146 +0,0 @@ -subroutine sync4(dat,jz,ntol,nfqso,mode,mode4,minwidth,dtx,dfx,snrx, & - snrsync,flip,width) - -! Synchronizes JT4 data, finding the best-fit DT and DF. - - parameter (NFFTMAX=2520) !Max length of FFTs - parameter (NHMAX=NFFTMAX/2) !Max length of power spectra - parameter (NSMAX=525) !Max number of half-symbol steps - integer ntol !Range of DF search - real dat(jz) - real s2(NHMAX,NSMAX) !2d spectrum, stepped by half-symbols - real ccfblue(-5:540) !CCF with pseudorandom sequence - real ccfred(NHMAX) !Peak of ccfblue, as function of freq - real red(NHMAX) !Peak of ccfblue, as function of freq - integer ipk1(1) - integer nch(7) - logical savered - equivalence (ipk1,ipk1a) - data nch/1,2,4,9,18,36,72/ - save - -! Do FFTs of twice symbol length, stepped by half symbols. Note that -! we have already downsampled the data by factor of 2. - nsym=207 - nfft=2520 - nh=nfft/2 - nq=nfft/4 - nsteps=jz/nq - 1 - df=0.5*11025.0/nfft - ftop=nfqso + 7*mode4*df - if(ftop.gt.11025.0/4.0) then - print*,'*** Rx Freq is set too high for this submode ***' - go to 900 - endif - - if(mode.eq.-999) width=0. !Silence compiler warning - - do j=1,nsteps !Compute spectrum for each step, get average - k=(j-1)*nq + 1 - call ps4(dat(k),nfft,s2(1,j)) - enddo - -! Set freq and lag ranges - ia=(nfqso-ntol)/df !Index of lowest tone, bottom of search range - ib=(nfqso+ntol)/df !Index of lowest tone, top of search range - iamin=nint(100.0/df) - if(ia.lt.iamin) ia=iamin - ibmax=nint(2700.0/df) - 6*mode4 - if(ib.gt.ibmax) ib=ibmax - - lag1=-5 - lag2=59 - syncbest=-1.e30 - snrx=-26.0 - ccfred=0. - red=0. - i0=nint(nfqso/df) - - do ich=minwidth,7 !Find best width - kz=nch(ich)/2 - savered=.false. - iaa=ia+kz - ibb=ib-kz - do i=iaa,ibb !Find best frequency channel for CCF - call xcor4(s2,i,nsteps,nsym,lag1,lag2,ich,mode4,ccfblue,ccf0, & - lagpk0,flip) - ccfred(i)=ccf0 - -! Find rms of the CCF, without main peak - call slope(ccfblue(lag1),lag2-lag1+1,lagpk0-lag1+1.0) - sync=abs(ccfblue(lagpk0)) -! write(*,3000) ich,i,i*df,ccf0,sync,syncbest -!3000 format(2i5,4f12.3) - -! Find best sync value - if(sync.gt.syncbest*1.03) then - ipk=i - lagpk=lagpk0 - ichpk=ich - syncbest=sync - savered=.true. - endif - enddo - if(savered) red=ccfred - enddo - if(syncbest.lt.-1.e29) go to 900 - ccfred=red - call pctile(ccfred(iaa:ibb),ibb-iaa+1,45,base) - ccfred=ccfred-base - - dfx=ipk*df - -! Peak up in time, at best whole-channel frequency - call xcor4(s2,ipk,nsteps,nsym,lag1,lag2,ichpk,mode4,ccfblue,ccfmax, & - lagpk,flip) - xlag=lagpk - if(lagpk.gt.lag1 .and. lagpk.lt.lag2) then - call peakup(ccfblue(lagpk-1),ccfmax,ccfblue(lagpk+1),dx2) - xlag=lagpk+dx2 - endif - -! Find rms of the CCF, without the main peak - call slope(ccfblue(lag1),lag2-lag1+1,xlag-lag1+1.0) - sq=0. - nsq=0 - do lag=lag1,lag2 - if(abs(lag-xlag).gt.2.0) then - sq=sq+ccfblue(lag)**2 - nsq=nsq+1 - endif - enddo - rms=sqrt(sq/nsq) - snrsync=max(0.0,db(abs(ccfblue(lagpk)/rms - 1.0)) - 4.5) - dt=2.0/11025.0 - istart=xlag*nq - dtx=istart*dt - - ipk1=maxloc(ccfred) - ccf10=0.5*maxval(ccfred) - do i=ipk1a,ia,-1 - if(ccfred(i).le.ccf10) exit - enddo - i1=i - do i=ipk1a,ib - if(ccfred(i).le.ccf10) exit - enddo - nw=i-i1 - width=nw*df - - sq=0. - ns=0 - iaa=max(ipk1a-10*nw,ia) - ibb=min(ipk1a+10*nw,ib) - jmax=2*mode4/3 - do i=iaa,ibb - j=abs(i-ipk1a) - if(j.gt.nw .and. j.lt.jmax) then - sq=sq + ccfred(j)*ccfred(j) - ns=ns+1 - endif - enddo - rms=sqrt(sq/ns) - snrx=10.0*log10(ccfred(ipk1a)/rms) - 41.2 - -900 return -end subroutine sync4 diff --git a/lib/xcor4.f90 b/lib/xcor4.f90 index fa9c2012..2dc2deb9 100644 --- a/lib/xcor4.f90 +++ b/lib/xcor4.f90 @@ -1,40 +1,22 @@ subroutine xcor4(s2,ipk,nsteps,nsym,lag1,lag2,ich,mode4,ccf,ccf0, & lagpk,flip) -! Computes ccf of the 4_FSK spectral array s2 and the pseudo-random -! array pr2. Returns peak of CCF and the lag at which peak occurs. +! Computes ccf of the 4_FSK spectral array s2 and the pseudo-random +! array pr2. Returns peak of CCF and the lag at which peak occurs. ! The CCF peak may be either positive or negative, with negative ! implying the "OOO" message. + use jt4, only: nch,npr parameter (NHMAX=1260) !Max length of power spectra parameter (NSMAX=525) !Max number of half-symbol steps real s2(NHMAX,NSMAX) !2d spectrum, stepped by half-symbols real a(NSMAX) real ccf(-5:540) - integer nch(7) - integer npr2(207) real pr2(207) - logical first - data lagmin/0/ !Silence compiler warning - data first/.true./ - data npr2/ & - 0,0,0,0,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0, & - 0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,0,0, & - 1,0,0,1,0,0,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,1,1,0,0,1, & - 0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1,0,1,0,1, & - 0,1,1,1,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1,0,0,0,1,1,1, & - 0,1,1,1,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,1,1,1,1, & - 1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1/ - data nch/1,2,4,9,18,36,72/ - save - - if(first) then - do i=1,207 - pr2(i)=2*npr2(i)-1 - enddo - first=.false. - endif + pr2=2*npr-1 + lagpk=lag1 + lagmin=lag1 ccfmax=0. ccfmin=0. nw=nch(min(max(ich,1),7)) diff --git a/main.cpp b/main.cpp index d9546e48..594c851e 100644 --- a/main.cpp +++ b/main.cpp @@ -297,6 +297,7 @@ int main(int argc, char *argv[]) bool jtty_tx_loopback_test {false}; bool ft8_tx_loopback_test {false}; bool receive_handoff_test {false}; + bool jt4_wav_test {false}; bool jt9_wav_test {false}; bool jt65_wav_test {false}; bool q65_wav_test {false}; @@ -400,6 +401,14 @@ int main(int argc, char *argv[]) QStringList {} << "receive-handoff-test", "Backlog two synthetic periods at the MainWindow receive boundary."); parser.addOption (receive_handoff_test_option); + QCommandLineOption jt4_wav_test_option ( + QStringList {} << "jt4-wav-test", + "Decode a JT4 WAV through the application and repeat the decode.", "wav-path"); + parser.addOption (jt4_wav_test_option); + QCommandLineOption jt4_wav_expected_option ( + QStringList {} << "jt4-wav-expected", + "Message that must appear during both JT4 WAV decodes.", "message"); + parser.addOption (jt4_wav_expected_option); QCommandLineOption jt9_wav_test_option ( QStringList {} << "jt9-wav-test", "Decode a JT9 WAV through the application and repeat the decode.", "wav-path"); @@ -472,6 +481,7 @@ int main(int argc, char *argv[]) jtty_tx_loopback_test = parser.isSet (jtty_tx_loopback_test_option); ft8_tx_loopback_test = parser.isSet (ft8_tx_loopback_test_option); receive_handoff_test = parser.isSet (receive_handoff_test_option); + jt4_wav_test = parser.isSet (jt4_wav_test_option); jt9_wav_test = parser.isSet (jt9_wav_test_option); jt65_wav_test = parser.isSet (jt65_wav_test_option); q65_wav_test = parser.isSet (q65_wav_test_option); @@ -501,6 +511,13 @@ int main(int argc, char *argv[]) "must be used together" << std::endl; return EXIT_FAILURE; } + if (jt4_wav_test != parser.isSet (jt4_wav_expected_option) + || (jt4_wav_test && parser.value (jt4_wav_expected_option).trimmed ().isEmpty ())) + { + std::cerr << "--jt4-wav-test and a nonempty --jt4-wav-expected must be used together" + << std::endl; + return EXIT_FAILURE; + } if (jt9_wav_test != parser.isSet (jt9_wav_expected_option) || (jt9_wav_test && parser.value (jt9_wav_expected_option).trimmed ().isEmpty ())) { @@ -540,7 +557,7 @@ int main(int argc, char *argv[]) + (jtty_live_audio_test ? 1 : 0) + (jtty_tx_loopback_test ? 1 : 0) + (ft8_tx_loopback_test ? 1 : 0) - + (receive_handoff_test ? 1 : 0) + (jt9_wav_test ? 1 : 0) + + (receive_handoff_test ? 1 : 0) + (jt4_wav_test ? 1 : 0) + (jt9_wav_test ? 1 : 0) + (jt65_wav_test ? 1 : 0) + (q65_wav_test ? 1 : 0) + (fst4_wav_test ? 1 : 0) + (fst4w_wav_test ? 1 : 0) > 1) { @@ -563,7 +580,7 @@ int main(int argc, char *argv[]) } automated_test = startup_smoke_test || live_audio_test || jtty_live_audio_test || jtty_tx_loopback_test || ft8_tx_loopback_test - || receive_handoff_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test; + || receive_handoff_test || jt4_wav_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test; #else automated_test = startup_smoke_test; #endif @@ -997,19 +1014,22 @@ int main(int argc, char *argv[]) controller->begin (); }); } - if (jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) + if (jt4_wav_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) { a.setQuitOnLastWindowClosed (false); wav_decode_controller.reset (new WavDecodeTestController { - &w, parser.value (jt9_wav_test ? jt9_wav_test_option + &w, parser.value (jt4_wav_test ? jt4_wav_test_option + : jt9_wav_test ? jt9_wav_test_option : jt65_wav_test ? jt65_wav_test_option : q65_wav_test ? q65_wav_test_option : fst4_wav_test ? fst4_wav_test_option : fst4w_wav_test_option), - parser.value (jt9_wav_test ? jt9_wav_expected_option + parser.value (jt4_wav_test ? jt4_wav_expected_option + : jt9_wav_test ? jt9_wav_expected_option : jt65_wav_test ? jt65_wav_expected_option : q65_wav_test ? q65_wav_expected_option : fst4_wav_test ? fst4_wav_expected_option : fst4w_wav_expected_option), - jt9_wav_test ? WavDecodeTestController::Mode::Jt9 + jt4_wav_test ? WavDecodeTestController::Mode::Jt4 + : jt9_wav_test ? WavDecodeTestController::Mode::Jt9 : jt65_wav_test ? WavDecodeTestController::Mode::Jt65 : q65_wav_test ? WavDecodeTestController::Mode::Q65 : fst4_wav_test ? WavDecodeTestController::Mode::Fst4 @@ -1100,7 +1120,7 @@ int main(int argc, char *argv[]) { result = EXIT_FAILURE; } - if ((jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) + if ((jt4_wav_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) && (!wav_decode_controller || !wav_decode_controller->succeeded ())) { result = EXIT_FAILURE; diff --git a/map65/commons.cpp b/map65/commons.cpp index 74c69b74..bbef8ed0 100644 --- a/map65/commons.cpp +++ b/map65/commons.cpp @@ -4,8 +4,5 @@ extern "C" { float* dd = nullptr; float* ss = nullptr; float* savg = nullptr; - float* dd_old = nullptr; - float* ss_old = nullptr; - float* savg_old = nullptr; } diff --git a/map65/commons.h b/map65/commons.h index 8938348e..b469b4a9 100644 --- a/map65/commons.h +++ b/map65/commons.h @@ -57,9 +57,6 @@ extern struct { //This is "common/datcom/..." in Fortran extern float* dd; extern float* ss; extern float* savg; - extern float* dd_old; - extern float* ss_old; - extern float* savg_old; extern int manualDecodeFlag ; double get_fcenter(); void get_mycall(char*); @@ -100,9 +97,7 @@ extern struct { //This is "common/datcom/..." in Fortran void set_dd_ptr(void* ptr, int dim1, int dim2); void set_ss_ptr(void* ptr, int dim1, int dim2, int dim3); void set_savg_ptr(void* ptr, int dim1, int dim2); - void set_dd_old_ptr(void* ptr, int dim1, int dim2); - void set_ss_old_ptr(void* ptr, int dim1, int dim2, int dim3); - void set_savg_old_ptr(void* ptr, int dim1, int dim2); + void set_snap_ptr(int idx, void* dd_ptr, void* ss_ptr, void* savg_ptr, int ndd, int nfft); void set_fcenter(double); void set_map65RxLog(int); void set_nutc(int); @@ -152,7 +147,7 @@ extern struct { //This is "common/datcom/..." in Fortran int buf_size, intptr_t event_handle); void set_manual_decode_flag(int); - void snapshot_buffers(); + void snapshot_buffers(int idx, int ksamp, int nhsym_snap); } extern QStringList allDecodes2; diff --git a/map65/libm65/CMakeLists.txt b/map65/libm65/CMakeLists.txt index 9ae45c54..3269c2c6 100644 --- a/map65/libm65/CMakeLists.txt +++ b/map65/libm65/CMakeLists.txt @@ -333,6 +333,11 @@ if (WSJT_ENABLE_TESTS) target_link_libraries (test_map65_symspec_contract PRIVATE m65impl) add_test (NAME test_map65_symspec_96 COMMAND test_map65_symspec_contract 96000) add_test (NAME test_map65_symspec_192 COMMAND test_map65_symspec_contract 192000) + add_executable (test_map65_pass_snapshots + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_pass_snapshots.f90) + target_include_directories (test_map65_pass_snapshots PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_pass_snapshots PRIVATE m65impl) + add_test (NAME test_map65_pass_snapshots COMMAND test_map65_pass_snapshots) add_executable (test_map65_q65_handoff ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_q65_handoff.f90) diff --git a/map65/libm65/datcom_ptrs_mod.f90 b/map65/libm65/datcom_ptrs_mod.f90 index a507168e..a4f94b37 100644 --- a/map65/libm65/datcom_ptrs_mod.f90 +++ b/map65/libm65/datcom_ptrs_mod.f90 @@ -1,14 +1,29 @@ module datcom_ptrs_mod use iso_c_binding + use debug_log, only: dbg, itoa + use npar_ptrs_mod, only: snapshot_fill_begin, snapshot_fill_end implicit none ! Fortran pointer targets real(c_float), pointer, contiguous :: dd(:,:) => null() ! [4, 5760000] real(c_float), pointer, contiguous :: ss(:,:,:) => null() ! [4, 322, NFFT] real(c_float), pointer, contiguous :: savg(:,:) => null() ! [4, NFFT] - real(c_float), pointer, contiguous :: dd_old(:,:) => null() ! [4, 5760000] - real(c_float), pointer, contiguous :: ss_old(:,:,:) => null() ! [4, 322, NFFT] - real(c_float), pointer, contiguous :: savg_old(:,:) => null() ! [4, NFFT] + + ! Two decoder snapshot sets, one per automatic pass (1 = early, nhsym1=280; + ! 2 = final, nhsym2=302). Each is filled by snapshot_buffers() at the moment + ! its pass is triggered, before the live buffers can be reset for the next + ! cycle, so a late-starting pass still decodes complete data. + type :: snap_set + real(c_float), pointer, contiguous :: dd(:,:) => null() ! [4, nsmax] + real(c_float), pointer, contiguous :: ss(:,:,:) => null() ! [4, 322, NFFT] + real(c_float), pointer, contiguous :: savg(:,:) => null() ! [4, NFFT] + end type snap_set + type(snap_set), save :: snap(2) + + ! Snapshot selected for the pass now being decoded (set by decode0) + real(c_float), pointer, contiguous :: dd_old(:,:) => null() + real(c_float), pointer, contiguous :: ss_old(:,:,:) => null() + real(c_float), pointer, contiguous :: savg_old(:,:) => null() ! Pointers used by decode0 / narrowband decoder real(c_float), pointer, contiguous :: dd_use(:,:) => null() @@ -21,10 +36,30 @@ module datcom_ptrs_mod contains - subroutine snapshot_buffers() bind(C) - dd_old(:,:) = dd(:,:) - ss_old(:,:,:) = ss(:,:,:) - savg_old(:,:) = savg(:,:) + ! Copy the live buffers into snapshot set idx (1 or 2). Called from dataSink() + ! on the GUI thread, which is also the thread that runs symspec, so ss and + ! savg cannot change during the copy. The sound-in thread writes dd only + ! forward of ksamp, so dd(:,1:ksamp+lookahead) is stable. + subroutine snapshot_buffers(idx, ksamp, nhsym_snap) bind(C, name="snapshot_buffers") + integer(c_int), value :: idx, ksamp, nhsym_snap + integer :: ncopy, ncol + logical :: ok + integer, parameter :: lookahead = 512 ! live_lookahead_samples in symspec + if (idx < 1 .or. idx > 2) return + call snapshot_fill_begin(idx, ok) + if (.not. ok) then + call dbg('snapshot ' // itoa(idx) // ' skipped: slot still in use by the running pass') + return + endif + if (.not. associated(snap(idx)%dd) .or. .not. associated(dd)) return + ncopy = max(0, min(size(dd,2), ksamp + lookahead)) + ncol = max(0, min(size(ss,2), nhsym_snap)) + snap(idx)%dd(:,1:ncopy) = dd(:,1:ncopy) + snap(idx)%dd(:,ncopy+1:) = 0. + snap(idx)%ss(:,1:ncol,:) = ss(:,1:ncol,:) + snap(idx)%ss(:,ncol+1:,:) = 0. + snap(idx)%savg(:,:) = savg(:,:) + call snapshot_fill_end(idx) end subroutine ! Helper subroutine to copy fixed-length Fortran string to C buffer @@ -67,31 +102,15 @@ contains print *, "Fortran: savg pointer associated with dimensions", dim1, dim2 end subroutine - subroutine set_dd_old_ptr(ptr, dim1, dim2) bind(C, name="set_dd_old_ptr") - use iso_c_binding - implicit none - type(c_ptr), value :: ptr - integer(c_int), value :: dim1, dim2 - call c_f_pointer(ptr, dd_old, [dim1, dim2]) - print *, "Fortran: dd_old pointer associated with dimensions", dim1, dim2 - end subroutine - - subroutine set_ss_old_ptr(ptr, dim1, dim2, dim3) bind(C, name="set_ss_old_ptr") + subroutine set_snap_ptr(idx, dd_ptr, ss_ptr, savg_ptr, ndd, nfft_s) bind(C, name="set_snap_ptr") use iso_c_binding implicit none - type(c_ptr), value :: ptr - integer(c_int), value :: dim1, dim2, dim3 - call c_f_pointer(ptr, ss_old, [dim1, dim2, dim3]) - print *, "Fortran: ss_old pointer associated with dimensions", dim1, dim2, dim3 - end subroutine - - subroutine set_savg_old_ptr(ptr, dim1, dim2) bind(C, name="set_savg_old_ptr") - use iso_c_binding - implicit none - type(c_ptr), value :: ptr - integer(c_int), value :: dim1, dim2 - call c_f_pointer(ptr, savg_old, [dim1, dim2]) - print *, "Fortran: savg_old pointer associated with dimensions", dim1, dim2 + integer(c_int), value :: idx, ndd, nfft_s + type(c_ptr), value :: dd_ptr, ss_ptr, savg_ptr + if (idx < 1 .or. idx > 2) return + call c_f_pointer(dd_ptr, snap(idx)%dd, [4, ndd]) + call c_f_pointer(ss_ptr, snap(idx)%ss, [4, 322, nfft_s]) + call c_f_pointer(savg_ptr, snap(idx)%savg, [4, nfft_s]) end subroutine function get_junk1() bind(C, name="get_junk1") diff --git a/map65/libm65/decode0.f90 b/map65/libm65/decode0.f90 index cdb8799b..1e217501 100644 --- a/map65/libm65/decode0.f90 +++ b/map65/libm65/decode0.f90 @@ -7,7 +7,7 @@ contains use iso_c_binding, only: c_int use timer_module, only: timer use npar_ptrs_mod - use datcom_ptrs_mod, only: NFFT, dd, dd_old, dd_use, ss, ss_old, savg, savg_old, ss_use, savg_use + use datcom_ptrs_mod, only: NFFT, dd_old, dd_use, ss_old, savg_old, ss_use, savg_use, snap use debug_log, only: dbg, itoa, rtoa use sec_midn_mod, only: sec_midn use map65a_mod @@ -25,6 +25,7 @@ contains integer nz integer :: nhsym0 integer :: newdat0 + integer :: isnap character(len=128) :: line character mycall0*12, hiscall0*12, hisgrid0*6 logical :: first_mcall3b_check @@ -47,25 +48,29 @@ contains ! newdat is forced to 1 by decode() for every call (manual or ! automatic); it does not by itself mean "the live buffers just - ! finished a fresh accumulation." nagain=1 marks a manual repeat - ! (Decode button / Find Delta Phi), which must not refresh dd_old - ! from a live buffer that may still be mid-fill. - if (newdat0 /= 0 .and. manualDecodeFlag == 0 .and. nagain == 0) then - dd_old = dd - ss_old = ss - savg_old = savg - call dbg('decode0: dd_old REFRESHED from live dd at t=' // rtoa(sec_midn()) // ' nhsym0=' // itoa(nhsym0)) - else - call dbg('decode0: dd_old NOT refreshed (reusing prior snapshot) at t=' // rtoa(sec_midn()) // & - ' nhsym0=' // itoa(nhsym0) // ' nagain=' // itoa(nagain)) - endif + ! finished a fresh accumulation." + ! + ! Each automatic pass decodes its own snapshot, taken by dataSink() at + ! the instant the pass was triggered (snap(1) at nhsym1, snap(2) at + ! nhsym2). decode0 never copies from the live buffers, so a pass that + ! starts late (queued behind a still-running pass) cannot see data the + ! audio thread has already reset for the next cycle. Manual repeats + ! (nagain=1, Decode button / Find Delta Phi) reuse the most recently + ! filled snapshot. + isnap = active_snap_idx ! slot claimed with this request + if (isnap < 1) isnap = 2 + call dbg('decode0: using snapshot ' // itoa(isnap) // ' at t=' // rtoa(sec_midn()) // & + ' nhsym0=' // itoa(nhsym0) // ' nagain=' // itoa(nagain)) + dd_old => snap(isnap)%dd + ss_old => snap(isnap)%ss + savg_old => snap(isnap)%savg nkeep = min(max(ntimeout, 10), 40) call sec0(0, tquick) call timer('decode0 ', 0) - ! Always decode from the snapshot (dd_old/ss_old/savg_old) taken above, + ! Always decode from the snapshot selected above (dd_old/ss_old/savg_old), ! never the live dd/ss/savg. The nhsym2 pass routinely runs past the ! minute boundary (several seconds), and symspec_() on the GUI thread ! resets/overwrites the live buffers for the next cycle unconditionally diff --git a/map65/libm65/npar_ptrs_mod.f90 b/map65/libm65/npar_ptrs_mod.f90 index 10c9b904..99bde665 100644 --- a/map65/libm65/npar_ptrs_mod.f90 +++ b/map65/libm65/npar_ptrs_mod.f90 @@ -60,9 +60,13 @@ module npar_ptrs_mod ! newdat = 1 in that copy) and clears ! draft%manualDecodeFlag ! claim_decode_request() copies the oldest request into active; an - ! automatic live request whose input generation - ! is out of date is marked expired, and run_m65 - ! skips it () + ! automatic request is marked expired, and run_m65 + ! skips it (), when the data + ! snapshot it was published with has been + ! overwritten or never filled (or, for requests + ! without a snapshot, when its input generation + ! is out of date). A request whose snapshot is + ! intact still runs after the minute rolls over. ! initialize_decode_parameters() copies draft into active once, at startup ! The decoder then sees a consistent snapshot for the whole pass, even if ! the GUI changes draft meanwhile. @@ -96,6 +100,8 @@ module npar_ptrs_mod type(decode_parameters) :: parameters integer(c_int64_t) :: id integer(c_int64_t) :: input_generation + integer(c_int) :: snap_idx = 0 ! snapshot slot (1 = nhsym1, 2 = nhsym2); 0 = none + integer(c_int64_t) :: snap_seq = 0 ! fill number of that slot when published type(decode_request), pointer :: next => null() end type type(decode_request), pointer, save :: pending_head => null(), pending_tail => null() @@ -105,6 +111,19 @@ module npar_ptrs_mod integer(c_int64_t), save :: active_input_generation = 0 logical, save :: active_request_expired = .false. + ! Decoder data snapshots (see datcom_ptrs_mod). All of this state is + ! protected by lock_decode_requests(). + ! snap_seq(i) fill number, bumped each time slot i is (re)filled + ! snap_valid_seq(i) fill number whose contents are intact; 0 while a fill + ! is in progress or after a fill was skipped + ! snap_busy(i) slot i is being read by the running decode pass; a fill + ! is skipped rather than overwrite it + integer(c_int64_t), save :: snap_seq(2) = 0 + integer(c_int64_t), save :: snap_valid_seq(2) = 0 + logical, save :: snap_busy(2) = .false. + integer(c_int), save :: snap_latest_idx = 0 ! most recently completed fill + integer(c_int), save :: active_snap_idx = 0 ! slot read by the active pass + real(c_double), pointer :: fcenter => active%fcenter real(c_double), pointer :: ftol_nb => active%ftol_nb integer(c_int), pointer :: nfa => active%nfa @@ -781,6 +800,16 @@ end subroutine request%input_generation = live_input_generation request%parameters = draft request%parameters%newdat = 1 + ! Automatic passes (nhsym1/nhsym2) were just snapshotted by dataSink(); + ! remember which slot and fill they own. Manual repeats use the latest. + if (draft%manualDecodeFlag == 0 .and. draft%nagain == 0 .and. & + (draft%nhsym == 280 .or. draft%nhsym == 302)) then + request%snap_idx = merge(1, 2, draft%nhsym == 280) + request%snap_seq = snap_seq(request%snap_idx) + ! No fill has ever happened for this slot (no snapshot support in the + ! caller): fall back to the input-generation rule. + if (request%snap_seq == 0) request%snap_idx = 0 + endif if (associated(pending_tail)) then pending_tail%next => request else @@ -804,8 +833,26 @@ end subroutine active = request%parameters active_request_id = request%id active_input_generation = request%input_generation - active_request_expired = active%ndiskdat == 0 .and. active%nagain == 0 .and. & - active%manualDecodeFlag == 0 .and. request%input_generation /= live_input_generation + active_snap_idx = 0 + if (request%snap_idx > 0) then + ! Automatic pass: valid while its snapshot is intact, even if the + ! minute has rolled over. A live request more than one generation old + ! (monitoring stopped, period changed) is still dropped. + active_request_expired = snap_valid_seq(request%snap_idx) /= request%snap_seq + if (active%ndiskdat == 0 .and. & + live_input_generation - request%input_generation >= 2) active_request_expired = .true. + if (.not. active_request_expired) then + active_snap_idx = request%snap_idx + snap_busy(active_snap_idx) = .true. + endif + else + active_request_expired = active%ndiskdat == 0 .and. active%nagain == 0 .and. & + active%manualDecodeFlag == 0 .and. request%input_generation /= live_input_generation + if (.not. active_request_expired .and. snap_latest_idx > 0) then + active_snap_idx = snap_latest_idx ! manual repeat: latest snapshot + snap_busy(active_snap_idx) = .true. + endif + endif deallocate(request) endif call unlock_decode_requests() @@ -817,6 +864,34 @@ end subroutine call unlock_decode_requests() end subroutine + ! A snapshot fill starts: invalidate the slot's contents and say whether the + ! copy may proceed (ok = .false. when the running pass is still reading it). + subroutine snapshot_fill_begin(idx, ok) + integer, intent(in) :: idx + logical, intent(out) :: ok + call lock_decode_requests() + snap_seq(idx) = snap_seq(idx) + 1 + snap_valid_seq(idx) = 0 + ok = .not. snap_busy(idx) + call unlock_decode_requests() + end subroutine + + subroutine snapshot_fill_end(idx) + integer, intent(in) :: idx + call lock_decode_requests() + snap_valid_seq(idx) = snap_seq(idx) + snap_latest_idx = idx + call unlock_decode_requests() + end subroutine + + ! The active pass is finished with its snapshot slot. + subroutine snapshot_release() + call lock_decode_requests() + if (active_snap_idx > 0) snap_busy(active_snap_idx) = .false. + active_snap_idx = 0 + call unlock_decode_requests() + end subroutine + subroutine advance_live_input_generation() bind(C) call lock_decode_requests() live_input_generation = live_input_generation + 1 diff --git a/map65/libm65/run_m65.f90 b/map65/libm65/run_m65.f90 index cc0ffe73..14042016 100644 --- a/map65/libm65/run_m65.f90 +++ b/map65/libm65/run_m65.f90 @@ -9,7 +9,7 @@ subroutine run_m65(pol, sample_rate_96000) bind(C, name='run_m65_') use timer_impl, only: init_timer, fini_timer use debug_log use m65a_mod - use npar_ptrs_mod, only: t_start, nhsym, mycall, hiscall, hisgrid, neme, & + use npar_ptrs_mod, only: snapshot_release, t_start, nhsym, mycall, hiscall, hisgrid, neme, & initialize_decode_parameters, claim_decode_request, get_stop_m65, & active_request_id, active_request_expired use stdout_channel_mod, only: write_stdout @@ -88,6 +88,7 @@ subroutine run_m65(pol, sample_rate_96000) bind(C, name='run_m65_') call system_clock(t_start, t_rate) call m65a() call system_clock(t_now) + call snapshot_release() call dbg('run_m65: request completed, elapsed=' // rtoa(real(t_now - t_start)/real(t_rate))) endif endif diff --git a/map65/mainwindow.cpp b/map65/mainwindow.cpp index e9a0e6d6..5e88572e 100644 --- a/map65/mainwindow.cpp +++ b/map65/mainwindow.cpp @@ -157,12 +157,14 @@ MainWindow::MainWindow(QWidget *parent) : std::cout << "ss pointer set to: " << ss << std::endl; set_savg_ptr(savg, 4, active_nfft); std::cout << "savg pointer set to: " << savg << std::endl; - dd_old = new float[ddSize]; - set_dd_old_ptr(dd_old, channels, pairsWorst); - ss_old = new float[4 * 322 * active_nfft]; - savg_old = new float[4 * active_nfft]; - set_ss_old_ptr(ss_old, 4, 322, active_nfft); - set_savg_old_ptr(savg_old, 4, active_nfft); + // Two snapshot sets, one per automatic decode pass (1 = nhsym 280, 2 = nhsym 302). + // They are filled in dataSink() at each trigger; see snapshot_buffers(). + for (int idx = 1; idx <= 2; idx++) { + float* sdd = new float[ddSize](); + float* sss = new float[4 * 322 * active_nfft](); + float* ssavg = new float[4 * active_nfft](); + set_snap_ptr(idx, sdd, sss, ssavg, pairsWorst, active_nfft); + } qDebug() << "MAINWINDOW created dd ss savg "; @@ -1302,6 +1304,7 @@ void MainWindow::dataSink(int k) setNewdat(1); setNagain(0); setNhsym(280); + snapshot_buffers(1, k, 280); //Freeze this pass's data now QDateTime t = QDateTime::currentDateTimeUtc(); m_dateTime=t.toString("yyyy-MMM-dd hh:mm"); decode(); //Start the decoder @@ -1314,6 +1317,7 @@ void MainWindow::dataSink(int k) setNewdat(1); setNagain(0); setNhsym(302); + snapshot_buffers(2, k, 302); //Freeze this pass's data now QDateTime t = QDateTime::currentDateTimeUtc(); m_dateTime=t.toString("yyyy-MMM-dd hh:mm"); decode(); //Start the decoder diff --git a/release-state.txt b/release-state.txt index 327836e0..5519575d 100644 --- a/release-state.txt +++ b/release-state.txt @@ -1,5 +1,5 @@ version=3.3.0 channel=BETA -prerelease=1 -revision=57ba9337fa020065dc0ceee2c4ef85e433ea32d4 +prerelease=2 +revision=9d059511f77e2d1be746ebfeaa7f88e77c1babb7 windows_signing=unsigned diff --git a/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt b/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt index 5add3711..97837102 100644 --- a/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt +++ b/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt @@ -1,2 +1,2 @@ -**** -14 1.8 1199 $# G3WDG OK1KIR RRR f +1757 -14 1.8 1199 $# G3WDG OK1KIR RRR f 0 1 0 diff --git a/tests/integration/decoder_engine/run_wav_gui.cmake b/tests/integration/decoder_engine/run_wav_gui.cmake index 88979815..a4204886 100644 --- a/tests/integration/decoder_engine/run_wav_gui.cmake +++ b/tests/integration/decoder_engine/run_wav_gui.cmake @@ -1,9 +1,10 @@ if (NOT DEFINED MODE) set (MODE JT9) endif () -if (NOT MODE STREQUAL "JT9" AND NOT MODE STREQUAL "JT65" AND NOT MODE STREQUAL "Q65" +if (NOT MODE STREQUAL "JT4" AND NOT MODE STREQUAL "JT9" AND NOT MODE STREQUAL "JT65" + AND NOT MODE STREQUAL "Q65" AND NOT MODE STREQUAL "FST4" AND NOT MODE STREQUAL "FST4W") - message (FATAL_ERROR "MODE must be JT9, JT65, Q65, FST4, or FST4W") + message (FATAL_ERROR "MODE must be JT4, JT9, JT65, Q65, FST4, or FST4W") endif () string (TOLOWER "${MODE}" mode_option) diff --git a/tests/integration/jt9/verify_jt4_12000_read_extent.cmake b/tests/integration/jt9/verify_jt4_12000_read_extent.cmake index 7011cc39..64f6fa33 100644 --- a/tests/integration/jt9/verify_jt4_12000_read_extent.cmake +++ b/tests/integration/jt9/verify_jt4_12000_read_extent.cmake @@ -1,22 +1,32 @@ -foreach (required_variable JT9 JT4SIM WORK_DIR) +foreach (required_variable JT9 WORK_DIR) if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") message (FATAL_ERROR "${required_variable} is required") endif () endforeach () file (MAKE_DIRECTORY "${WORK_DIR}") -execute_process ( - COMMAND "${JT4SIM}" "G3WDG OK1KIR RRR" F 1 0 0 1 99 - WORKING_DIRECTORY "${WORK_DIR}" - RESULT_VARIABLE simulator_result - OUTPUT_QUIET - ERROR_VARIABLE simulator_stderr) -if (NOT "${simulator_result}" STREQUAL "0") - message (FATAL_ERROR - "jt4sim exited with ${simulator_result}\n${simulator_stderr}") +if (DEFINED JT4_WAV AND NOT "${JT4_WAV}" STREQUAL "") + set (full_wav "${JT4_WAV}") + set (submode A) + set (expected_message "K1ABC W9XYZ FN42") +else () + if (NOT DEFINED JT4SIM OR "${JT4SIM}" STREQUAL "") + message (FATAL_ERROR "JT4_WAV or JT4SIM is required") + endif () + execute_process ( + COMMAND "${JT4SIM}" "G3WDG OK1KIR RRR" F 1 0 0 1 99 + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE simulator_result + OUTPUT_QUIET + ERROR_VARIABLE simulator_stderr) + if (NOT "${simulator_result}" STREQUAL "0") + message (FATAL_ERROR + "jt4sim exited with ${simulator_result}\n${simulator_stderr}") + endif () + set (full_wav "${WORK_DIR}/000000_0001.wav") + set (submode F) + set (expected_message "G3WDG OK1KIR RRR") endif () - -set (full_wav "${WORK_DIR}/000000_0001.wav") set (truncated_wav "${WORK_DIR}/000000_0001_truncated.wav") # Keep enough samples to distinguish a complete JT4 read from premature termination. set (truncate_script [=[ @@ -47,7 +57,7 @@ execute_process ( COMMAND "${JT9}" -a "${WORK_DIR}" -t "${WORK_DIR}" - --jt4 -b F -f 1000 -d 3 + --jt4 -b "${submode}" -f 1000 -d 3 "${truncated_wav}" WORKING_DIRECTORY "${WORK_DIR}" RESULT_VARIABLE decoder_result @@ -59,6 +69,9 @@ if (NOT "${decoder_result}" STREQUAL "0") "stdout:\n${decoder_stdout}\n" "stderr:\n${decoder_stderr}") endif () +if (NOT "${decoder_stdout}" MATCHES "${expected_message}") + message (FATAL_ERROR "Truncated JT4 recording did not decode:\n${decoder_stdout}") +endif () if (NOT "${decoder_stdout}" MATCHES "EOF on input file") message (FATAL_ERROR "jt9 did not read beyond the obsolete 570240-sample cutoff\n" diff --git a/tests/integration/jt9/verify_jt4_engine.cmake b/tests/integration/jt9/verify_jt4_engine.cmake new file mode 100644 index 00000000..45f5226c --- /dev/null +++ b/tests/integration/jt9/verify_jt4_engine.cmake @@ -0,0 +1,19 @@ +if (NOT DEFINED JT9_EXECUTABLE OR NOT DEFINED JT4_WAV OR NOT DEFINED TEST_DIRECTORY) + message (FATAL_ERROR "JT4 engine test requires JT9_EXECUTABLE, JT4_WAV and TEST_DIRECTORY") +endif () +file (MAKE_DIRECTORY "${TEST_DIRECTORY}") +execute_process (COMMAND "${JT9_EXECUTABLE}" --jt4 -b A -f 1000 -d 1 + -a "${TEST_DIRECTORY}" -t "${TEST_DIRECTORY}" "${JT4_WAV}" + WORKING_DIRECTORY "${TEST_DIRECTORY}" + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error TIMEOUT 60) +if (NOT status EQUAL 0) + message (FATAL_ERROR "JT4 CLI failed (${status}): ${error}\n${output}") +endif () +if (NOT output MATCHES "K1ABC W9XYZ FN42") + message (FATAL_ERROR "JT4 CLI did not decode the generated recording:\n${output}\n${error}") +endif () +string (REGEX MATCHALL "K1ABC W9XYZ FN42" messages "${output}") +list (LENGTH messages count) +if (NOT count EQUAL 1 OR NOT output MATCHES "[^\n]*[ ]1[ ]+0") + message (FATAL_ERROR "JT4 CLI produced unexpected messages/completion:\n${output}") +endif () diff --git a/tests/unit/decoder_engine/CMakeLists.txt b/tests/unit/decoder_engine/CMakeLists.txt index c2546109..82965b4b 100644 --- a/tests/unit/decoder_engine/CMakeLists.txt +++ b/tests/unit/decoder_engine/CMakeLists.txt @@ -10,6 +10,9 @@ target_include_directories (test_decoder_engine PRIVATE ${CMAKE_SOURCE_DIR}) target_link_libraries (test_decoder_engine PRIVATE test_decoder_engine_signal) add_test (NAME test_decoder_engine COMMAND test_decoder_engine) set_tests_properties (test_decoder_engine PROPERTIES TIMEOUT 90) +add_test (NAME prepare_ft8_engine_wav COMMAND test_decoder_engine + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/ft8-engine.wav) +set_tests_properties (prepare_ft8_engine_wav PROPERTIES FIXTURES_SETUP ft8_engine_wav TIMEOUT 15) add_executable (test_decoder_engine_ft4 test_decoder_engine_ft4.c) set_target_properties (test_decoder_engine_ft4 PROPERTIES LINKER_LANGUAGE CXX) @@ -220,3 +223,56 @@ if (TARGET wsjt_fort_omp) set_tests_properties (test_decoder_engine_fst4_omp PROPERTIES TIMEOUT 360 PROCESSORS 2 ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2;OMP_STACKSIZE=1M") endif () + +add_library (test_decoder_engine_jt4_signal STATIC jt4_engine_signal.f90) +wsjt_link_common_fortran (test_decoder_engine_jt4_signal) +add_executable (test_decoder_engine_jt4 test_decoder_engine_jt4.c) +set_target_properties (test_decoder_engine_jt4 PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine_jt4 PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decoder_engine_jt4 PRIVATE test_decoder_engine_jt4_signal Threads::Threads) +add_test (NAME test_decoder_engine_jt4 COMMAND test_decoder_engine_jt4 --small-stack) +set_tests_properties (test_decoder_engine_jt4 PROPERTIES TIMEOUT 180 + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +add_executable (test_decoder_engine_jt4_state test_decoder_engine_jt4_state.f90) +set_target_properties (test_decoder_engine_jt4_state PROPERTIES LINKER_LANGUAGE CXX) +wsjt_link_common_fortran (test_decoder_engine_jt4_state) +add_test (NAME test_decoder_engine_jt4_state COMMAND test_decoder_engine_jt4_state) +set_tests_properties (test_decoder_engine_jt4_state PROPERTIES TIMEOUT 30) +add_test (NAME prepare_jt4_engine_wav COMMAND test_decoder_engine_jt4 + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/jt4-engine.wav) +set_tests_properties (prepare_jt4_engine_wav PROPERTIES FIXTURES_SETUP jt4_engine_wav TIMEOUT 15) +if (TARGET wsjt_fort_omp AND TARGET wsjt_fort) + add_library (test_decoder_engine_jt4_signal_omp STATIC jt4_engine_signal.f90) + target_link_libraries (test_decoder_engine_jt4_signal_omp PUBLIC wsjt_fort_omp wsjt_fortran_openmp) + add_executable (test_decoder_engine_jt4_omp test_decoder_engine_jt4.c) + set_target_properties (test_decoder_engine_jt4_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_jt4_omp PRIVATE ${CMAKE_SOURCE_DIR}) + target_link_libraries (test_decoder_engine_jt4_omp PRIVATE test_decoder_engine_jt4_signal_omp Threads::Threads) + add_test (NAME test_decoder_engine_jt4_omp COMMAND test_decoder_engine_jt4_omp --smoke) + set_tests_properties (test_decoder_engine_jt4_omp PROPERTIES TIMEOUT 90 + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +endif () + +add_test (NAME test_jt4_engine_cli COMMAND ${CMAKE_COMMAND} + "-DJT9_EXECUTABLE=$" + "-DJT4_WAV=${CMAKE_CURRENT_BINARY_DIR}/jt4-engine.wav" + "-DTEST_DIRECTORY=${CMAKE_CURRENT_BINARY_DIR}/jt4-cli" + -P ${CMAKE_SOURCE_DIR}/tests/integration/jt9/verify_jt4_engine.cmake) +set_tests_properties (test_jt4_engine_cli PROPERTIES FIXTURES_REQUIRED jt4_engine_wav TIMEOUT 60) + +add_executable (test_decoder_engine_jt4_host test_decoder_engine_jt4_host.f90) +set_target_properties (test_decoder_engine_jt4_host PROPERTIES LINKER_LANGUAGE CXX) +target_link_libraries (test_decoder_engine_jt4_host PRIVATE test_decoder_engine_jt4_signal) +wsjt_link_common_fortran (test_decoder_engine_jt4_host) +file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt4-host) +add_test (NAME test_decoder_engine_jt4_host COMMAND test_decoder_engine_jt4_host) +set_tests_properties (test_decoder_engine_jt4_host PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt4-host TIMEOUT 90) + +add_test (NAME test_jt4_12000_read_extent COMMAND ${CMAKE_COMMAND} + "-DJT9=$" + "-DJT4_WAV=${CMAKE_CURRENT_BINARY_DIR}/jt4-engine.wav" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/jt4-read-extent" + -P ${CMAKE_SOURCE_DIR}/tests/integration/jt9/verify_jt4_12000_read_extent.cmake) +set_tests_properties (test_jt4_12000_read_extent PROPERTIES + FIXTURES_REQUIRED jt4_engine_wav LABELS "decoder;jt4;integration" TIMEOUT 60) diff --git a/tests/unit/decoder_engine/jt4_engine_signal.f90 b/tests/unit/decoder_engine/jt4_engine_signal.f90 new file mode 100644 index 00000000..0599b7d5 --- /dev/null +++ b/tests/unit/decoder_engine/jt4_engine_signal.f90 @@ -0,0 +1,47 @@ +subroutine decoder_engine_test_jt4_signal(rate,submode,seed,amplitude,noise,frequency,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t,c_float + implicit none + integer(c_int), value :: rate,submode,seed + real(c_float), value :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(60*rate) + call jt4_engine_make_signal('K1ABC W9XYZ FN42',rate,submode,seed,amplitude,noise,frequency,samples) +end subroutine + +subroutine jt4_engine_make_signal(message,rate,submode,seed,amplitude,noise,frequency,samples) + use iso_c_binding, only: c_int,c_int16_t,c_float + use iso_fortran_env, only: int64,real64 + use jt4, only: nch + implicit none + character(len=*), intent(in) :: message + integer(c_int), intent(in) :: rate,submode,seed + real(c_float), intent(in) :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(60*rate) + real(real64), parameter :: twopi=6.283185307179586476925286766559_real64 + integer(int64) :: state + integer :: tones(206),i,symbol,itype + real(real64) :: phase,value,u1,u2,freq + character(len=22) :: encoded,sent + + if(submode<0.or.submode>6) error stop 'invalid JT4 fixture submode' + if(rate/=11025.and.rate/=12000) error stop 'invalid JT4 fixture sample rate' + encoded=message + call gen4(encoded,0,sent,tones,itype) + state=104729_int64+int(seed,int64) + phase=0.0_real64 + do i=1,size(samples) + state=modulo(16807_int64*state,2147483647_int64) + u1=max(real(state,real64)/2147483647.0_real64,tiny(1.0_real64)) + state=modulo(16807_int64*state,2147483647_int64) + u2=real(state,real64)/2147483647.0_real64 + value=noise*sqrt(-2.0_real64*log(u1))*cos(twopi*u2) + if(i>rate) then + symbol=int(real(i-rate-1,real64)*4.375_real64/rate)+1 + if(symbol<=206) then + freq=frequency+tones(symbol)*4.375_real64*nch(submode+1) + phase=modulo(phase+twopi*freq/rate,twopi) + value=value+amplitude*sin(phase) + endif + endif + samples(i)=int(nint(max(-32768.0_real64,min(32767.0_real64,value))),c_int16_t) + enddo +end subroutine diff --git a/tests/unit/decoder_engine/test_decoder_engine.c b/tests/unit/decoder_engine/test_decoder_engine.c index 218688b3..71d9e3be 100644 --- a/tests/unit/decoder_engine/test_decoder_engine.c +++ b/tests/unit/decoder_engine/test_decoder_engine.c @@ -270,8 +270,44 @@ static void check_mtd_lifecycle(callback_context *context, decoder_attempt_reque free(saved); } -int main(void) +static void write_le(FILE *file, uint32_t value, unsigned bytes) { + for (unsigned i = 0; i < bytes; ++i) CHECK(fputc((value >> (8 * i)) & 255, file) != EOF); +} + +static void write_wav(const char *path) +{ + const int count = 180000; + int16_t *samples = malloc(count * sizeof *samples); + int8_t payload[77], tones[79]; + CHECK(samples); + decoder_engine_test_signal(samples, payload, tones, 6000); + FILE *file = fopen(path, "wb"); + CHECK(file); + CHECK(fwrite("RIFF", 1, 4, file) == 4); + write_le(file, 36 + count * 2, 4); + CHECK(fwrite("WAVEfmt ", 1, 8, file) == 8); + write_le(file, 16, 4); + write_le(file, 1, 2); + write_le(file, 1, 2); + write_le(file, 12000, 4); + write_le(file, 24000, 4); + write_le(file, 2, 2); + write_le(file, 16, 2); + CHECK(fwrite("data", 1, 4, file) == 4); + write_le(file, count * 2, 4); + for (int i = 0; i < count; ++i) write_le(file, (uint16_t)samples[i], 2); + CHECK(fclose(file) == 0); + free(samples); +} + +int main(int argc, char **argv) +{ + if (argc == 3 && !strcmp(argv[1], "--write-wav")) { + write_wav(argv[2]); + return 0; + } + CHECK(argc == 1); decoder_engine_options options = {DECODER_ENGINE_ABI}; decoder_engine_handle engine = NULL, second = NULL; decoder_engine_capabilities capabilities; @@ -293,7 +329,7 @@ int main(void) CHECK(decoder_engine_create(&options, &second) == DECODER_BUSY); CHECK(decoder_engine_get_capabilities(engine, &capabilities) == DECODER_OK); CHECK(capabilities.abi_version == DECODER_ENGINE_ABI); - CHECK(capabilities.supported_modes == (DECODER_SUPPORT_FT8 | DECODER_SUPPORT_FT4 | DECODER_SUPPORT_JT9 | DECODER_SUPPORT_JT65 | DECODER_SUPPORT_Q65 | DECODER_SUPPORT_FST4 | DECODER_SUPPORT_FST4W)); + CHECK(capabilities.supported_modes == (DECODER_SUPPORT_FT8 | DECODER_SUPPORT_FT4 | DECODER_SUPPORT_JT9 | DECODER_SUPPORT_JT65 | DECODER_SUPPORT_Q65 | DECODER_SUPPORT_FST4 | DECODER_SUPPORT_FST4W | DECODER_SUPPORT_JT4)); CHECK(capabilities.cancellation == 0); CHECK(capabilities.concurrent_sessions == 0); CHECK(capabilities.evidence_capacity == 1024); diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt4.c b/tests/unit/decoder_engine/test_decoder_engine_jt4.c new file mode 100644 index 00000000..3b1d9e7d --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt4.c @@ -0,0 +1,470 @@ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#include "DecoderEngine.h" +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#ifdef __linux__ +#include +#endif + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +enum { SAMPLE_CAPACITY = 60 * 12000 }; +extern void decoder_engine_test_jt4_signal(int, int, int, float, float, float, int16_t *); + +typedef struct { + decoder_engine_handle engine; + decoder_attempt_request request; + decoder_audio_view audio; + int16_t *samples, *before; + int observations, messages, method, average_count, kind; + float sync; +} fixture; + +static void observe(const decoder_observation *record, void *opaque) +{ + fixture *f = opaque; + CHECK(record->input_id == f->request.input_id); + CHECK(record->analysis_id == f->request.analysis_id); + CHECK(record->attempt_no == f->request.attempt_no); + CHECK(record->mode == DECODER_MODE_JT4); + CHECK(record->variant == f->request.jt4.submode); + CHECK(isfinite(record->sync) && isfinite(record->frequency_hz)); + CHECK(isfinite(record->dt_seconds) && isfinite(record->quality)); + CHECK(record->ap_type == 0); + CHECK(record->ft8.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->jt4.kind >= DECODER_JT4_NO_SYNC && record->jt4.kind <= DECODER_JT4_MESSAGE); + ++f->observations; + f->kind = record->jt4.kind; + f->sync = record->sync; + if (record->jt4.kind == DECODER_JT4_MESSAGE) { + CHECK(!strcmp(record->message, "K1ABC W9XYZ FN42")); + CHECK(record->jt4.method == DECODER_JT4_METHOD_FANO || + record->jt4.method == DECODER_JT4_METHOD_DEEP_SEARCH); + CHECK(record->jt4.average_count >= 0 && record->jt4.average_count <= 64); + CHECK(record->jt4.width_profile >= 0 && record->jt4.width_profile <= f->request.jt4.submode); + CHECK(record->jt4.sync_polarity == 1); + CHECK(fabsf(record->frequency_hz - 1000) < 10); + CHECK(fabsf(record->dt_seconds) < 0.4f); + ++f->messages; + f->method = record->jt4.method; + f->average_count = record->jt4.average_count; + } else { + CHECK(!record->message[0]); + CHECK(record->jt4.method == DECODER_JT4_METHOD_NONE); + } + CHECK(decoder_engine_release_input(f->engine, record->input_id) == DECODER_BUSY); + CHECK(decoder_engine_clear_jt4_averages(f->engine) == DECODER_BUSY); + CHECK(decoder_engine_set_jt4_calls(f->engine, NULL, 0) == DECODER_BUSY); +} + +static void create(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + decoder_engine_capabilities capabilities; + f->samples = malloc(SAMPLE_CAPACITY * sizeof *f->samples); + f->before = malloc(SAMPLE_CAPACITY * sizeof *f->before); + CHECK(f->samples && f->before); + f->audio.samples = f->samples; + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + CHECK(decoder_engine_get_capabilities(f->engine, &capabilities) == DECODER_OK); + CHECK(capabilities.supported_modes & DECODER_SUPPORT_JT4); +} + +static void prepare(fixture *f, int rate, int submode, int utc) +{ + static int64_t next_id = 100; + memset(&f->request, 0, sizeof f->request); + f->request.input_id = ++next_id; + f->request.analysis_id = next_id; + f->request.attempt_no = 1; + f->request.mode = DECODER_MODE_JT4; + f->request.phase = DECODER_PHASE_NORMAL; + f->request.source = DECODER_SOURCE_FILE; + f->request.jt4.utc = utc; + f->request.jt4.submode = submode; + f->request.jt4.receive_frequency_hz = 1000; + f->request.jt4.tolerance_hz = 50; + f->request.jt4.depth = 1; + memset(f->request.jt4.mycall, ' ', sizeof f->request.jt4.mycall); + memset(f->request.jt4.hiscall, ' ', sizeof f->request.jt4.hiscall); + memset(f->request.jt4.hisgrid, ' ', sizeof f->request.jt4.hisgrid); + f->audio.sample_count = 60 * rate; + f->audio.sample_rate_hz = rate; + decoder_engine_test_jt4_signal(rate, submode, utc + 1, 300, 100, 1000, f->samples); +} + +static void decode(fixture *f, int expected) +{ + decoder_attempt_outcome outcome; + decoder_attempt_request before_request = f->request; + size_t bytes = f->audio.sample_count * sizeof *f->samples; + memcpy(f->before, f->samples, bytes); + f->observations = f->messages = f->average_count = 0; + f->method = DECODER_JT4_METHOD_NONE; + f->kind = -1; + f->sync = NAN; + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_OK); + CHECK(outcome.status == DECODER_OK && outcome.observation_count == f->observations); + CHECK(outcome.evidence_dropped == 0); + CHECK(!memcmp(&before_request, &f->request, sizeof before_request)); + CHECK(!memcmp(f->before, f->samples, bytes)); + if (expected >= 0) { + if (!!f->messages != !!expected) + fprintf(stderr, "JT4%c %d Hz UTC %06d: got %d messages, expected %d\n", + 'A' + f->request.jt4.submode, f->audio.sample_rate_hz, + f->request.jt4.utc, f->messages, expected); + CHECK(!!f->messages == !!expected); + } +} + +static void release(fixture *f) +{ + CHECK(decoder_engine_release_input(f->engine, f->request.input_id) == DECODER_OK); +} + +static void repeat(fixture *f) +{ + f->request.phase = DECODER_PHASE_REPEAT; + ++f->request.analysis_id; + ++f->request.attempt_no; +} + +static void destroy(fixture *f) +{ + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + free(f->before); + free(f->samples); +} + +static void invalid(fixture *f) +{ + decoder_attempt_outcome outcome; + f->observations = 0; + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_INVALID); + CHECK(f->observations == 0); +} + +static void lifecycle(fixture *f) +{ + prepare(f, 11025, 0, 120000); + decode(f, 1); + CHECK(f->method == DECODER_JT4_METHOD_FANO && !f->average_count); + repeat(f); + --f->audio.sample_count; + invalid(f); + ++f->audio.sample_count; + f->audio.sample_rate_hz = 12000; + invalid(f); + f->audio.sample_rate_hz = 11025; + f->request.jt4.receive_frequency_hz = 1500; + decode(f, 0); + repeat(f); + f->request.jt4.receive_frequency_hz = 1000; + decode(f, 1); + release(f); + + prepare(f, 12000, 0, 120100); + decode(f, 1); + release(f); + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120200); + f->audio.sample_count = 1; + f->samples[0] = 0; + decode(f, 0); + CHECK(f->observations == 1); + release(f); + prepare(f, 11025, 0, 120300); + decode(f, 1); + release(f); + prepare(f, 11025, 0, 120400); + memset(f->samples, 0, f->audio.sample_count * sizeof *f->samples); + decode(f, 0); + CHECK(f->observations == 1); + release(f); +} + +static void averages(fixture *f, int expected) +{ + decoder_jt4_average_entry entries[DECODER_JT4_AVERAGE_CAPACITY]; + int32_t count; + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK); + CHECK(count == expected); + CHECK(decoder_engine_get_jt4_averages(f->engine, entries, DECODER_JT4_AVERAGE_CAPACITY, &count) == DECODER_OK); + CHECK(count == expected); + for (int i = 0; i < count; ++i) { + CHECK(entries[i].utc == 120000 + i * 200); + CHECK(entries[i].polarity == 1 && entries[i].used == 1); + CHECK(abs(entries[i].frequency_hz - 1000) < 10); + CHECK(isfinite(entries[i].sync) && isfinite(entries[i].dt_seconds)); + } + if (count > 1) { + CHECK(decoder_engine_get_jt4_averages(f->engine, entries, 1, &count) == DECODER_CAPACITY); + CHECK(count == expected); + } +} + +static void weak_averaging(fixture *f) +{ + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + for (int i = 0; i < 2; ++i) { + prepare(f, 11025, 0, 120000 + i * 200); + f->request.jt4.depth = 3; + f->request.jt4.averaging = 1; + decoder_engine_test_jt4_signal(11025, 0, 5 + i, 5.0f, 100, 1000, f->samples); + decode(f, i == 1); + averages(f, i + 1); + if (i == 0) release(f); + } + CHECK(f->messages == 1 && f->method == DECODER_JT4_METHOD_FANO && f->average_count == 2); + repeat(f); + decode(f, 1); + CHECK(f->average_count == 2); + averages(f, 2); + CHECK(decoder_engine_clear_jt4_averages(f->engine) == DECODER_OK); + averages(f, 0); + repeat(f); + decode(f, 0); + int32_t count; + decoder_jt4_average_entry entry; + CHECK(decoder_engine_get_jt4_averages(f->engine, &entry, 1, &count) == DECODER_OK); + CHECK(count == 1 && entry.utc == 120200); + release(f); + prepare(f, 11025, 1, 120400); + decode(f, 1); + averages(f, 0); + release(f); +} + +static void forced_decode(fixture *f) +{ + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120000); + f->request.jt4.tolerance_hz = 0; + f->request.jt4.averaging = 1; + decoder_engine_test_jt4_signal(11025, 0, 1, 0, 100, 1000, f->samples); + decode(f, 0); + CHECK(f->kind == DECODER_JT4_NO_SYNC && f->sync == 0); + int32_t count; + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK && count == 0); + repeat(f); + f->request.jt4.min_sync = -1; + decode(f, 0); + CHECK(f->kind == DECODER_JT4_SYNC && f->sync == 0); + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK && count == 1); + release(f); + + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120200); + f->request.jt4.min_sync = -1; + f->request.jt4.averaging = 1; + memset(f->samples, 0, f->audio.sample_count * sizeof *f->samples); + decode(f, 0); + CHECK(f->kind == DECODER_JT4_NO_SYNC && f->sync == 0); + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK && count == 0); + release(f); +} + +static void deep_search(fixture *f) +{ + decoder_jt4_call call = {"W9XYZ ", "FN42"}; + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120000); + f->request.jt4.depth = 3; + memcpy(f->request.jt4.mycall, "K1ABC ", 12); + decoder_engine_test_jt4_signal(11025, 0, 1, 5.0f, 100, 1000, f->samples); + decode(f, 0); + CHECK(decoder_engine_set_jt4_calls(f->engine, &call, 1) == DECODER_OK); + memset(&call, 0, sizeof call); + repeat(f); + f->request.jt4.deep_search = 1; + decode(f, 1); + CHECK(f->method == DECODER_JT4_METHOD_DEEP_SEARCH && !f->average_count); + memcpy(call.call, "N0CALL ", 12); + memcpy(call.grid, "EM00", 4); + CHECK(decoder_engine_set_jt4_calls(f->engine, &call, 1) == DECODER_OK); + repeat(f); + decode(f, 0); + CHECK(decoder_engine_set_jt4_calls(f->engine, NULL, 0) == DECODER_OK); + memcpy(f->request.jt4.hiscall, "W9XYZ ", 12); + memcpy(f->request.jt4.hisgrid, "FN42 ", 6); + repeat(f); + decode(f, 1); + CHECK(f->method == DECODER_JT4_METHOD_DEEP_SEARCH); + memcpy(f->request.jt4.hiscall, "N0CALL ", 12); + memcpy(f->request.jt4.hisgrid, "EM00 ", 6); + repeat(f); + decode(f, 0); + release(f); + memcpy(call.call, "W9XYZ ", 12); + memcpy(call.grid, "FN42", 4); + CHECK(decoder_engine_set_jt4_calls(f->engine, &call, 1) == DECODER_OK); + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120200); + f->request.jt4.depth = 3; + f->request.jt4.deep_search = 1; + memcpy(f->request.jt4.mycall, "K1ABC ", 12); + decoder_engine_test_jt4_signal(11025, 0, 1, 5.0f, 100, 1000, f->samples); + decode(f, 0); + release(f); +} + +static void run_tests(int smoke) +{ + fixture f = {0}; + create(&f); + for (int submode = 0; submode < (smoke ? 1 : 7); ++submode) { + prepare(&f, submode == 5 ? 12000 : 11025, submode, 0); + decode(&f, 1); + CHECK(f.method == DECODER_JT4_METHOD_FANO && !f.average_count); + release(&f); + } + if (!smoke) { + decoder_jt4_call call = {"W9XYZ ", "FN42"}; + CHECK(decoder_engine_set_jt4_calls(f.engine, &call, 1) == DECODER_OK); + memset(&call, 0, sizeof call); + CHECK(decoder_engine_set_jt4_calls(f.engine, NULL, 1) == DECODER_INVALID); + CHECK(decoder_engine_set_jt4_calls(f.engine, NULL, DECODER_JT4_CALL_CAPACITY + 1) == DECODER_INVALID); + CHECK(decoder_engine_set_jt4_calls(f.engine, NULL, 0) == DECODER_OK); + int32_t count = -1; + CHECK(decoder_engine_get_jt4_averages(f.engine, NULL, 0, &count) == DECODER_OK && count == 0); + prepare(&f, 11025, 0, 0); + f.request.phase = DECODER_PHASE_EARLY; + invalid(&f); + f.request.phase = DECODER_PHASE_NORMAL; + f.request.jt4.minimum_width_profile = 1; + invalid(&f); + f.request.jt4.minimum_width_profile = 0; + f.request.jt4.utc = 126000; + invalid(&f); + f.request.jt4.utc = 0; + f.request.jt4.submode = 7; + invalid(&f); + f.request.jt4.submode = 0; + f.audio.sample_rate_hz = 8000; + decoder_attempt_outcome outcome; + f.observations = 0; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_UNSUPPORTED); + CHECK(f.observations == 0); + f.audio.sample_rate_hz = 11025; + ++f.audio.sample_count; + invalid(&f); + --f.audio.sample_count; + f.request.jt4.averaging = 2; + invalid(&f); + } + lifecycle(&f); + if (!smoke) { + weak_averaging(&f); + forced_decode(&f); + deep_search(&f); + } + CHECK(decoder_engine_destroy(f.engine) == DECODER_OK); + decoder_engine_options options = {DECODER_ENGINE_ABI}; + CHECK(decoder_engine_create(&options, &f.engine) == DECODER_OK); + prepare(&f, 11025, 0, 130000); + decode(&f, 1); + destroy(&f); +} + +static void write_le(FILE *file, uint32_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; ++i) CHECK(fputc((value >> (8 * i)) & 255, file) != EOF); +} + +static void write_wav(const char *path) +{ + int16_t *samples = malloc(SAMPLE_CAPACITY * sizeof *samples); + CHECK(samples); + decoder_engine_test_jt4_signal(12000, 0, 1, 300, 100, 1000, samples); + FILE *file = fopen(path, "wb"); + CHECK(file); + CHECK(fwrite("RIFF", 1, 4, file) == 4); + write_le(file, 36 + SAMPLE_CAPACITY * 2, 4); + CHECK(fwrite("WAVEfmt ", 1, 8, file) == 8); + write_le(file, 16, 4); + write_le(file, 1, 2); + write_le(file, 1, 2); + write_le(file, 12000, 4); + write_le(file, 24000, 4); + write_le(file, 2, 2); + write_le(file, 16, 2); + CHECK(fwrite("data", 1, 4, file) == 4); + write_le(file, SAMPLE_CAPACITY * 2, 4); + for (int i = 0; i < SAMPLE_CAPACITY; ++i) write_le(file, (uint16_t)samples[i], 2); + CHECK(fclose(file) == 0); + free(samples); +} + +#ifdef _WIN32 +static DWORD WINAPI run_on_small_stack(LPVOID unused) +#else +static void *run_on_small_stack(void *unused) +#endif +{ + (void)unused; + run_tests(0); + return 0; +} + +#ifdef __linux__ +static int add_tls_size(struct dl_phdr_info *info, size_t size, void *opaque) +{ + (void)size; + size_t *stack_size = opaque; + for (int i = 0; i < info->dlpi_phnum; ++i) { + const ElfW(Phdr) *header = &info->dlpi_phdr[i]; + if (header->p_type == PT_TLS) *stack_size += header->p_memsz + header->p_align; + } + return 0; +} +#endif + +int main(int argc, char **argv) +{ + if (argc == 3 && !strcmp(argv[1], "--write-wav")) write_wav(argv[2]); + else if (argc == 2 && !strcmp(argv[1], "--smoke")) run_tests(1); + else if (argc == 1) run_tests(0); + else { + CHECK(argc == 2 && !strcmp(argv[1], "--small-stack")); +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 1024 * 1024, run_on_small_stack, NULL, + STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); + CHECK(thread != NULL); + CHECK(WaitForSingleObject(thread, INFINITE) == WAIT_OBJECT_0); + DWORD status; + CHECK(GetExitCodeThread(thread, &status) && status == 0); + CHECK(CloseHandle(thread)); +#else + pthread_attr_t attributes; + pthread_t thread; + size_t stack_size = 1024 * 1024; +#ifdef __linux__ + /* Linux puts static TLS in the stack mapping; reserve 1 MiB for calls. */ + dl_iterate_phdr(add_tls_size, &stack_size); +#endif + CHECK(pthread_attr_init(&attributes) == 0); + CHECK(pthread_attr_setstacksize(&attributes, stack_size) == 0); + int error = pthread_create(&thread, &attributes, run_on_small_stack, NULL); + if (error) fprintf(stderr, "pthread_create with %zu bytes: %s\n", stack_size, strerror(error)); + CHECK(error == 0); + CHECK(pthread_attr_destroy(&attributes) == 0); + CHECK(pthread_join(thread, NULL) == 0); +#endif + } + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 b/tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 new file mode 100644 index 00000000..2b228894 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 @@ -0,0 +1,213 @@ +program test_decoder_engine_jt4_host + use iso_c_binding, only: c_int,c_int8_t,c_int16_t,c_int64_t,c_float,c_sizeof + use decoder_engine, only: engine_host_decode + use decoder_engine_types, only: engine_jt4_options + use ft8_engine_kernel, only: params_block + use jt4_decode, only: jt4_decoder + use jt4_host_support, only: convert_jt4_host_options,load_jt4_calls,write_jt4_averages + use decode_completion_module, only: decode_completion_result + use prog_args, only: data_dir,temp_dir + implicit none + type(params_block) :: params,before_params + type(engine_jt4_options) :: options + type(jt4_decoder), allocatable :: decoder + type(decode_completion_result) :: completion + integer(c_int8_t) :: zeros(c_sizeof(params)) + integer(c_int16_t), allocatable, target :: samples(:) + integer(c_int16_t), allocatable :: before(:) + integer(c_int64_t) :: input_id=700,analysis_id=700 + integer :: npatience,nthreads,unit,ios,attempt=1 + character(len=100) :: line + logical :: exists + common/patience/npatience,nthreads + interface + subroutine signal(rate,submode,seed,amplitude,noise,frequency,samples) bind(C,name='decoder_engine_test_jt4_signal') + import c_int,c_int16_t,c_float + integer(c_int), value :: rate,submode,seed + real(c_float), value :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(*) + end subroutine + end interface + + data_dir='.' + temp_dir='.' + zeros=0 + params=transfer(zeros,params) + params%nmode=4 + params%ntr=60 + params%nutc=1234 + params%nfqso=1000 + params%ntol=50 + params%ndepth=3+16+32+128 + params%mycall=transfer('K1ABC ',params%mycall) + params%hiscall=transfer('W9XYZ ',params%hiscall) + params%hisgrid=transfer('FN42 ',params%hisgrid) + before_params=params + call convert_jt4_host_options(params,options) + call require(options%utc==123400,'legacy HHMM converts to HHMMSS') + call require(options%depth==3.and.options%averaging==1.and.options%deep_search==1,'packed effort separates feature flags') + call require(all(transfer(params,zeros)==transfer(before_params,zeros)),'conversion does not mutate legacy parameters') + + allocate(decoder) + npatience=0 + call remove_file('CALL3.TXT') + call load_jt4_calls(decoder) + inquire(file='CALL3.TXT',exist=exists) + call require(.not.exists,'missing call list is not created by loading') + call require(size(decoder%calls)==0,'missing call list clears template knowledge') + open(newunit=unit,file='CALL3.TXT',status='replace') + write(unit,'(a)') '// ignored comment','invalid','W9XYZ,FN42,,','K9XYZ,EN50,,','ZZZZ,AA00,,','N0CALL,EM00,,' + close(unit) + call load_jt4_calls(decoder) + call require(size(decoder%calls)==2,'CALL3 terminator stops parsing') + call require(decoder%calls(1)%call=='W9XYZ'.and.decoder%calls(2)%call=='K9XYZ','CALL3 ordering is preserved') + call require(decoder%calls(1)%grid=='FN42','CALL3 grid survives loading') + open(newunit=unit,file='CALL3.TXT',status='replace') + write(unit,'(a)') 'N0CALL,EM00,,' + close(unit) + call load_jt4_calls(decoder) + call require(size(decoder%calls)==1.and.decoder%calls(1)%call=='N0CALL','changed call list replaces host knowledge') + + call decoder%save_average(123400,5.0,0.1,1.0,1000,50) + call decoder%save_average(123600,6.0,0.1,-1.0,1000,50) + decoder%average_used(1)=.true. + open(newunit=unit,file='avemsg.txt',status='replace') + call write_jt4_averages(decoder,unit) + rewind(unit) + read(unit,'(a)') line + call require(line(1:1)=='$'.and.line(3:6)=='1234'.and.index(line,'*')>0,'legacy average row UTC and selection') + read(unit,'(a)') line + call require(line(1:1)=='.'.and.index(line(2:),'$')>0,'legacy inverted-polarity average marker') + call decoder%clear_averages() + call write_jt4_averages(decoder,unit) + rewind(unit) + read(unit,'(a)',iostat=ios) line + call require(ios<0,'clear truncates old average output') + close(unit) + deallocate(decoder) + + allocate(samples(60*11025),before(60*11025)) + params%ndepth=1 + params%newdat=.true. + params%ndiskdat=.true. + params%nclearave=.true. + samples=0 + before=samples + call run(0) + params%nclearave=.false. + call signal(11025,0,1,300.0,100.0,1000.0,samples) + before=samples + call run(1) + call require(output_contains('K1ABC W9XYZ FN42'),'legacy host prints recovered message') + call require(output_contains('1234'),'legacy host retains HHMM output') + params%newdat=.false. + params%nagain=.true. + attempt=2 + analysis_id=analysis_id+1 + call run(1) + call require(output_contains('K1ABC W9XYZ FN42'),'manual repeat decodes retained input') + input_id=input_id+1 + analysis_id=analysis_id+1 + attempt=1 + params%newdat=.true. + params%nagain=.false. + samples=0 + before=0 + call run(0) + call require(.not.output_contains('K1ABC'),'no-sync output cannot reuse prior message') + call new_period(1234) + params%ndepth=3+16 + call signal(11025,0,5,5.0,100.0,1000.0,samples) + before=samples + call run(0) + call require(average_rows()==1,'weak synchronized reception enters average history') + call require(.not.output_contains('K1ABC'),'sync-only observation is not a recovered message') + + params%minsync=100 + params%nagain=.true. + params%newdat=.false. + attempt=2 + analysis_id=analysis_id+1 + call run(0) + call require(output_contains('1234'),'no-sync observation remains visible without counting as decoded') + params%minsync=0 + + call new_period(1235) + params%nclearave=.true. + samples=0 + before=samples + call run(0) + params%nclearave=.false. + + call new_period(1236) + call signal(11025,0,6,5.0,100.0,1000.0,samples) + before=samples + call run(0) + call require(average_rows()==1,'quiet clear prevents reuse of the preceding weak reception') + deallocate(samples,before) + +contains + subroutine require(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if(.not.condition) then + print *, 'JT4 host: ',message + error stop 1 + endif + end subroutine + + subroutine run(expected) + integer, intent(in) :: expected + before_params=params + open(unit=6,file='host-output.txt',status='replace') + call engine_host_decode(samples,params,11025,completion,0,input_id,analysis_id,attempt,size(samples)) + close(6) + call require(completion%available.and.completion%decoded==expected,'host completion counts only recovered messages') + call require(all(before==samples),'host leaves supplied PCM unchanged') + call require(all(transfer(params,zeros)==transfer(before_params,zeros)),'host leaves packed parameters unchanged') + end subroutine + + subroutine new_period(utc) + integer, intent(in) :: utc + params%nutc=utc + params%newdat=.true. + params%nagain=.false. + input_id=input_id+1 + analysis_id=analysis_id+1 + attempt=1 + end subroutine + + integer function average_rows() result(count) + integer :: file_unit,status + character(len=100) :: row + count=0 + open(newunit=file_unit,file='avemsg.txt',status='old') + do + read(file_unit,'(a)',iostat=status) row + if(status/=0) exit + count=count+1 + enddo + close(file_unit) + end function + + logical function output_contains(text) result(found) + character(len=*), intent(in) :: text + integer :: file_unit,status + character(len=256) :: row + found=.false. + open(newunit=file_unit,file='host-output.txt',status='old') + do + read(file_unit,'(a)',iostat=status) row + if(status/=0) exit + if(index(row,text)>0) found=.true. + enddo + close(file_unit) + end function + + subroutine remove_file(path) + character(len=*), intent(in) :: path + integer :: file_unit,status + open(newunit=file_unit,file=path,status='old',iostat=status) + if(status==0) close(file_unit,status='delete') + end subroutine +end program diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 b/tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 new file mode 100644 index 00000000..947750ce --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 @@ -0,0 +1,112 @@ +program test_decoder_engine_jt4_state + use iso_c_binding, only: c_int16_t + use jt4_decode, only: jt4_decoder,jt4_options,jt4_average_entry + implicit none + type(jt4_decoder), allocatable :: decoder,other + type(jt4_average_entry) :: entries(64) + type(jt4_options) :: options + integer(c_int16_t) :: silence(1)=0 + real :: sym(207,7),symbols(207) + integer :: nsum,i,slot,entry_count,ncount,status + character(len=22) :: decoded + interface + subroutine ignore_result(this,snr,dt,freq,have_sync,sync,is_deep,decoded,qual,ich,is_average,ave) + import jt4_decoder + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: snr,freq,ich,ave + real,intent(in) :: dt,qual + logical,intent(in) :: have_sync,is_deep,is_average + character,intent(in) :: sync + character(len=22),intent(in) :: decoded + end subroutine + end interface + + allocate(decoder,other) + allocate(decoder%rsymbol(207,7),decoder%ppsave(207,7,64)) + decoder%rsymbol=2.0 + call decoder%save_average(120000,4.0,0.0,1.0,1000,20) + call check(decoder%average_count==1,'first reception') + decoder%rsymbol=4.0 + call decoder%save_average(120000,6.0,0.01,1.0,1010,20) + call check(decoder%average_count==1,'same minute and nearby frequency deduplicate') + call decoder%save_average(120200,6.0,0.1,1.0,1010,20) + call decoder%select_average(120200,0.0,1.0,1000,20,sym,nsum) + call check(nsum==2.and.all(abs(sym-3.0)<1.e-6),'matching receptions average symbols') + call check(count(decoder%average_used)==2,'selected reception flags') + + call decoder%save_average(120100,8.0,0.0,1.0,1000,20) + call decoder%save_average(120400,8.0,0.5,1.0,1000,20) + call decoder%save_average(120600,8.0,0.0,-1.0,1000,20) + call decoder%save_average(120800,8.0,0.0,1.0,1100,20) + call decoder%select_average(120200,0.0,1.0,1000,20,sym,nsum) + call check(nsum==2,'parity, DT, polarity and frequency exclude incompatible receptions') + call check(decoder%average_count==6,'excluded receptions remain in history') + call check(other%average_count==0,'decoder instances do not share history') + + call decoder%clear_averages() + call check(decoder%average_count==0.and.all(decoder%iutc<0),'clear removes all entries') + call check(.not.any(decoder%average_used),'clear removes selection flags') + decoder%rsymbol=1.0 + call decoder%save_average(120000,4.0,0.0,1.0,1000,20) + call check(decoder%average_count==1,'cleared reception can be inserted again') + + call decoder%clear_averages() + do i=0,64 + decoder%rsymbol=real(i) + call decoder%save_average((i/60)*10000+mod(i,60)*100,4.0,0.0,1.0,1000,20) + enddo + call check(decoder%average_count==64,'history capacity after ring wrap') + call check(count(decoder%iutc>=0)==64,'all slots remain visible after ring wrap') + call check(.not.any(decoder%iutc==0),'oldest reception evicted') + call check(any(decoder%iutc==10400),'newest reception retained') + call decoder%get_averages(entries,entry_count) + call check(entry_count==64,'snapshot reports all entries after ring wrap') + call check(entries(1)%utc==10400,'snapshot preserves physical slot order') + call decoder%select_average(10400,0.0,1.0,1000,20,sym,nsum) + call check(nsum==32,'parity selection remains correct across hour and ring wrap') + call check(all(abs(sym-33.0)<1.e-6),'wrapped average contains precisely retained even minutes') + slot=decoder%nsave + call decoder%save_average(10400,9.0,0.0,1.0,1001,20) + call check(decoder%nsave==slot.and.decoder%average_count==64,'duplicate does not advance ring') + + options%submode=1 + call decoder%decode_pcm(options,silence,11025,ignore_result,status) + call check(status==0,'prepare changed submode') + decoder%rsymbol=1.0 + call decoder%save_average(120000,4.0,0.0,1.0,1000,20) + call decoder%decode_pcm(options,silence,11025,ignore_result,status) + call check(status==0.and.decoder%average_count==1,'same width profile retains compatible history') + options%minimum_width_profile=1 + call decoder%decode_pcm(options,silence,11025,ignore_result,status) + call check(status==0.and.decoder%average_count==0,'changed width profile clears incompatible history') + deallocate(decoder,other) + + do i=0,1 + symbols=real(i) + decoded='stale decoded message' + ncount=42 + call extract4(symbols,ncount,decoded) + call check(ncount<0.and.len_trim(decoded)==0,'zero-variance symbols fail without stale message') + enddo + +contains + subroutine check(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if(.not.condition) then + print *, 'JT4 average state: ',message + stop 1 + endif + end subroutine +end program + +subroutine ignore_result(this,snr,dt,freq,have_sync,sync,is_deep,decoded,qual,ich,is_average,ave) + use jt4_decode, only: jt4_decoder + implicit none + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: snr,freq,ich,ave + real,intent(in) :: dt,qual + logical,intent(in) :: have_sync,is_deep,is_average + character,intent(in) :: sync + character(len=22),intent(in) :: decoded +end subroutine diff --git a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp index c2b3b45b..25fa54b0 100644 --- a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp +++ b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp @@ -80,3 +80,40 @@ extern "C" int jtty_cpp_rtty_smoke (int tones[], int* nsym) } return status; } + +extern "C" int jtty_cpp_rtty_line_refused () +{ + // 80 characters; RTTY Roundup writes the serial as 005, which makes it 81. + QString const line = QString (73, QLatin1Char {'A'}) + QStringLiteral (" 599 05"); + auto encodesWith = [] (Jtty::NativeExchangeProfile exchange) { + return [profile = static_cast (exchange)] (QString const& text) { + auto frame = Jtty::transmitFrame (text).toLatin1 (); + std::array tones {}; + std::array frameStarts {}; + int symbols {}; + int const isFinal = 0; + genjtty_profile_ (frame.data (), &profile, tones.data (), &symbols, + frameStarts.data (), &isFinal, frame.size ()); + return symbols > 0; + }; + }; + auto const rtty = Jtty::encodeTransmitLine (line, encodesWith (Jtty::NativeExchangeProfile::RttyRoundup)); + auto const none = Jtty::encodeTransmitLine (line, encodesWith (Jtty::NativeExchangeProfile::None)); + return !rtty && none && none->size () == 1; +} + +extern "C" int jtty_cpp_rtty_line_tones (int tones[], int* nsym) +{ + // 79 characters; with the serial written as 005 it is exactly 80. + QString const line = QString (72, QLatin1Char {'A'}) + QStringLiteral (" 599 05"); + int const profile = static_cast (Jtty::NativeExchangeProfile::RttyRoundup); + auto encode = [&] (QString const& text, int isFinal) { + auto frame = Jtty::transmitFrame (text).toLatin1 (); + std::array frameStarts {}; + *nsym = 0; + genjtty_profile_ (frame.data (), &profile, tones, nsym, frameStarts.data (), &isFinal, frame.size ()); + return *nsym > 0; + }; + auto const segments = Jtty::encodeTransmitLine (line, [&] (QString const& text) { return encode (text, 0); }); + return segments && segments->size () == 1 && encode (segments->front ().text, 1); +} diff --git a/tests/unit/jtty/test_jtty_messages.cpp b/tests/unit/jtty/test_jtty_messages.cpp index 033966e4..f877e1a0 100644 --- a/tests/unit/jtty/test_jtty_messages.cpp +++ b/tests/unit/jtty/test_jtty_messages.cpp @@ -2,6 +2,16 @@ #include "widgets/JttyMessages.hpp" +namespace +{ + // 121 characters: two transmit segments. + QString longLine () + { + return QStringLiteral ("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG AND KEEPS RUNNING ACROSS THE FIELD" + " UNTIL IT REACHES THE OLD BARN BY THE RIVER"); + } +} + class TestJttyMessages final : public QObject { @@ -690,6 +700,44 @@ private slots: Jtty::maxTransmitLength); } + void encodeTransmitLineRefusesRatherThanShortens () + { + QString const line = QString (73, QLatin1Char {'A'}) + QStringLiteral (" 599 05"); + QStringList attempts; + auto const encoded = Jtty::encodeTransmitLine (line, [&] (QString const& text) { + attempts << text; + return text.size () < line.size (); + }); + QVERIFY (!encoded); + QCOMPARE (attempts, QStringList {line}); + + QStringList cuts; + auto const laterSegmentFails = Jtty::encodeTransmitLine (longLine (), [&] (QString const& text) { + cuts << text; + return cuts.size () < 2; + }); + QVERIFY (!laterSegmentFails); + QCOMPARE (cuts.size (), 2); + QCOMPARE (cuts.join (QString {}), longLine ()); + } + + void encodeTransmitLineKeepsTheSegmentCuts () + { + QString const line = longLine (); + QStringList attempts; + auto const encoded = Jtty::encodeTransmitLine (line, [&] (QString const& text) { + attempts << text; + return true; + }); + QVERIFY (encoded); + QCOMPARE (encoded->size (), 2); + QCOMPARE (attempts, (QStringList {encoded->at (0).text, encoded->at (1).text})); + QCOMPARE (encoded->at (0).text + encoded->at (1).text, line); + auto const blank = Jtty::encodeTransmitLine (QString (5, QLatin1Char {' '}), + [] (QString const&) { return false; }); + QVERIFY (blank && blank->isEmpty ()); + } + void wavCaptureValid_data () { QTest::addColumn ("k0"); diff --git a/tests/unit/jtty/test_jtty_structured_decode.f90 b/tests/unit/jtty/test_jtty_structured_decode.f90 index 6a55a816..56f9256a 100644 --- a/tests/unit/jtty/test_jtty_structured_decode.f90 +++ b/tests/unit/jtty/test_jtty_structured_decode.f90 @@ -37,6 +37,15 @@ program test_jtty_structured_decode integer(c_int), intent(out) :: tones(*),nsym integer(c_int) :: status end function jtty_cpp_rtty_smoke + function jtty_cpp_rtty_line_refused() result(refused) bind(C) + import :: c_int + integer(c_int) :: refused + end function jtty_cpp_rtty_line_refused + function jtty_cpp_rtty_line_tones(tones,nsym) result(planned) bind(C) + import :: c_int + integer(c_int), intent(out) :: tones(*),nsym + integer(c_int) :: planned + end function jtty_cpp_rtty_line_tones subroutine genjtty_atoms(atoms,natoms,itone,nsym) use jtty_mod, only: jtty_source_atom type(jtty_source_atom), intent(in) :: atoms(:) @@ -63,6 +72,9 @@ program test_jtty_structured_decode call decode_cpp_compiled_n1mm(failures) call decode_compact_text(failures) call decode_profile_text(failures) + call expect(jtty_cpp_rtty_line_refused().eq.1, & + 'an RTTY line whose serial does not fit is refused, not split',failures) + call decode_accepted_rtty_line(failures) if(failures.ne.0) then write(*,'(a,i0)') 'test_jtty_structured_decode: failures=',failures @@ -351,6 +363,23 @@ contains deallocate(pcm,wave,complex_wave) end subroutine decode_waveform + subroutine decode_accepted_rtty_line(count) + integer, intent(inout) :: count + integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols + character(len=80) :: expected + + expected=repeat('A',72)//' 599 005' + call expect(jtty_cpp_rtty_line_tones(tones,nsymbols).eq.1, & + 'the longest RTTY line that fits is one segment',count) + if(nsymbols.le.0) return + call decode_waveform(tones,int(nsymbols)) + call expect(npending.ge.1,'the accepted RTTY line produces updates',count) + if(npending.lt.1) return + call expect(trim(normalized(pending_updates(npending)%decoded)).eq.trim(expected) .and. & + pending_updates(npending)%complete .and. nactive.eq.0, & + 'the accepted RTTY line arrives whole, serial included',count) + end subroutine decode_accepted_rtty_line + function normalized(value) result(result_value) character(len=*), intent(in) :: value character(len=80) :: result_value diff --git a/tests/unit/map65/test_map65_pass_snapshots.f90 b/tests/unit/map65/test_map65_pass_snapshots.f90 new file mode 100644 index 00000000..cfbd12b7 --- /dev/null +++ b/tests/unit/map65/test_map65_pass_snapshots.f90 @@ -0,0 +1,100 @@ +program test_map65_pass_snapshots + ! Each automatic decode pass must decode data frozen at the moment it was + ! triggered. Simulates the new minute resetting the live buffers while the + ! 302-symbol pass is still queued behind the running 280-symbol pass. + use iso_c_binding, only: c_float + use datcom_ptrs_mod, only: dd, ss, savg, snap, snapshot_buffers + use npar_ptrs_mod, only: snap_latest_idx, set_nhsym, set_nagain, set_ndiskdat, & + publish_decode_request, claim_decode_request, active_request_expired, & + active_snap_idx, snapshot_release, advance_live_input_generation + implicit none + + integer, parameter :: nsmax = 4000, ncol = 12, nfft = 16 + integer(8) :: rid + + allocate(dd(4,nsmax), ss(4,ncol,nfft), savg(4,nfft)) + allocate(snap(1)%dd(4,nsmax), snap(1)%ss(4,ncol,nfft), snap(1)%savg(4,nfft)) + allocate(snap(2)%dd(4,nsmax), snap(2)%ss(4,ncol,nfft), snap(2)%savg(4,nfft)) + snap(1)%dd = -1.0; snap(1)%ss = -1.0; snap(1)%savg = -1.0 + snap(2)%dd = -1.0; snap(2)%ss = -1.0; snap(2)%savg = -1.0 + + ! Early pass (nhsym 280 stand-in): live buffers hold cycle A up to sample 3000 + dd = 0.0; dd(:,1:3000) = 1.0 + ss = 0.0; ss(:,1:10,:) = 1.0 + savg = 10.0 + call snapshot_buffers(1, 3000, 10) + call require(snap_latest_idx == 1, 'latest snapshot is the early one') + + ! Later: live buffers keep filling, then the new minute resets them + dd(:,3001:3800) = 2.0 + ss(:,11:12,:) = 2.0 + savg = 20.0 + call snapshot_buffers(2, 3800, 12) + call require(snap_latest_idx == 2, 'latest snapshot is the final one') + + dd = 7.0; ss = 7.0; savg = 0.0 !Next cycle overwrites / resets live + + call require(all(snap(1)%dd(:,1:3000) == 1.0), 'early dd frozen') + call require(all(snap(1)%dd(:,3513:) == 0.0), 'early dd past lookahead is zero') + call require(all(snap(1)%ss(:,1:10,:) == 1.0), 'early ss frozen') + call require(all(snap(1)%ss(:,11:,:) == 0.0), 'early ss past nhsym is zero') + call require(all(snap(1)%savg == 10.0), 'early savg frozen') + + call require(all(snap(2)%dd(:,1:3000) == 1.0), 'final dd has early part') + call require(all(snap(2)%dd(:,3001:3800) == 2.0), 'final dd has later part') + call require(all(snap(2)%ss(:,11:12,:) == 2.0), 'final ss frozen') + call require(all(snap(2)%savg == 20.0), 'final savg frozen') + + ! ---- request expiry follows the snapshot, not the minute boundary ---- + call set_nagain(0); call set_ndiskdat(0) + + ! 1. A final-pass request claimed after the minute rolled over still runs + ! (its snapshot is intact), and holds its slot while running. + dd = 3.0; ss = 3.0; savg = 3.0 + call set_nhsym(302) + call snapshot_buffers(2, 3800, 12) + rid = publish_decode_request() + call advance_live_input_generation() !new minute begins + call require(claim_decode_request(), 'request claimed') + call require(.not. active_request_expired, 'late request with intact snapshot runs') + call require(active_snap_idx == 2, 'late request reads its own slot') + + ! 2. While that pass is running, the next cycle's fill must not overwrite + ! the slot; the request published for it is then dropped, not mis-decoded. + dd = 4.0 + call snapshot_buffers(2, 3800, 12) + call require(all(snap(2)%dd(:,1:3800) == 3.0), 'busy slot not overwritten') + rid = publish_decode_request() + call snapshot_release() + call require(claim_decode_request(), 'second request claimed') + call require(active_request_expired, 'request whose fill was skipped is dropped') + + ! 3. A queued request whose slot is refilled before it is claimed is dropped. + dd = 5.0 + call snapshot_buffers(2, 3800, 12) + rid = publish_decode_request() + dd = 6.0 + call snapshot_buffers(2, 3800, 12) + call require(claim_decode_request(), 'third request claimed') + call require(active_request_expired, 'overwritten snapshot request is dropped') + + ! 4. More than one generation old (monitoring stopped etc.) is dropped. + call snapshot_buffers(2, 3800, 12) + rid = publish_decode_request() + call advance_live_input_generation() + call advance_live_input_generation() + call require(claim_decode_request(), 'fourth request claimed') + call require(active_request_expired, 'request two generations old is dropped') + print *, 'test_map65_pass_snapshots: PASS' + +contains + + subroutine require(ok, what) + logical, intent(in) :: ok + character(*), intent(in) :: what + if (.not. ok) then + print *, 'FAIL: ', what + error stop 1 + end if + end subroutine require +end program test_map65_pass_snapshots diff --git a/tests/unit/streaming/CMakeLists.txt b/tests/unit/streaming/CMakeLists.txt index 4db80617..6aae5282 100644 --- a/tests/unit/streaming/CMakeLists.txt +++ b/tests/unit/streaming/CMakeLists.txt @@ -1,11 +1,13 @@ add_executable (test_streaming_consumers test_streaming_consumers.cpp) -add_dependencies (test_streaming_consumers test_decoder_engine_q65 test_decoder_engine_fst4) +add_dependencies (test_streaming_consumers test_decoder_engine test_decoder_engine_q65 test_decoder_engine_fst4 test_decoder_engine_jt4) target_link_libraries (test_streaming_consumers Qt5::Test) target_compile_definitions (test_streaming_consumers PRIVATE + JT4_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/jt4-engine.wav" JT9_EXECUTABLE="$" WSPRD_EXECUTABLE="$" FST4_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/fst4-engine.wav" FST4W_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/fst4w-engine.wav" + FT8_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/ft8-engine.wav" Q65_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/q65-engine.wav" ) @@ -13,7 +15,7 @@ add_test (NAME test_streaming_consumers COMMAND test_streaming_consumers) set_tests_properties (test_streaming_consumers PROPERTIES LABELS "streaming;runtime" TIMEOUT 360 - FIXTURES_REQUIRED "q65_engine_wav;fst4_engine_wav;fst4w_engine_wav" + FIXTURES_REQUIRED "ft8_engine_wav;jt4_engine_wav;q65_engine_wav;fst4_engine_wav;fst4w_engine_wav" ) if (WSJT_ENABLE_TSAN) set_tests_properties (test_streaming_consumers PROPERTIES diff --git a/tests/unit/streaming/test_streaming_consumers.cpp b/tests/unit/streaming/test_streaming_consumers.cpp index 91ed0e2e..3d9caf46 100644 --- a/tests/unit/streaming/test_streaming_consumers.cpp +++ b/tests/unit/streaming/test_streaming_consumers.cpp @@ -238,6 +238,52 @@ class TestStreamingConsumers final : public QObject Q_OBJECT private slots: + void jt4DecodesWaveform_data () + { + QTest::addColumn ("timeFields"); + QTest::addColumn ("expected"); + QTest::newRow ("afternoon") << QJsonObject {{"utc", "12:34:00"}} << QString {"123400"}; + QTest::newRow ("legacy-numeric") << QJsonObject {{"nutc", 1234}} << QString {"123400"}; + QTest::newRow ("early-hour-iso-precedence") + << QJsonObject {{"nutc", 1234}, {"utc", "00:12:34"}} << QString {"001234"}; + } + + void jt4DecodesWaveform () + { + QFETCH (QJsonObject, timeFields); + QFETCH (QString, expected); + QFile recording {QString::fromUtf8 (JT4_ENGINE_WAV)}; + QVERIFY2 (recording.open (QIODevice::ReadOnly), qPrintable (recording.errorString ())); + auto const wav = recording.readAll (); + QCOMPARE (wav.size (), 44 + 60 * 12000 * 2); + QCOMPARE (wav.left (4), QByteArray {"RIFF"}); + QCOMPARE (wav.mid (36, 4), QByteArray {"data"}); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QJsonObject configuration {{"t", "configure"}, {"mode", "JT4"}, {"trperiod", 60}, + {"submode", 0}, {"depth_level", 1}, {"rxfreq", 1000}, {"ntol", 50}}; + for (auto it = timeFields.constBegin (); it != timeFields.constEnd (); ++it) + { + configuration.insert (it.key (), it.value ()); + } + auto const input = sessionHeader () + controlFrame ( + QJsonDocument {configuration}.toJson (QJsonDocument::Compact)) + + frame (0x01u, wav.mid (44)) + controlFrame (R"({"t":"halt"})"); + auto const result = runProcess (QString::fromUtf8 (JT9_EXECUTABLE), + {"-a", directory.path (), "-t", directory.path (), "--stream"}, input, directory.path ()); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + auto const decodes = eventsMatching (events.values, "decode"); + QCOMPARE (decodes.size (), 1); + QCOMPARE (decodes.first ().value ("mode").toString (), QString {"JT4"}); + QCOMPARE (decodes.first ().value ("time").toString (), expected); + QCOMPARE (decodes.first ().value ("message").toString ().trimmed (), QString {"K1ABC W9XYZ FN42"}); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), expected); + } + void fst4DecodesWaveform_data () { QTest::addColumn ("mode"); @@ -277,7 +323,7 @@ private slots: bool found = false; for (auto const& decode : eventsMatching (events.values, "decode")) { - QCOMPARE (decode.value ("mode").toString (), QString {"FST4"}); + QCOMPARE (decode.value ("mode").toString (), mode); found |= decode.value ("message").toString ().trimmed () == message; } QVERIFY2 (found, result.standardOutput.constData ()); @@ -475,6 +521,120 @@ private slots: QCOMPARE (eventsMatching (events.values, "decode_finished").size (), 2); } + // A period's label is the producer's UTC, whichever key and frame carried it. + void jt9LabelsPeriodsWithTheProducersUtc_data () + { + QTest::addColumn ("configure"); + QTest::addColumn ("samples"); + QTest::addColumn ("periodEnd"); + QTest::newRow ("FT8 05:11:15") + << controlFrame (R"({"t":"configure","mode":"FT8","utc":"05:11:15"})") << 15 * 12000 << QString {"051115"}; + QTest::newRow ("FT8 00:45:15") + << controlFrame (R"({"t":"configure","mode":"FT8","utc":"00:45:15"})") << 15 * 12000 << QString {"004515"}; + QTest::newRow ("JT9, utc, then FT8") + << controlFrame (R"({"t":"configure","mode":"JT9"})") + controlFrame (R"({"t":"configure","utc":"05:11:15"})") + + controlFrame (R"({"t":"configure","mode":"FT8"})") + << 15 * 12000 << QString {"051115"}; + QTest::newRow ("FT8 nutc") + << controlFrame (R"({"t":"configure","mode":"FT8","nutc":51115})") << 15 * 12000 << QString {"051115"}; + QTest::newRow ("JT9, nutc 1530, then FT8") + << controlFrame (R"({"t":"configure","mode":"JT9"})") + controlFrame (R"({"t":"configure","nutc":1530})") + + controlFrame (R"({"t":"configure","mode":"FT8"})") + << 15 * 12000 << QString {"001530"}; + QTest::newRow ("FT8 negative nutc") + << controlFrame (R"({"t":"configure","mode":"FT8","nutc":-1})") << 15 * 12000 << QString {"000000"}; + QTest::newRow ("FT4 05:11:15") + << controlFrame (R"({"t":"configure","mode":"FT4","utc":"05:11:15"})") << Ft4PeriodSamples << QString {"051115"}; + QTest::newRow ("MSK144 05:11:15") + << controlFrame (R"({"t":"configure","mode":"MSK144","trperiod":15,"utc":"05:11:15"})") << 15 * 12000 + << QString {"051115"}; + QTest::newRow ("FST4-15 05:11:15") + << controlFrame (R"({"t":"configure","mode":"FST4","trperiod":15,"utc":"05:11:15"})") << 15 * 12000 + << QString {"051115"}; + QTest::newRow ("JT9 05:11:00") + << controlFrame (R"({"t":"configure","mode":"JT9","utc":"05:11:00"})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 nutc HHMM") + << controlFrame (R"({"t":"configure","mode":"JT9","nutc":511})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 nutc HHMMSS") + << controlFrame (R"({"t":"configure","mode":"JT9","nutc":51100})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 nutc 4515") + << controlFrame (R"({"t":"configure","mode":"JT9","nutc":4515})") << 60 * 12000 << QString {"004515"}; + QTest::newRow ("JT9 utc and nutc in one frame") + << controlFrame (R"({"t":"configure","mode":"JT9","utc":"00:15:00","nutc":1530})") << 60 * 12000 + << QString {"001500"}; + QTest::newRow ("utc 00:15:00, then JT9") + << controlFrame (R"({"t":"configure","utc":"00:15:00"})") + controlFrame (R"({"t":"configure","mode":"JT9"})") + << 60 * 12000 << QString {"001500"}; + QTest::newRow ("nutc HHMM, then JT9") + << controlFrame (R"({"t":"configure","nutc":511})") + controlFrame (R"({"t":"configure","mode":"JT9"})") + << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 utc, then nutc") + << controlFrame (R"({"t":"configure","mode":"JT9","utc":"05:11:00"})") + + controlFrame (R"({"t":"configure","nutc":512})") + << 60 * 12000 << QString {"051200"}; + QTest::newRow ("JT65 05:11:00") + << controlFrame (R"({"t":"configure","mode":"JT65","utc":"05:11:00"})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT4 05:11:00") + << controlFrame (R"({"t":"configure","mode":"JT4","utc":"05:11:00"})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("FST4-60 05:11:00") + << controlFrame (R"({"t":"configure","mode":"FST4","trperiod":60,"utc":"05:11:00"})") << 60 * 12000 + << QString {"051100"}; + QTest::newRow ("FST4W-120 05:12:00") + << controlFrame (R"({"t":"configure","mode":"FST4W","trperiod":120,"utc":"05:12:00"})") << 120 * 12000 + << QString {"051200"}; + QTest::newRow ("Q65-60 05:11:00") + << controlFrame (R"({"t":"configure","mode":"Q65","trperiod":60,"utc":"05:11:00"})") << 60 * 12000 + << QString {"051100"}; + } + + void jt9LabelsPeriodsWithTheProducersUtc () + { + QFETCH (QByteArray, configure); + QFETCH (int, samples); + QFETCH (QString, periodEnd); + auto const result = runJt9 (sessionHeader () + configure + silentAudioFrame (samples)); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), periodEnd); + } + + void ft8DecodeCarriesTheProducersUtc_data () + { + QTest::addColumn ("utc"); + QTest::addColumn ("label"); + QTest::newRow ("05:11:15") << QString {"05:11:15"} << QString {"051115"}; + QTest::newRow ("00:45:15") << QString {"00:45:15"} << QString {"004515"}; + } + + void ft8DecodeCarriesTheProducersUtc () + { + QFETCH (QString, utc); + QFETCH (QString, label); + QFile recording {QString::fromUtf8 (FT8_ENGINE_WAV)}; + QVERIFY2 (recording.open (QIODevice::ReadOnly), qPrintable (recording.errorString ())); + auto const wav = recording.readAll (); + QCOMPARE (wav.size (), 44 + 15 * 12000 * 2); + QJsonObject configuration {{"t", "configure"}, {"mode", "FT8"}, {"utc", utc}}; + auto const result = runJt9 (sessionHeader () + controlFrame ( + QJsonDocument {configuration}.toJson (QJsonDocument::Compact)) + frame (0x01u, wav.mid (44))); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + bool found = false; + for (auto const& decode : eventsMatching (events.values, "decode")) + { + QCOMPARE (decode.value ("time").toString (), label); + found |= decode.value ("message").toString ().trimmed () == "CQ K1JT FN20"; + } + QVERIFY2 (found, result.standardOutput.constData ()); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), label); + } + void wsprdRejectsOversizedFrames_data () { QTest::addColumn ("declaredLength"); diff --git a/widgets/JttyMessages.hpp b/widgets/JttyMessages.hpp index b25a1cf9..9f51a6a0 100644 --- a/widgets/JttyMessages.hpp +++ b/widgets/JttyMessages.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -262,6 +263,22 @@ namespace Jtty return {offset, length, message.mid (offset, length)}; } + // A segment that does not encode refuses the line rather than being cut shorter: the rest would continue the receiver's 80-column message. + template + std::optional> encodeTransmitLine (QString const& line, Encode&& encode) + { + QVector segments; + for (int offset = 0; offset < line.size ();) { + auto const source = nextTransmitTextSegment (line, offset); + if (!source.text.trimmed ().isEmpty ()) { + if (!encode (source.text)) return std::nullopt; + segments.append (source); + } + offset += source.length; + } + return segments; + } + // An empty result rejects oversized text before it reaches the fixed-width codec. inline QString transmitFrame (QString const& message) { diff --git a/widgets/mainwindow.cpp b/widgets/mainwindow.cpp index 9c9031fb..41f25835 100644 --- a/widgets/mainwindow.cpp +++ b/widgets/mainwindow.cpp @@ -5630,7 +5630,8 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, #if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) bool MainWindow::startWavDecodeTest (QString const& path) { - auto const fixtureMode = ((m_mode == QStringLiteral ("JT9") + auto const fixtureMode = ((m_mode == QStringLiteral ("JT4") + || m_mode == QStringLiteral ("JT9") || m_mode == QStringLiteral ("JT65") || m_mode == QStringLiteral ("Q65")) && m_TRperiod == 60.0) || (m_mode == QStringLiteral ("FST4") && m_TRperiod == 15.0) diff --git a/widgets/mainwindow_jtty.cpp b/widgets/mainwindow_jtty.cpp index 2ad9b573..bd19b584 100644 --- a/widgets/mainwindow_jtty.cpp +++ b/widgets/mainwindow_jtty.cpp @@ -341,29 +341,18 @@ int MainWindow::countJttyTransmitFrames(QString const& preparedMessage) const int totalFrames = 0; auto const lines = preparedMessage.split (QLatin1Char ('\n')); for (auto const& line : lines) { - for (int offset = 0; offset < line.size ();) { - auto source = Jtty::nextTransmitTextSegment (line, offset); - if (source.text.trimmed ().isEmpty ()) { - offset += source.length; - continue; - } - for (;;) { - auto frame = Jtty::transmitFrame (source.text).toLatin1 (); - QVector tones (944); - int nsym = 0; - int frameStarts[kMaxJttyFrames] = {}; - int const finalFlag = 1; // irrelevant to frame count, which EOM doesn't affect - genjtty_profile_ (frame.data (), &exchangeProfile, tones.data (), - &nsym, frameStarts, &finalFlag, (FCL)80); - if (nsym > 0) { - totalFrames += nsym / 59; - break; - } - if (source.length <= 1) return totalFrames; - source = Jtty::nextTransmitTextSegment (line, offset, source.length - 1); - } - offset += source.length; - } + auto const encoded = Jtty::encodeTransmitLine (line, [&] (QString const& text) { + auto frame = Jtty::transmitFrame (text).toLatin1 (); + QVector tones (944); + int nsym = 0; + int frameStarts[kMaxJttyFrames] = {}; + int const finalFlag = 1; // irrelevant to frame count, which EOM doesn't affect + genjtty_profile_ (frame.data (), &exchangeProfile, tones.data (), + &nsym, frameStarts, &finalFlag, (FCL)80); + totalFrames += nsym / 59; + return nsym > 0; + }); + if (!encoded) return 0; } return totalFrames; } @@ -475,7 +464,7 @@ void MainWindow::execute_jtty_tx(qint64 requestId, QString message, bool isFinal } int const exchangeProfile = static_cast(jttyExchangeProfile(m_config)); - // One-shot encode of text already known to fit (no retry): used for the initial non-final pass and to re-bake a line's true last segment once its real EOM status is known. + // One-shot encode; empty tones mean the text did not encode. Used for the initial non-final pass and to re-bake a line's true last segment once its real EOM status is known. auto encodeOnce = [&] (QString const& text, bool segmentIsFinal) { Jtty::TransmitSegment segment; auto frame = Jtty::transmitFrame(text).toLatin1(); @@ -494,9 +483,15 @@ void MainWindow::execute_jtty_tx(qint64 requestId, QString message, bool isFinal // Fortran gives 1-indexed columns; store 0-indexed offsets. segment.frameCharStarts.append(frameStarts[i] - 1); } + } else { + segment.tones.clear(); } return segment; }; + auto refuseUnencodable = [&] { + showStatusMessage(tr("JTTY text not sent: a line does not fit in one message once encoded; shorten it and send again")); + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); + }; QVector segments; // Newlines force a new segment; split them out before nextTransmitTextSegment (space-only breaks). @@ -504,32 +499,26 @@ void MainWindow::execute_jtty_tx(qint64 requestId, QString message, bool isFinal for (int lineIndex = 0; lineIndex < lines.size(); ++lineIndex) { auto const& line = lines[lineIndex]; int const lineStart = segments.size(); - for (int offset = 0; offset < line.size();) { - auto source = Jtty::nextTransmitTextSegment(line, offset); - if (source.text.trimmed().isEmpty()) { - offset += source.length; - continue; - } - Jtty::TransmitSegment segment; - for (;;) { - segment = encodeOnce(source.text, /*segmentIsFinal=*/false); - if (!segment.tones.isEmpty()) break; - if (source.length <= 1) { - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); - return; - } - source = Jtty::nextTransmitTextSegment(line, offset, source.length - 1); - } + auto const encoded = Jtty::encodeTransmitLine(line, [&] (QString const& text) { + auto segment = encodeOnce(text, /*segmentIsFinal=*/false); + if (segment.tones.isEmpty()) return false; segment.frequency = ui->TxFreqSpinBox_2->value(); segments.append(std::move(segment)); - offset += source.length; + return true; + }); + if (!encoded) { + refuseUnencodable(); + return; } if (segments.size() == lineStart) continue; bool const lineIsFinal = lineIndex + 1 < lines.size() || isFinal; if (!lineIsFinal) continue; auto& last = segments.last(); auto final_ = encodeOnce(last.text, /*segmentIsFinal=*/true); - Q_ASSERT (!final_.tones.isEmpty()); // same text that just succeeded above + if (final_.tones.isEmpty()) { + refuseUnencodable(); + return; + } final_.frequency = last.frequency; last = std::move(final_); } -- cgit v1.2.3