diff options
| author | Christoph Berg <myon@debian.org> | 2026-09-26 23:24:03 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2026-09-26 23:24:03 +0200 |
| commit | 059831534c7e884f0a607ed86b582fd00d821731 (patch) | |
| tree | 76bcb67a78f8aa2654fd34c2ad801a62136b0170 /tests/unit/jtty | |
| parent | d83a420f0517d7fc47aeb288a6a0cf4891784fcc (diff) | |
New upstream version 3.2.0~rc1+dfsgupstream/3.2.0_rc1+dfsg
Diffstat (limited to 'tests/unit/jtty')
27 files changed, 5745 insertions, 0 deletions
diff --git a/tests/unit/jtty/CMakeLists.txt b/tests/unit/jtty/CMakeLists.txt new file mode 100644 index 00000000..8dd698d0 --- /dev/null +++ b/tests/unit/jtty/CMakeLists.txt @@ -0,0 +1,198 @@ +add_executable (test_jtty_pack test_jtty_pack.f90) +target_include_directories (test_jtty_pack PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_pack) + +add_executable (test_jtty_source_codec test_jtty_source_codec.f90) +target_include_directories (test_jtty_source_codec PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_source_codec) +add_test (NAME test_jtty_source_codec COMMAND test_jtty_source_codec) +set_tests_properties (test_jtty_source_codec PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_source_codec: all checks passed" +) + +add_executable (test_tbcc test_tbcc.f90) +target_include_directories (test_tbcc PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_tbcc) +add_test (NAME test_tbcc COMMAND test_tbcc) +set_tests_properties (test_tbcc PROPERTIES + PASS_REGULAR_EXPRESSION "test_tbcc: all checks passed" +) + +add_executable (test_jtty_block_pow test_jtty_block_pow.f90) +target_include_directories (test_jtty_block_pow PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_block_pow) +add_test (NAME test_jtty_block_pow COMMAND test_jtty_block_pow) +set_tests_properties (test_jtty_block_pow PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_block_pow: all checks passed" +) + +add_executable (test_jtty_message_matching test_jtty_message_matching.f90) +target_include_directories (test_jtty_message_matching PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_message_matching) +add_test (NAME test_jtty_message_matching COMMAND test_jtty_message_matching) +set_tests_properties (test_jtty_message_matching PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_message_matching: all checks passed" +) + +add_executable (test_jtty_receive_state test_jtty_receive_state.f90) +target_include_directories (test_jtty_receive_state PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_receive_state) +add_test (NAME test_jtty_receive_state COMMAND test_jtty_receive_state) +set_tests_properties (test_jtty_receive_state PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_receive_state: all checks passed" +) + +add_executable (test_jtty_adjacent_decode test_jtty_adjacent_decode.f90) +target_include_directories (test_jtty_adjacent_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_adjacent_decode) +add_test (NAME test_jtty_adjacent_decode COMMAND test_jtty_adjacent_decode) +# These decoder tests are compute-heavy under ARM emulation. Their timeouts +# include headroom for hosted-runner variability. +set_tests_properties (test_jtty_adjacent_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_adjacent_decode: all checks passed" + TIMEOUT 180 +) + +add_executable (test_jtty_structured_decode + test_jtty_structured_decode.f90 + jtty_cpp_n1mm_smoke.cpp) +target_include_directories (test_jtty_structured_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_structured_decode) +target_link_libraries (test_jtty_structured_decode PRIVATE Qt5::Core) +add_test (NAME test_jtty_structured_decode COMMAND test_jtty_structured_decode) +set_tests_properties (test_jtty_structured_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_structured_decode: all checks passed" + TIMEOUT 240 +) + +add_executable (test_jtty_overlap_decode test_jtty_overlap_decode.f90) +target_include_directories (test_jtty_overlap_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_overlap_decode) +add_test (NAME test_jtty_overlap_decode COMMAND test_jtty_overlap_decode) +set_tests_properties (test_jtty_overlap_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_overlap_decode: all checks passed" + TIMEOUT 180 +) + +add_test (NAME test_jtty_overlap_decode_480 COMMAND test_jtty_overlap_decode 480) +set_tests_properties (test_jtty_overlap_decode_480 PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_overlap_decode: all checks passed" + TIMEOUT 240 +) + +add_executable (test_jtty_sticky_retry test_jtty_sticky_retry.f90) +target_include_directories (test_jtty_sticky_retry PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_sticky_retry) +add_test (NAME test_jtty_sticky_retry COMMAND test_jtty_sticky_retry) +set_tests_properties (test_jtty_sticky_retry PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_sticky_retry: all checks passed" + TIMEOUT 60 +) + +add_executable (test_jtty_windowed_decode test_jtty_windowed_decode.f90) +target_include_directories (test_jtty_windowed_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_windowed_decode) +add_test (NAME test_jtty_windowed_decode COMMAND test_jtty_windowed_decode) +set_tests_properties (test_jtty_windowed_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_windowed_decode: all checks passed" + TIMEOUT 180 +) + +add_executable (test_jtty_gap_merge test_jtty_gap_merge.f90) +target_include_directories (test_jtty_gap_merge PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_gap_merge) +add_test (NAME test_jtty_gap_merge COMMAND test_jtty_gap_merge) +set_tests_properties (test_jtty_gap_merge PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_gap_merge: all checks passed" + TIMEOUT 180 +) + +configure_file(${CMAKE_SOURCE_DIR}/tests/fixtures/jtty/jtty_msgs.txt "${CMAKE_CURRENT_BINARY_DIR}/jtty_msgs.txt" COPYONLY) + +add_test (NAME test_jtty_pack COMMAND test_jtty_pack) +set_tests_properties (test_jtty_pack PROPERTIES + WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" + PASS_REGULAR_EXPRESSION "^ 3 3 67 14 NOW IS THE TIME FOR ALL GOOD MEN TO COME TO THE AID OF THEIR PARTY\.;^ 3 3 52 11 THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG, TWICE\.;\nTotal messages: 36 Number of errors: 0\n$" +) + +add_executable (test_jtty_frequency_window test_jtty_frequency_window.f90) +wsjt_link_common_fortran (test_jtty_frequency_window) +add_test (NAME test_jtty_frequency_window COMMAND test_jtty_frequency_window) + +add_executable (test_jtty_surface_ranges test_jtty_surface_ranges.f90) +wsjt_link_common_fortran (test_jtty_surface_ranges) +add_test (NAME test_jtty_surface_ranges COMMAND test_jtty_surface_ranges) +set_tests_properties (test_jtty_surface_ranges PROPERTIES TIMEOUT 180) + +add_executable (test_jtty_get_updates test_jtty_get_updates.f90) +target_include_directories (test_jtty_get_updates PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_get_updates) +add_test (NAME test_jtty_get_updates COMMAND test_jtty_get_updates) +set_tests_properties (test_jtty_get_updates PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_get_updates: all checks passed" +) + +add_executable (test_jtty_txstream + test_jtty_txstream.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp + ${CMAKE_SOURCE_DIR}/Modulator/JttyPcmFifo.cpp + ${CMAKE_SOURCE_DIR}/Audio/TxAudioQueue.cpp + ${CMAKE_SOURCE_DIR}/Modulator/JttyTxStream.cpp + ${CMAKE_SOURCE_DIR}/Audio/soundout.cpp) +target_link_libraries (test_jtty_txstream wsjt_qt Boost::log_setup Qt5::Test Qt5::Multimedia) +add_test (NAME test_jtty_txstream COMMAND test_jtty_txstream) +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_jtty_txstream PROPERTIES + ENVIRONMENT + "QT_QPA_PLATFORM=offscreen;TSAN_OPTIONS=${wsjt_tsan_gui_options}") +endif () + +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_n1mm test_jtty_n1mm.cpp) +target_link_libraries (test_jtty_n1mm Qt5::Test) +add_test (NAME test_jtty_n1mm COMMAND test_jtty_n1mm) + +add_executable (test_mmttyif + test_mmttyif.cpp + ${CMAKE_SOURCE_DIR}/widgets/MMTTYIF.cpp +) +target_link_libraries (test_mmttyif Qt5::Test Qt5::Network) +add_test (NAME test_mmttyif COMMAND test_mmttyif) +# Connection setup may retry for several seconds on slow Windows runners. +set_tests_properties (test_mmttyif PROPERTIES TIMEOUT 30) + +add_executable (test_jtty_tbcc_list_decoder test_jtty_tbcc_list_decoder.f90) +wsjt_link_common_fortran (test_jtty_tbcc_list_decoder) +add_test (NAME test_jtty_tbcc_list_decoder COMMAND test_jtty_tbcc_list_decoder) + +add_executable (test_jtty_tbcc_decoder test_jtty_tbcc_decoder.f90) +wsjt_link_common_fortran (test_jtty_tbcc_decoder) +add_test (NAME test_jtty_tbcc_decoder COMMAND test_jtty_tbcc_decoder) + +add_executable (test_jtty_tbcc_code_profile test_jtty_tbcc_code_profile.f90) +wsjt_link_common_fortran (test_jtty_tbcc_code_profile) +add_test (NAME test_jtty_tbcc_code_profile COMMAND test_jtty_tbcc_code_profile) + +add_executable (test_jtty_payload_correlators test_jtty_payload_correlators.f90) +wsjt_link_common_fortran (test_jtty_payload_correlators) +add_test (NAME test_jtty_payload_correlators COMMAND test_jtty_payload_correlators) + +add_executable (test_jtty_replay_ownership + test_jtty_replay_ownership.cpp + ${CMAKE_SOURCE_DIR}/DecDataMutex.cpp) +target_link_libraries (test_jtty_replay_ownership + Qt5::Core Qt5::Test) +add_test (NAME test_jtty_replay_ownership COMMAND test_jtty_replay_ownership) +set_tests_properties (test_jtty_replay_ownership PROPERTIES + TIMEOUT 30 LABELS "receive-handoff;jtty-replay") +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_jtty_replay_ownership PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66") +endif () diff --git a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp new file mode 100644 index 00000000..1d666113 --- /dev/null +++ b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp @@ -0,0 +1,78 @@ +#include "widgets/JttyN1mm.hpp" +#include "wsjtx_config.h" + +#include <algorithm> +#include <array> + +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" int jtty_cpp_n1mm_smoke (int tones[], int* nsym) +{ + auto const compiled = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:CALL_EXCH]] W9XYZ 32D EMA"), + Jtty::NativeExchangeProfile::FieldDay); + *nsym = 0; + int status = static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + if (compiled.isNative ()) { + genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), + tones, nsym, &status); + } + return status; +} + +extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[], int chained) +{ + Jtty::NativeMacroContext const context {QStringLiteral ("K1ABC"), {}, 0}; + auto const compiled = Jtty::compileNativeMacro ( + 1, Jtty::nativeMacroTemplate (1), context); + *nsym = 0; + int status = static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + if (compiled.isNative ()) { + auto const frame = Jtty::transmitFrame (compiled.text, chained != 0).toLatin1 (); + std::copy (frame.cbegin (), frame.cend (), text); + genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), + tones, nsym, &status); + } + return status; +} + +extern "C" int jtty_cpp_rtty_smoke (int tones[], int* nsym) +{ + Jtty::NativeMacroContext context { + QStringLiteral ("K1ABC"), {}, 1, Jtty::NativeExchangeProfile::RttyRoundup, + QStringLiteral ("DX")}; + *nsym = 0; + int status = static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + std::array<int, 16 * 59> packedTones {}; + struct Example {int serial; QString raw; QString canonical;}; + std::array<Example, 3> const examples {{ + {1, QStringLiteral ("599 001"), QStringLiteral ("599 001")}, + {5, QStringLiteral ("599 05"), QStringLiteral ("599 005")}, + {123, QStringLiteral ("599 0123"), QStringLiteral ("599 123")}}}; + for (auto const& example : examples) { + context.serialNumber = example.serial; + auto const compiled = Jtty::compileNativeMacro (8, Jtty::nativeMacroTemplate (8), context); + if (!compiled.isNative () || compiled.text != example.canonical) { + return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + } + genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), tones, nsym, &status); + if (status != static_cast<int> (Jtty::NativeEncodeStatus::Ok) || *nsym <= 0) return status; + auto text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + int packedSymbols {}; + auto profile = static_cast<int> (context.exchangeProfile); + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, text.size ()); + if (packedSymbols != *nsym || !std::equal (tones, tones + *nsym, packedTones.cbegin ()) || + text != Jtty::transmitFrame (example.canonical, false).toLatin1 ()) { + return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + } + text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + profile = static_cast<int> (Jtty::NativeExchangeProfile::None); + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, text.size ()); + if (packedSymbols != 2 * *nsym || text != Jtty::transmitFrame (example.raw, false).toLatin1 ()) { + return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + } + } + return status; +} diff --git a/tests/unit/jtty/test_jtty_adjacent_decode.f90 b/tests/unit/jtty/test_jtty_adjacent_decode.f90 new file mode 100644 index 00000000..dc3e6cdd --- /dev/null +++ b/tests/unit/jtty/test_jtty_adjacent_decode.f90 @@ -0,0 +1,105 @@ +program test_jtty_adjacent_decode + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + integer :: failures + + failures=0 + call run_case('CQ KA1ABC CQ','WB9XYZ TU',1,1,failures) + call run_case('WB9XYZ 599 0123','WB9XYZ TU CQ KA1ABC CQ',3,2,failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_adjacent_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_adjacent_decode: all checks passed' + +contains + + subroutine run_case(first_message,second_message,first_frames,second_frames, & + count) + character(len=*), intent(in) :: first_message,second_message + integer, intent(in) :: first_frames,second_frames + integer, intent(inout) :: count + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: first_tones(MAX_FRAMES*frame_symbols) + integer :: second_tones(MAX_FRAMES*frame_symbols) + integer :: first_symbols,second_symbols,first_samples,second_samples + integer :: total_samples + integer(int16), allocatable :: pcm(:) + real, allocatable :: first_wave(:),second_wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: first_input,second_input + + call discard_pending_updates() + first_input=first_message + second_input=second_message + call genjtty(first_input,first_tones,first_symbols) + call genjtty(second_input,second_tones,second_symbols) + call expect(first_symbols.eq.first_frames*frame_symbols, & + 'the first message has the expected frame count',count) + call expect(second_symbols.eq.second_frames*frame_symbols, & + 'the second message has the expected frame count',count) + + first_samples=first_symbols*nsps + second_samples=second_symbols*nsps + total_samples=first_samples+second_samples+frame_symbols*nsps + allocate(first_wave(first_samples),second_wave(second_samples)) + allocate(complex_wave(max(first_samples,second_samples))) + allocate(pcm(total_samples)) + + call gen_jttywave(first_tones,first_symbols,nsps,2.0,12000.0,1500.0, & + complex_wave,first_wave,0,first_samples) + call gen_jttywave(second_tones,second_symbols,nsps,2.0,12000.0,1500.0, & + complex_wave,second_wave,0,second_samples) + pcm=0_int16 + pcm(1:first_samples)=int(nint(30000.0*first_wave),int16) + pcm(first_samples+1:first_samples+second_samples)= & + int(nint(30000.0*second_wave),int16) + + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,50.0) + + call expect(npending.eq.2,'the decoder keeps two adjacent messages',count) + if(npending.eq.2) then + call expect(trim(normalized(pending_updates(1)%decoded)).eq.trim(first_message), & + 'the first decoded text is retained in order',count) + call expect(trim(normalized(pending_updates(2)%decoded)).eq.trim(second_message), & + 'the second decoded text is retained in order',count) + call expect(pending_updates(1)%complete, & + 'the first message reaches end of message',count) + call expect(pending_updates(2)%complete, & + 'the second message reaches end of message',count) + endif + + deallocate(pcm,first_wave,second_wave,complex_wave) + end subroutine run_case + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_adjacent_decode diff --git a/tests/unit/jtty/test_jtty_block_pow.f90 b/tests/unit/jtty/test_jtty_block_pow.f90 new file mode 100644 index 00000000..e4366970 --- /dev/null +++ b/tests/unit/jtty/test_jtty_block_pow.f90 @@ -0,0 +1,144 @@ +program test_jtty_block_pow + + ! Focused tests for coherent block detection (lib/jtty/jtty_block_pow.f90), + ! used as a fallback by jtty_mdecode.f90's decode_and_merge when ordinary + ! blocksize-1 (single-symbol) detection fails to decode a candidate. + + use, intrinsic :: iso_fortran_env, only: real32, int32 + use jtty_fec ! re-exports tbcc's public API: TOTAL_K, PAYLOAD_BITS, + ! tbcc_init, tbcc_encode, tbcc_wava_fsk_decode + implicit none + + call expect_block_roundtrip_and_phase_invariance() + call expect_block_detection_rescues_a_misleading_symbol() + call expect_clean_signal_unaffected_by_block_detection() + + print *, 'test_jtty_block_pow: all checks passed' + +contains + + subroutine expect_block_roundtrip_and_phase_invariance() + ! Noiseless round trip through jtty_block_pow at iblock=2 and iblock=4, + ! then through tbcc_wava_fsk_decode, at an arbitrary global carrier + ! phase -- block detection must not need to know absolute phase, only + ! stay coherent within each short block, so the result must not depend + ! on this offset. + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS) + integer(int32) :: tone_symbols(TOTAL_K) + complex(real32) :: z(0:3, TOTAL_K), phase + real(real32) :: pow_block(0:3, TOTAL_K) + logical :: success + integer :: i, t, iblk + + call tbcc_init(9) + + do i = 1, PAYLOAD_BITS + payload(i) = mod(i, 2) + end do + payload(JTTY_RESERVED_BIT) = 0 ! reserved_zero_bit requires this below + call tbcc_encode(payload, tone_symbols) + + phase = cmplx(cos(0.7_real32), sin(0.7_real32), real32) ! arbitrary global carrier phase + z = cmplx(0.0_real32, 0.0_real32, real32) + do t = 1, TOTAL_K + z(tone_symbols(t), t) = phase + end do + + do iblk = 2, 4, 2 + call jtty_block_pow(z, TOTAL_K, iblk, pow_block) + call tbcc_wava_fsk_decode(pow_block, 4, 2, & + decoded, success, reserved_zero_bit=JTTY_RESERVED_BIT) + if (.not. success) then + print *, 'test_jtty_block_pow: noiseless block decode failed, iblock=', iblk + error stop 1 + end if + if (any(decoded /= payload)) then + print *, 'test_jtty_block_pow: noiseless block decode mismatch, iblock=', iblk + error stop 1 + end if + end do + end subroutine expect_block_roundtrip_and_phase_invariance + + subroutine expect_block_detection_rescues_a_misleading_symbol() + ! A minimal, hand-verified 2-symbol block where blocksize-1 detection + ! picks the WRONG tone at position 1 (tone 1's raw |z|^2 = 1.1025 + ! exceeds tone 0's |z|^2 = 1.0 there), but tone 1's value is phase- + ! rotated 120 degrees away from the block's coherent reference (the + ! phase shared by position 1's correct tone and position 2's tone). + ! Coherently summing across the block must favor the true sequence + ! (tone 0 @ position 1, tone 2 @ position 2) despite tone 1's larger + ! single-symbol magnitude, because it doesn't add constructively: + ! |z(0,1)+z(2,2)|^2 = |1.0+1.0|^2 = 4.0 + ! |z(1,1)+z(2,2)|^2 = |1.05*exp(i*2pi/3)+1.0|^2 ~= 1.05 + ! This is the actual mechanism block detection is meant to exploit -- + ! not merely averaging out noise, but that a misleading single-symbol + ! reading doesn't survive being coherently combined with its neighbor. + complex(real32) :: z(0:3, 2) + real(real32) :: pow_block(0:3, 2) + real(real32) :: twopi, pow1_correct, pow1_wrong + + twopi = 8.0_real32*atan(1.0_real32) + + z = cmplx(0.0_real32, 0.0_real32, real32) + z(0,1) = cmplx(1.0_real32, 0.0_real32, real32) ! correct tone, position 1 + z(1,1) = 1.05_real32 * cmplx(cos(twopi/3.0_real32), & + sin(twopi/3.0_real32), real32) ! misleading tone, position 1 + z(2,2) = cmplx(1.0_real32, 0.0_real32, real32) ! correct tone, position 2 + + pow1_correct = real(z(0,1)*conjg(z(0,1))) + pow1_wrong = real(z(1,1)*conjg(z(1,1))) + if (.not. (pow1_wrong > pow1_correct)) then + print *, 'test_jtty_block_pow: test setup error -- expected tone 1 to look', & + ' stronger than tone 0 at blocksize 1' + error stop 1 + end if + + call jtty_block_pow(z, 2, 2, pow_block) + + if (.not. (pow_block(0,1) > pow_block(1,1))) then + print *, 'test_jtty_block_pow: block detection failed to rescue the', & + ' misleading symbol at position 1' + error stop 1 + end if + if (maxloc(pow_block(:,1),dim=1)-1 /= 0) then + print *, 'test_jtty_block_pow: block-detected tone at position 1 is not the correct one' + error stop 1 + end if + if (maxloc(pow_block(:,2),dim=1)-1 /= 2) then + print *, 'test_jtty_block_pow: block-detected tone at position 2 is not the correct one' + error stop 1 + end if + end subroutine expect_block_detection_rescues_a_misleading_symbol + + subroutine expect_clean_signal_unaffected_by_block_detection() + ! Non-regression: on an unambiguous, noiseless signal, blocksize-2 and + ! blocksize-4 detection must pick exactly the same tone at every + ! position as blocksize-1 already does -- block detection is a fallback + ! that should never second-guess an already-clean reading. + integer(int32) :: tone_symbols(TOTAL_K) + complex(real32) :: z(0:3, TOTAL_K) + real(real32) :: pow_block(0:3, TOTAL_K) + integer :: i, t, iblk + + do t = 1, TOTAL_K + tone_symbols(t) = mod(t, 4) ! deterministic, exercises all 4 tones + end do + + z = cmplx(0.0_real32, 0.0_real32, real32) + do t = 1, TOTAL_K + z(tone_symbols(t), t) = cmplx(1.0_real32, 0.0_real32, real32) + end do + + do iblk = 2, 4, 2 + call jtty_block_pow(z, TOTAL_K, iblk, pow_block) + do i = 1, TOTAL_K + if (maxloc(pow_block(:,i),dim=1)-1 /= tone_symbols(i)) then + print *, 'test_jtty_block_pow: clean-signal regression at position', i, & + ' iblock=', iblk + error stop 1 + end if + end do + end do + end subroutine expect_clean_signal_unaffected_by_block_detection + +end program test_jtty_block_pow diff --git a/tests/unit/jtty/test_jtty_draft_acceptance.cpp b/tests/unit/jtty/test_jtty_draft_acceptance.cpp new file mode 100644 index 00000000..f321aaf5 --- /dev/null +++ b/tests/unit/jtty/test_jtty_draft_acceptance.cpp @@ -0,0 +1,128 @@ +#include <QtTest> + +#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_frequency_window.f90 b/tests/unit/jtty/test_jtty_frequency_window.f90 new file mode 100644 index 00000000..897fd823 --- /dev/null +++ b/tests/unit/jtty/test_jtty_frequency_window.f90 @@ -0,0 +1,89 @@ +program test_jtty_frequency_window + use jtty_mdec, only: jtty_search_window + implicit none + + integer, parameter :: first_bin=3,last_bin=4094 + real, parameter :: df=6000.0/8192.0 + integer :: ja,jb + real :: fc + logical :: usable + + fc=1500.0 + call jtty_search_window(fc,50.0,200,2800,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'nominal window is usable') + call assert_true(fc.eq.1500.0, 'nominal center is unchanged') + call assert_true(ja.eq.int(1450.0/df), 'nominal lower bin is unchanged') + call assert_true(jb.eq.int(1550.0/df), 'nominal upper bin is unchanged') + + fc=2500.0 + call jtty_search_window(fc,1000.0,0,5000,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'partially overlapping upper window is usable') + call assert_true(ja.eq.int(1500.0/df), 'partial upper window keeps its lower bin') + call assert_true(jb.eq.last_bin, 'partial upper window is clipped to the spectrum') + + fc=5000.0 + call jtty_search_window(fc,1000.0,0,5000,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(.not.usable, 'window above the spectrum is rejected') + + fc=1500.0 + call jtty_search_window(fc,20.0,4900,5000,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(fc.eq.4900.0, 'center is clamped to the graph lower edge') + call assert_true(.not.usable, 'graph above the spectrum is rejected') + + fc=1500.0 + call jtty_search_window(fc,20.0,4900,5000,.false.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'QSO window ignores an unrelated graph range') + call assert_true(fc.eq.1500.0, 'QSO center is not moved to the graph edge') + call assert_true(ja.eq.int(1480.0/df), 'QSO lower bin follows Rx tolerance') + call assert_true(jb.eq.int(1520.0/df), 'QSO upper bin follows Rx tolerance') + + fc=1500.0 + call jtty_search_window(fc,20.0,1800,1200,.false.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'QSO window ignores inverted graph limits') + call assert_true(fc.eq.1500.0, 'inverted graph limits do not move QSO center') + + fc=1350.0 + call jtty_search_window(fc,150.0,1400,1600,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'lower auxiliary edge is usable') + call assert_true(fc.eq.1400.0, 'lower auxiliary center is clamped') + call assert_true(ja.eq.ceiling(1400.0/df), 'lower graph edge clips the window') + + fc=1650.0 + call jtty_search_window(fc,150.0,1400,1600,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'upper auxiliary edge is usable') + call assert_true(fc.eq.1600.0, 'upper auxiliary center is clamped') + call assert_true(jb.eq.floor(1600.0/df), 'upper graph edge clips the window') + + fc=1500.0 + call jtty_search_window(fc,50.0,1800,1200,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(.not.usable, 'inverted graph limits are rejected') + + fc=1500.0 + call jtty_search_window(fc,-1.0,200,2800,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(.not.usable, 'negative window width is rejected') + + print *, 'JTTY frequency window tests passed' + +contains + + subroutine assert_true(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + write(*,'(a)') message + error stop 1 + endif + end subroutine assert_true + +end program test_jtty_frequency_window diff --git a/tests/unit/jtty/test_jtty_gap_merge.f90 b/tests/unit/jtty/test_jtty_gap_merge.f90 new file mode 100644 index 00000000..ff13e28e --- /dev/null +++ b/tests/unit/jtty/test_jtty_gap_merge.f90 @@ -0,0 +1,135 @@ +program test_jtty_gap_merge + + ! When a frame in the middle of a multi-frame message fails to decode + ! (common at marginal SNR), the message must still remain one message with + ! a gap marker between the surviving fragments, not split into two + ! messages (the bug Joe reported on 000000_000011.wav: "THE QUICK BROWN FOX + ! JUMPED OVER THE LAZY DOG." decoded as two separate lines, "THE Q" and + ! "BROWN FOX JUMPED OVER THE LAZY DOG.", losing "UICK " with no trace). + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + character(len=*), parameter :: msg='THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.' + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: failures,total_samples,nframes + integer(int16), allocatable :: reference_pcm(:) + + failures=0 + + call build_message_pcm(msg,reference_pcm,total_samples,nframes) + call run_dropped_frame_case(msg,reference_pcm,total_samples,nframes,1,failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_gap_merge: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_gap_merge: all checks passed' + +contains + + subroutine build_message_pcm(message,pcm,total_samples,nframes) + character(len=*), intent(in) :: message + integer(int16), allocatable, intent(out) :: pcm(:) + integer, intent(out) :: total_samples,nframes + integer :: tones(MAX_FRAMES*frame_symbols) + integer :: nsymbols + real, allocatable :: wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: input + + input=message + call genjtty(input,tones,nsymbols) + nframes=nsymbols/frame_symbols + total_samples=(nsymbols+frame_symbols)*nsps + allocate(wave(nsymbols*nsps),complex_wave(nsymbols*nsps),pcm(total_samples)) + call gen_jttywave(tones,nsymbols,nsps,2.0,12000.0,1500.0, & + complex_wave,wave,0,nsymbols*nsps) + pcm=0_int16 + pcm(1:nsymbols*nsps)=int(nint(30000.0*wave),int16) + end subroutine build_message_pcm + + ! Drops consecutive middle frames and confirms the message still merges + ! into one slot with a fixed-width gap marker. + subroutine run_dropped_frame_case(expected_text,reference_pcm, & + total_samples,nframes,n_dropped,count) + character(len=*), intent(in) :: expected_text + integer(int16), intent(in) :: reference_pcm(:) + integer, intent(in) :: total_samples,nframes,n_dropped + integer, intent(inout) :: count + integer :: idrop + integer :: drop_start,drop_end + integer(int16), allocatable :: pcm(:) + character(len=80) :: before,after + character(len=200) :: description + integer :: gap_pos + logical :: surviving_text_matches + + pcm=reference_pcm + idrop=nframes/2 + + ! Zero out idrop..idrop+n_dropped-1's audio so those frames can't sync. + drop_start=(idrop-1)*frame_symbols*nsps+1 + drop_end=(idrop+n_dropped-1)*frame_symbols*nsps + pcm(drop_start:drop_end)=0_int16 + + call discard_pending_updates() + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,50.0) + + write(description,'(a,i0,a)') 'dropping ',n_dropped, & + ' consecutive frame(s) still merges into one message' + call expect(npending.eq.1,trim(description),count) + if(npending.ne.1) return + + ! The gap sentinel is a fixed-width 5-tilde run regardless of how many + ! frames were actually dropped -- " ... " is a generic "something's + ! missing" marker, not a precise character count (matches Joe's own + ! suggested display). + gap_pos=index(pending_updates(1)%decoded,'~~~~~') + write(description,'(a,i0,a)') 'dropping ',n_dropped, & + ' consecutive frame(s) leaves a gap sentinel' + call expect(gap_pos.gt.0,trim(description),count) + if(gap_pos.le.0) return + + before=trim(normalized(adjustl(pending_updates(1)%decoded(1:gap_pos-1)))) + after=trim(normalized(adjustl(pending_updates(1)%decoded(gap_pos+5:)))) + write(description,'(a,i0,a)') 'dropping ',n_dropped, & + ' consecutive frame(s): surviving text matches the original message' + surviving_text_matches=.false. + if(len_trim(before).gt.0 .and. len_trim(after).gt.0 .and. & + len_trim(after).le.len_trim(expected_text)) then + surviving_text_matches=index(expected_text,trim(before)).eq.1 .and. & + expected_text(len_trim(expected_text)-len_trim(after)+1: & + len_trim(expected_text)).eq.trim(after) + endif + call expect(surviving_text_matches,trim(description),count) + end subroutine run_dropped_frame_case + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_gap_merge diff --git a/tests/unit/jtty/test_jtty_get_updates.f90 b/tests/unit/jtty/test_jtty_get_updates.f90 new file mode 100644 index 00000000..0ecf61dc --- /dev/null +++ b/tests/unit/jtty/test_jtty_get_updates.f90 @@ -0,0 +1,113 @@ +program test_jtty_get_updates + use iso_fortran_env, only: int64 + use jtty_mdec, only: message_assembly,npending,discard_pending_updates, & + queue_message_update + implicit none + + integer, parameter :: BATCH_SIZE=30,TEXT_WIDTH=80 + character(len=BATCH_SIZE*TEXT_WIDTH) :: text_blocks + integer(int64) :: message_ids(BATCH_SIZE) + real :: frequencies(BATCH_SIZE),start_tsync(BATCH_SIZE) + logical*1 :: eom(BATCH_SIZE) + type(message_assembly) :: message + integer :: i,count + + call discard_pending_updates() + + message=make_message(41_int64,1500.4,1.25,'CQ K1ABC') + 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 expect(count.eq.1 .and. npending.eq.0, & + 'retrieving an update drains it exactly once') + call expect(message_ids(1).eq.41_int64 .and. & + trim(block_text(text_blocks,1)).eq.'CQ K1ABC FN20', & + 'the batch contains the newest state and stable identity') + 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(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 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') + + do i=1,35 + message=make_message(int(100+i,int64),1400.0+real(i), & + 10.0+real(i),'MESSAGE') + write(message%decoded,'(a,i0)') 'MESSAGE ',i + message%k=len_trim(message%decoded) + call queue_message_update(message,mod(i,2).eq.0) + enddo + 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 expect(count.eq.BATCH_SIZE .and. npending.eq.5, & + 'the first batch drains the oldest thirty updates') + do i=1,BATCH_SIZE + call expect(message_ids(i).eq.int(100+i,int64), & + 'the first batch preserves update order') + call expect(abs(frequencies(i)-(1400.0+real(i))).lt.0.001 .and. & + abs(start_tsync(i)-(10.0+real(i))).lt.0.001, & + 'the first batch preserves numeric metadata') + call expect(eom(i) .eqv. (mod(i,2).eq.0), & + 'the first batch preserves completion state') + enddo + + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(count.eq.5 .and. npending.eq.0, & + 'a second batch drains every remaining update') + do i=1,5 + call expect(message_ids(i).eq.int(130+i,int64), & + 'the second batch continues in update order') + enddo + + print *, 'test_jtty_get_updates: all checks passed' + +contains + + function make_message(id,frequency,tsync,text) result(value) + integer(int64), intent(in) :: id + real, intent(in) :: frequency,tsync + character(len=*), intent(in) :: text + type(message_assembly) :: value + + value%message_id=id + value%f1=frequency + value%tsync=tsync + value%start_tsync=tsync + value%decoded=text + value%k=len_trim(value%decoded) + end function make_message + + function block_text(blocks,index) result(text) + character(len=*), intent(in) :: blocks + integer, intent(in) :: index + character(len=TEXT_WIDTH) :: text + integer :: first + + first=(index-1)*TEXT_WIDTH+1 + text=blocks(first:first+TEXT_WIDTH-1) + end function block_text + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + write(*,'(a)') message + error stop 1 + endif + end subroutine expect + +end program test_jtty_get_updates diff --git a/tests/unit/jtty/test_jtty_message_matching.f90 b/tests/unit/jtty/test_jtty_message_matching.f90 new file mode 100644 index 00000000..1308009a --- /dev/null +++ b/tests/unit/jtty/test_jtty_message_matching.f90 @@ -0,0 +1,99 @@ +program test_jtty_message_matching + use jtty_mdec, only: decode,message_assembly,classify_active_candidate + implicit none + + real, parameter :: frame_period=2.0 + type(message_assembly) :: existing + type(decode) :: candidate + logical :: match,is_window_dupe + integer :: failures,nframes_gap + + failures=0 + existing%f1=1500.0 + existing%tsync=10.0 + existing%decoded='OPEN MESSAGE' + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+frame_period + candidate%decoded='CONTINUATION' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe .and. nframes_gap.eq.1, & + 'an active message accepts the next frame',failures) + + candidate%f1=1505.0 + candidate%tsync=existing%tsync+frame_period/4.0 + candidate%decoded='SHIFTED REDISCOVERY' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. is_window_dupe, & + 'an active message rejects a quarter-frame rediscovery',failures) + + candidate%f1=1505.0 + candidate%tsync=existing%tsync+frame_period + candidate%decoded='WIDE CONTINUATION' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe, & + 'an active message accepts a 5 Hz next frame',failures) + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+2*frame_period + candidate%decoded='ONE MISSED FRAME' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe .and. nframes_gap.eq.2, & + 'an active message bridges one missed frame',failures) + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+3*frame_period + candidate%decoded='TWO MISSED FRAMES' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe .and. nframes_gap.eq.3, & + 'an active message bridges two missed frames',failures) + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+4*frame_period + candidate%decoded='THREE MISSED FRAMES' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(.not.match, & + 'an active message does not bridge beyond the continuation limit', & + failures) + + candidate%f1=1505.0 + candidate%tsync=existing%tsync+3*frame_period/4.0 + candidate%decoded='LAST RETRO STEP' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. is_window_dupe, & + 'the final actual retro step is classified as rediscovery',failures) + + candidate%tsync=existing%tsync+5*frame_period/4.0 + candidate%decoded='OUTSIDE RETRO HORIZON' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(.not.match, & + 'a later quarter-phase frame is not mistaken for rediscovery',failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_message_matching: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_message_matching: all checks passed' + +contains + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_message_matching diff --git a/tests/unit/jtty/test_jtty_messages.cpp b/tests/unit/jtty/test_jtty_messages.cpp new file mode 100644 index 00000000..7c38dfa4 --- /dev/null +++ b/tests/unit/jtty/test_jtty_messages.cpp @@ -0,0 +1,938 @@ +#include <QtTest> + +#include "widgets/JttyMessages.hpp" + +class TestJttyMessages final + : public QObject +{ + Q_OBJECT + +private slots: + void nativeMacroMappings () + { + Jtty::NativeMacroContext const context {QString {"k1abc"}, QString {"w9xyz"}, 7}; + + struct Expected + { + QString text; + QVector<int> kinds; + QVector<int> subtypes; + QVector<QString> calls; + }; + QVector<Expected> const expected { + {QString {"CQ K1ABC CQ"}, {0}, {0}, {QString {"K1ABC"}}}, + {QString {"W9XYZ 599 007"}, {0, 1}, {1, 0}, {QString {"W9XYZ"}, QString {}}}, + {QString {"W9XYZ TU CQ K1ABC CQ"}, {0, 0}, {3, 0}, + {QString {"W9XYZ"}, QString {"K1ABC"}}}, + {QString {"K1ABC"}, {0}, {1}, {QString {"K1ABC"}}}, + {QString {"W9XYZ"}, {0}, {1}, {QString {"W9XYZ"}}}, + {QString {"TU NOW W9XYZ 599 007"}, {0, 1}, {5, 0}, + {QString {"W9XYZ"}, QString {}}}, + {QString {"W9XYZ AGN?"}, {0}, {4}, {QString {"W9XYZ"}}}, + {QString {"599 007"}, {1}, {0}, {QString {}}} + }; + + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + auto const compiled = Jtty::compileNativeMacro ( + functionKey, Jtty::nativeMacroTemplate (functionKey), context); + auto const& wanted = expected.at (functionKey - 1); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, wanted.text); + QCOMPARE (compiled.atoms.size (), wanted.kinds.size ()); + for (int i = 0; i < compiled.atoms.size (); ++i) { + auto const& atom = compiled.atoms.at (i); + QCOMPARE (int {atom.kind}, wanted.kinds.at (i)); + QCOMPARE (int {atom.subtype}, wanted.subtypes.at (i)); + QCOMPARE (int {atom.reserved}, 0); + QCOMPARE (QString::fromLatin1 (atom.text), wanted.calls.at (i)); + if (atom.kind == static_cast<qint8> (Jtty::NativeAtomKind::ExchangeNumber)) { + QCOMPARE (int {atom.role}, static_cast<int> (Jtty::ExchangeRole::Full)); + QCOMPARE (atom.value, qint32 {7}); + } else { + QCOMPARE (int {atom.role}, 0); + QCOMPARE (atom.value, qint32 {0}); + } + } + } + } + + void nativeMacroMatchesCaseAndWhitespaceBeforeExpansion () + { + Jtty::NativeMacroContext const context {QString {" k1abc "}, QString {" w9xyz "}, 42}; + auto const compiled = Jtty::compileNativeMacro ( + 3, QString {" \t%h tu\n cq %m cq "}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, QString {"W9XYZ TU CQ K1ABC CQ"}); + QCOMPARE (compiled.atoms.size (), 2); + QCOMPARE (QString::fromLatin1 (compiled.atoms.at (0).text), QString {"W9XYZ"}); + QCOMPARE (QString::fromLatin1 (compiled.atoms.at (1).text), QString {"K1ABC"}); + } + + void customizedMacroFallsBackToExpandedLiteral () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 7}; + auto const customized = Jtty::compileNativeMacro ( + 2, QString {"TEST %H 599 %N"}, context); + QCOMPARE (customized.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (customized.text, QString {"TEST W9XYZ 599 007"}); + QVERIFY (customized.atoms.isEmpty ()); + + auto const movedDefault = Jtty::compileNativeMacro ( + 4, QString {"%H"}, context); + QCOMPARE (movedDefault.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (movedDefault.text, QString {"W9XYZ"}); + QCOMPARE (movedDefault.atoms.size (), 1); + QCOMPARE (int {movedDefault.atoms.at (0).subtype}, + static_cast<int> (Jtty::CallAction::Call)); + + auto const unknownPlaceholder = Jtty::compileNativeMacro ( + 8, QString {"599 %R"}, context); + QCOMPARE (unknownPlaceholder.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (unknownPlaceholder.text, QString {"599 %R"}); + + auto const editedLegacyCase = Jtty::compileNativeMacro ( + 2, QString {"%h 599 %n"}, context); + QCOMPARE (editedLegacyCase.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (editedLegacyCase.text, QString {"%h 599 %n"}); + + auto const editedLegacySpacing = Jtty::compileNativeMacro ( + 8, QString {" 599 %N "}, context); + QCOMPARE (editedLegacySpacing.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (editedLegacySpacing.text, QString {" 599 007 "}); + } + + void blankMacroDoesNotSelectNativeCq () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 7}; + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + for (QString const& macro : {QString {}, QString {" \t "}}) { + auto const compiled = Jtty::compileNativeMacro (functionKey, macro, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::LiteralFallback); + QVERIFY (compiled.atoms.isEmpty ()); + QVERIFY (compiled.text.trimmed ().isEmpty ()); + } + } + } + + void nativeCallDescriptorTextIsBounded () + { + auto const atom = Jtty::nativeCallAtom ( + Jtty::CallAction::Call, QStringLiteral ("K1ABCDEFGHIJK")); + QCOMPARE (QString::fromLatin1 (atom.text), QStringLiteral ("K1ABCDEF")); + } + + void recognizedMacroRejectsInvalidRuntime_data () + { + QTest::addColumn<int> ("functionKey"); + QTest::addColumn<QString> ("myCall"); + QTest::addColumn<QString> ("hisCall"); + QTest::addColumn<int> ("serialNumber"); + + QTest::newRow ("missing-my-call") << 1 << QString {} << QString {"W9XYZ"} << 1; + QTest::newRow ("missing-his-call") << 2 << QString {"K1ABC"} << QString {} << 1; + QTest::newRow ("call-without-area") << 4 << QString {"KABC"} << QString {"W9XYZ"} << 1; + QTest::newRow ("call-without-suffix") << 5 << QString {"K1ABC"} << QString {"W9"} << 1; + QTest::newRow ("q-prefix") << 7 << QString {"K1ABC"} << QString {"Q1ABC"} << 1; + QTest::newRow ("portable-call") << 3 << QString {"K1ABC/P"} << QString {"W9XYZ"} << 1; + QTest::newRow ("negative-serial") << 8 << QString {"K1ABC"} << QString {"W9XYZ"} << -1; + QTest::newRow ("serial-overflow") << 6 << QString {"K1ABC"} << QString {"W9XYZ"} + << (1 << 17); + } + + void recognizedMacroRejectsInvalidRuntime () + { + QFETCH (int, functionKey); + QFETCH (QString, myCall); + QFETCH (QString, hisCall); + QFETCH (int, serialNumber); + Jtty::NativeMacroContext const context {myCall, hisCall, serialNumber}; + + auto const compiled = Jtty::compileNativeMacro ( + functionKey, Jtty::nativeMacroTemplate (functionKey), context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (compiled.atoms.isEmpty ()); + QVERIFY (compiled.text.isEmpty ()); + } + + void nativeRuntimeBoundariesAndUnusedFields () + { + auto const minimum = Jtty::compileNativeMacro ( + 8, Jtty::nativeMacroTemplate (8), {QString {}, QString {}, 0}); + QCOMPARE (minimum.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (minimum.text, QString {"599 000"}); + QCOMPARE (minimum.atoms.at (0).value, qint32 {0}); + + auto const maximum = Jtty::compileNativeMacro ( + 8, Jtty::nativeMacroTemplate (8), {QString {}, QString {}, (1 << 17) - 1}); + QCOMPARE (maximum.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (maximum.text, QString {"599 131071"}); + QCOMPARE (maximum.atoms.at (0).value, qint32 {(1 << 17) - 1}); + + auto const unusedInvalidFields = Jtty::compileNativeMacro ( + 1, Jtty::nativeMacroTemplate (1), {QString {"K1ABC"}, QString {}, -1}); + QCOMPARE (unusedInvalidFields.status, Jtty::NativeMacroStatus::Native); + } + + void functionKeyApiIsParityFriendly () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 123}; + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + QString const configuredText = Jtty::nativeMacroTemplate (functionKey); + auto const keyboard = Jtty::compileNativeMacro (functionKey, configuredText, context); + auto const button = Jtty::compileNativeMacro (functionKey, configuredText, context); + QCOMPARE (keyboard.status, button.status); + QCOMPARE (keyboard.text, button.text); + QCOMPARE (keyboard.atoms.size (), button.atoms.size ()); + for (int i = 0; i < keyboard.atoms.size (); ++i) { + QCOMPARE (keyboard.atoms.at (i).kind, button.atoms.at (i).kind); + QCOMPARE (keyboard.atoms.at (i).subtype, button.atoms.at (i).subtype); + QCOMPARE (keyboard.atoms.at (i).role, button.atoms.at (i).role); + QCOMPARE (keyboard.atoms.at (i).value, button.atoms.at (i).value); + QCOMPARE (QString::fromLatin1 (keyboard.atoms.at (i).text), + QString::fromLatin1 (button.atoms.at (i).text)); + } + } + } + + void legacyAndProfileAwareTemplatesRemainNative () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 12}; + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + auto const current = Jtty::compileNativeMacro ( + functionKey, Jtty::nativeMacroTemplate (functionKey), context); + auto const legacy = Jtty::compileNativeMacro ( + functionKey, Jtty::legacyNativeMacroTemplate (functionKey), context); + QCOMPARE (current.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (legacy.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (current.text, legacy.text); + QCOMPARE (current.atoms.size (), legacy.atoms.size ()); + } + + QCOMPARE (Jtty::nativeMacroTemplate (2), QString {"%H %E"}); + QCOMPARE (Jtty::nativeMacroTemplate (6), QString {"TU NOW %Q %E"}); + QCOMPARE (Jtty::nativeMacroTemplate (8), QString {"%E"}); + } + + void savedDefaultMigrationIsExactAndNarrow () + { + for (int functionKey : {2, 6, 8}) { + QCOMPARE (Jtty::migratedNativeMacroTemplate ( + functionKey, Jtty::legacyNativeMacroTemplate (functionKey)), + Jtty::nativeMacroTemplate (functionKey)); + } + + QCOMPARE (Jtty::migratedNativeMacroTemplate (1, QString {"CQ %M CQ"}), + QString {"CQ %M CQ"}); + QCOMPARE (Jtty::migratedNativeMacroTemplate (2, QString {"%h 599 %n"}), + QString {"%h 599 %n"}); + QCOMPARE (Jtty::migratedNativeMacroTemplate (8, QString {" 599 %N "}), + QString {" 599 %N "}); + QCOMPARE (Jtty::migratedNativeMacroTemplate (8, QString {"TEST 599 %N"}), + QString {"TEST 599 %N"}); + } + + void noneProfileUsesLiveSerial () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 7, Jtty::NativeExchangeProfile::None}; + auto const compiled = Jtty::compileNativeMacro (QString {"%H %E"}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, QString {"W9XYZ 599 007"}); + QCOMPARE (compiled.atoms.size (), 2); + QCOMPARE (int {compiled.atoms.at (1).kind}, + static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber)); + QCOMPARE (int {compiled.atoms.at (1).subtype}, + static_cast<int> (Jtty::NumberKind::Serial)); + QCOMPARE (int {compiled.atoms.at (1).role}, + static_cast<int> (Jtty::ExchangeRole::Full)); + QCOMPARE (compiled.atoms.at (1).value, qint32 {7}); + } + + void fieldDayProfileParsesClassAndSection_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::addColumn<QString> ("text"); + QTest::addColumn<int> ("count"); + QTest::addColumn<int> ("classIndex"); + QTest::addColumn<QString> ("section"); + + QTest::newRow ("minimum") << QString {"1A AB"} << QString {"1A AB"} + << 1 << 0 << QString {"AB"}; + QTest::newRow ("maximum") << QString {"32F EMA"} << QString {"32F EMA"} + << 32 << 5 << QString {"EMA"}; + QTest::newRow ("normalizes-case-and-spacing") + << QString {" 2d wma "} << QString {"2D WMA"} << 2 << 3 << QString {"WMA"}; + } + + void compactFieldDayConfigurationIsNormalized () + { + QCOMPARE (Jtty::normalizedFieldDayExchange (QStringLiteral ("3AOR")), + QStringLiteral ("3A OR")); + QCOMPARE (Jtty::normalizedFieldDayExchange (QStringLiteral (" 32fema ")), + QStringLiteral ("32F EMA")); + QCOMPARE (Jtty::normalizedFieldDayExchange (QStringLiteral ("3A OR")), + QStringLiteral ("3A OR")); + + Jtty::NativeMacroContext context; + context.exchangeProfile = Jtty::NativeExchangeProfile::FieldDay; + context.configuredExchange = Jtty::normalizedFieldDayExchange ( + QStringLiteral ("3AOR")); + auto const compiled = Jtty::compileNativeMacro (QStringLiteral ("%E"), context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, QStringLiteral ("3A OR")); + } + + void fieldDayProfileParsesClassAndSection () + { + QFETCH (QString, exchange); + QFETCH (QString, text); + QFETCH (int, count); + QFETCH (int, classIndex); + QFETCH (QString, section); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::FieldDay, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, text); + QCOMPARE (compiled.atoms.size (), 1); + auto const& atom = compiled.atoms.constFirst (); + QCOMPARE (int {atom.kind}, static_cast<int> (Jtty::NativeAtomKind::ExchangePair)); + QCOMPARE (int {atom.subtype}, static_cast<int> (Jtty::PairSchema::ClassSection)); + QCOMPARE (int {atom.role}, classIndex); + QCOMPARE (atom.value, qint32 {count}); + QCOMPARE (QString::fromLatin1 (atom.text), section); + } + + void profileExchangeComposesWithCallActions () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 1, + Jtty::NativeExchangeProfile::FieldDay, QString {"2D WMA"}}; + + auto const reply = Jtty::compileNativeMacro (QString {"%H %E"}, context); + QCOMPARE (reply.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (reply.text, QString {"W9XYZ 2D WMA"}); + QCOMPARE (reply.atoms.size (), 2); + QCOMPARE (int {reply.atoms.at (0).kind}, static_cast<int> (Jtty::NativeAtomKind::Call)); + QCOMPARE (int {reply.atoms.at (1).kind}, + static_cast<int> (Jtty::NativeAtomKind::ExchangePair)); + + auto const queued = Jtty::compileNativeMacro (QString {"TU NOW %Q %E"}, context); + QCOMPARE (queued.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (queued.text, QString {"TU NOW W9XYZ 2D WMA"}); + QCOMPARE (queued.atoms.size (), 2); + QCOMPARE (int {queued.atoms.at (0).subtype}, + static_cast<int> (Jtty::CallAction::TuNowCall)); + QCOMPARE (int {queued.atoms.at (1).kind}, + static_cast<int> (Jtty::NativeAtomKind::ExchangePair)); + } + + void invalidFieldDayExchangeIsRejected_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::newRow ("missing") << QString {}; + QTest::newRow ("zero-count") << QString {"0A EMA"}; + QTest::newRow ("count-overflow") << QString {"33A EMA"}; + QTest::newRow ("bad-class") << QString {"1G EMA"}; + QTest::newRow ("short-section") << QString {"1A E"}; + QTest::newRow ("long-section") << QString {"1A WMAA"}; + QTest::newRow ("non-base36-section") << QString {"1A E-A"}; + QTest::newRow ("noncanonical-three-character-section") << QString {"1A 0AB"}; + } + + void invalidFieldDayExchangeIsRejected () + { + QFETCH (QString, exchange); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::FieldDay, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (!compiled.error.isEmpty ()); + QVERIFY (compiled.atoms.isEmpty ()); + } + + void rttyProfileParsesConfiguredExchange_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::addColumn<int> ("serial"); + QTest::addColumn<int> ("kind"); + QTest::addColumn<int> ("value"); + QTest::addColumn<QString> ("atomText"); + QTest::addColumn<QString> ("rendered"); + + QTest::newRow ("dx-live-serial") << QString {"DX"} << 42 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber) << 42 << QString {} + << QString {"599 042"}; + QTest::newRow ("hash-live-serial") << QString {"#"} << 1234 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber) << 1234 << QString {} + << QString {"599 1234"}; + QTest::newRow ("decimal-serial") << QString {"0013"} << 99 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber) << 13 << QString {} + << QString {"599 013"}; + QTest::newRow ("state") << QString {" ma "} << 99 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeLocation) << 0 << QString {"MA"} + << QString {"599 MA"}; + QTest::newRow ("province") << QString {"nwt"} << 99 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeLocation) << 0 << QString {"NWT"} + << QString {"599 NWT"}; + } + + void rttyProfileParsesConfiguredExchange () + { + QFETCH (QString, exchange); + QFETCH (int, serial); + QFETCH (int, kind); + QFETCH (int, value); + QFETCH (QString, atomText); + QFETCH (QString, rendered); + Jtty::NativeMacroContext const context { + QString {}, QString {}, serial, Jtty::NativeExchangeProfile::RttyRoundup, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, rendered); + auto const& atom = compiled.atoms.constFirst (); + QCOMPARE (int {atom.kind}, kind); + QCOMPARE (atom.value, qint32 {value}); + QCOMPARE (QString::fromLatin1 (atom.text), atomText); + if (kind == static_cast<int> (Jtty::NativeAtomKind::ExchangeLocation)) { + QCOMPARE (int {atom.subtype}, static_cast<int> (Jtty::LocationKind::StateProvince)); + QCOMPARE (int {atom.role}, static_cast<int> (Jtty::ExchangeRole::Full)); + } + } + + void invalidRttyExchangeIsRejected_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::newRow ("empty") << QString {}; + QTest::newRow ("one-character") << QString {"M"}; + QTest::newRow ("too-long") << QString {"NWTX"}; + QTest::newRow ("punctuation") << QString {"M-A"}; + QTest::newRow ("noncanonical-three-character-token") << QString {"0MA"}; + QTest::newRow ("decimal-overflow") << QString {"131072"}; + } + + void invalidRttyExchangeIsRejected () + { + QFETCH (QString, exchange); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 7, Jtty::NativeExchangeProfile::RttyRoundup, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (!compiled.error.isEmpty ()); + } + + void gridMacroUsesFieldOnlyAndFullRoles_data () + { + QTest::addColumn<QString> ("macro"); + QTest::addColumn<QString> ("grid"); + QTest::addColumn<int> ("role"); + QTest::addColumn<QString> ("text"); + QTest::newRow ("field-only-lower-bound") << QString {"%G"} << QString {"aa00"} + << static_cast<int> (Jtty::ExchangeRole::FieldOnly) << QString {"AA00"}; + QTest::newRow ("field-only-upper-bound") << QString {"%G"} << QString {"RR99"} + << static_cast<int> (Jtty::ExchangeRole::FieldOnly) << QString {"RR99"}; + QTest::newRow ("full") << QString {"599 %G"} << QString {"FN42"} + << static_cast<int> (Jtty::ExchangeRole::Full) << QString {"599 FN42"}; + } + + void gridMacroUsesFieldOnlyAndFullRoles () + { + QFETCH (QString, macro); + QFETCH (QString, grid); + QFETCH (int, role); + QFETCH (QString, text); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::None, QString {}, grid}; + auto const compiled = Jtty::compileNativeMacro (macro, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, text); + QCOMPARE (compiled.atoms.size (), 1); + QCOMPARE (int {compiled.atoms.constFirst ().kind}, + static_cast<int> (Jtty::NativeAtomKind::Grid4)); + QCOMPARE (int {compiled.atoms.constFirst ().role}, role); + QCOMPARE (QString::fromLatin1 (compiled.atoms.constFirst ().text), grid.toUpper ()); + } + + void callAndQueuedGridTemplatesKeepGridFieldOnly () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 1, + Jtty::NativeExchangeProfile::None, QString {}, QString {"FN42"}}; + + auto const call = Jtty::compileNativeMacro (QString {"%H %G"}, context); + QCOMPARE (call.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (call.text, QString {"W9XYZ FN42"}); + QCOMPARE (call.atoms.size (), 2); + QCOMPARE (int {call.atoms.at (1).kind}, static_cast<int> (Jtty::NativeAtomKind::Grid4)); + QCOMPARE (int {call.atoms.at (1).role}, + static_cast<int> (Jtty::ExchangeRole::FieldOnly)); + + auto const queued = Jtty::compileNativeMacro (QString {"TU NOW %Q %G"}, context); + QCOMPARE (queued.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (queued.text, QString {"TU NOW W9XYZ FN42"}); + QCOMPARE (queued.atoms.size (), 2); + QCOMPARE (int {queued.atoms.at (1).role}, + static_cast<int> (Jtty::ExchangeRole::FieldOnly)); + } + + void configuredSubsquareProducesGrid4WithoutChangingLiteralExpansion () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 1, + Jtty::NativeExchangeProfile::None, QString {}, QString {"fn42ab"}}; + auto const native = Jtty::compileNativeMacro (QString {"%H %G"}, context); + QCOMPARE (native.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (native.text, QString {"W9XYZ FN42"}); + QCOMPARE (QString::fromLatin1 (native.atoms.at (1).text), QString {"FN42"}); + + auto const literal = Jtty::compileNativeMacro (QString {"GRID %G"}, context); + QCOMPARE (literal.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (literal.text, QString {"GRID fn42ab"}); + } + + void invalidGridIsRejected_data () + { + QTest::addColumn<QString> ("grid"); + QTest::newRow ("empty") << QString {}; + QTest::newRow ("short") << QString {"AA0"}; + QTest::newRow ("field-overflow") << QString {"AS00"}; + QTest::newRow ("square-letter") << QString {"AA0A"}; + QTest::newRow ("invalid-subsquare") << QString {"FN42AZ"}; + } + + void invalidGridIsRejected () + { + QFETCH (QString, grid); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::None, QString {}, grid}; + auto const compiled = Jtty::compileNativeMacro (QString {"%G"}, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (!compiled.error.isEmpty ()); + } + + void registeredControlPhrasesCompileNatively () + { + Jtty::NativeMacroContext const context; + for (int phraseId = 0; phraseId < 18; ++phraseId) { + auto const compiled = Jtty::compileNativeMacro ( + QString {" %1 "}.arg (Jtty::controlPhrase (phraseId).toLower ()), context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, Jtty::controlPhrase (phraseId)); + QCOMPARE (compiled.atoms.size (), 1); + QCOMPARE (int {compiled.atoms.constFirst ().kind}, + static_cast<int> (Jtty::NativeAtomKind::Control)); + QCOMPARE (int {compiled.atoms.constFirst ().subtype}, phraseId); + } + } + + void customLiteralExpandsProfileFields () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 7, + 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"}); + QVERIFY (compiled.error.isEmpty ()); + } + + void prepareTransmitText_data () + { + QTest::addColumn<QString> ("message"); + QTest::addColumn<QString> ("expected"); + QTest::addColumn<bool> ("substituted"); + QTest::addColumn<bool> ("truncated"); + + QTest::newRow ("empty") << QString {} << QString {} + << false << false; + QTest::newRow ("supported") << QString {"CQ KA1ABC CQ"} << QString {"CQ KA1ABC CQ"} + << false << false; + QTest::newRow ("lowercase-preserved") << QString {"cq ka1abc cq"} << QString {"cq ka1abc cq"} + << 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; + QTest::newRow ("nul") << (QString {"A"} + QChar::Null + QString {"B"}) << QString {"A B"} + << true << false; + QTest::newRow ("display-space-marker") << QString {"A~B"} << QString {"A B"} + << true << false; + 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; + QTest::newRow ("unsupported-past-limit") + << (QString (80, QLatin1Char {'A'}) + QString {"\t"}) + << QString (80, QLatin1Char {'A'}) + << false << true; + QTest::newRow ("substitution-and-truncation") + << (QString (79, QLatin1Char {'A'}) + QString {"\tB"}) + << (QString (79, QLatin1Char {'A'}) + QString {"#"}) + << true << true; + } + + void prepareTransmitText () + { + 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<QString> ("message"); + QTest::addColumn<bool> ("isChained"); + QTest::addColumn<QString> ("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<QString> ("message"); + QTest::addColumn<bool> ("isChained"); + QTest::addColumn<QString> ("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 {' '}); + } + + void transmitFrame () + { + QFETCH (QString, message); + QFETCH (bool, isChained); + QFETCH (QString, expected); + + QString const frame = Jtty::transmitFrame (message, isChained); + + QCOMPARE (frame, expected); + QCOMPARE (frame.size (), Jtty::maxTransmitLength); + } + + void wavCaptureValid_data () + { + QTest::addColumn<qint32> ("k0"); + QTest::addColumn<bool> ("expected"); + + QTest::newRow ("zero") << qint32 {0} << false; + QTest::newRow ("negative") << qint32 {-1} << false; + QTest::newRow ("below-one-frame") << qint32 {Jtty::jttyFrameSamples - 1} << false; + QTest::newRow ("exactly-one-frame") << qint32 {Jtty::jttyFrameSamples} << false; + QTest::newRow ("just-over-one-frame") << qint32 {Jtty::jttyFrameSamples + 1} << true; + QTest::newRow ("typical-interval") << qint32 {1000000} << true; + QTest::newRow ("sentinel-minus-one") << qint32 {Jtty::invalidCaptureSamples - 1} << true; + QTest::newRow ("sentinel") << qint32 {Jtty::invalidCaptureSamples} << false; + QTest::newRow ("sentinel-plus-one") << qint32 {Jtty::invalidCaptureSamples + 1} << false; + } + + void wavCaptureValid () + { + QFETCH (qint32, k0); + QFETCH (bool, expected); + + QCOMPARE (Jtty::wavCaptureValid (k0), expected); + } + + void formatSerialNumber_data () + { + QTest::addColumn<int> ("serialNumber"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("minimum") << 1 << QString {"001"}; + QTest::newRow ("single-digit") << 5 << QString {"005"}; + QTest::newRow ("two-digit") << 57 << QString {"057"}; + QTest::newRow ("three-digit") << 101 << QString {"101"}; + QTest::newRow ("four-digit") << 1234 << QString {"1234"}; + QTest::newRow ("spinbox-maximum") << 5000 << QString {"5000"}; + } + + void formatSerialNumber () + { + QFETCH (int, serialNumber); + QFETCH (QString, expected); + + QCOMPARE (Jtty::formatSerialNumber (serialNumber), expected); + } + + void jttyLineTimeLabel_data () + { + QTest::addColumn<QDateTime> ("diskDateTime"); + QTest::addColumn<qint32> ("utcDiskRaw"); + QTest::addColumn<float> ("tsyncSeconds"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("real-date-anchors-tsync") + << QDateTime {QDate {2026, 8, 28}, QTime {19, 45, 7}, Qt::UTC} + << qint32 {194507} << 3.0f << QString {"194510"}; + QTest::newRow ("real-date-wraps-past-midnight") + << QDateTime {QDate {2026, 8, 28}, QTime {23, 59, 58}, Qt::UTC} + << qint32 {235958} << 5.0f << QString {"000003"}; + QTest::newRow ("subsecond-offset-preserves-current-second") + << QDateTime {QDate {2026, 8, 28}, QTime {19, 45, 7}, Qt::UTC} + << qint32 {194507} << 0.6f << QString {"194507"}; + QTest::newRow ("dummy-date-falls-back-to-raw-digits") + << QDateTime {} << qint32 {2} << 0.0f << QString {"000002"}; + QTest::newRow ("dummy-date-fallback-still-anchors-tsync") + << QDateTime {} << qint32 {2} << 5.0f << QString {"000007"}; + QTest::newRow ("neither-anchor-usable") + << QDateTime {} << qint32 {999999} << 0.0f << QString {}; + } + + void jttyLineTimeLabel () + { + QFETCH (QDateTime, diskDateTime); + QFETCH (qint32, utcDiskRaw); + QFETCH (float, tsyncSeconds); + QFETCH (QString, expected); + + QCOMPARE (Jtty::jttyLineTimeLabel (diskDateTime, utcDiskRaw, tsyncSeconds), expected); + } + + void jttyLineStartTimeUtc () + { + QDateTime const diskDateTime {QDate {2026, 8, 28}, QTime {23, 59, 58}, Qt::UTC}; + QDateTime const expectedMidnight {QDate {2026, 8, 29}, QTime {0, 0, 3}, Qt::UTC}; + QDateTime const expectedFallback {QDate {2000, 1, 1}, QTime {0, 0, 7}, Qt::UTC}; + QCOMPARE (Jtty::jttyLineStartTimeUtc (diskDateTime, 235958, 5.0f), expectedMidnight); + QCOMPARE (Jtty::jttyLineStartTimeUtc (QDateTime {}, 2, 5.0f), expectedFallback); + QVERIFY (!Jtty::jttyLineStartTimeUtc (QDateTime {}, 999999, 0.0f).isValid ()); + } + + void jttyLineTimeLabelForStoredTimestamp () + { + QCOMPARE (Jtty::jttyLineTimeLabel ( + QDateTime {QDate {2026, 8, 28}, QTime {19, 45, 7}, Qt::UTC}), + QString {"194507"}); + QCOMPARE (Jtty::jttyLineTimeLabel (QDateTime {}), QString {}); + } + + void parseDecodeLine_data () + { + QTest::addColumn<QString> ("line"); + QTest::addColumn<int> ("frequency"); + QTest::addColumn<QString> ("message"); + QTest::addColumn<bool> ("valid"); + + QTest::newRow ("four-digit-frequency") + << QString {"1500 CQ K1ABC"} << 1500 << QString {"CQ K1ABC"} << true; + QTest::newRow ("three-digit-frequency-with-padding") + << QString {" 500 599 K1ABC "} << 500 << QString {"599 K1ABC"} << true; + QTest::newRow ("numeric-leading-message-is-preserved") + << QString {"1500 599 K1ABC"} << 1500 << QString {"599 K1ABC"} << true; + QTest::newRow ("frequency-only") + << QString {"1500"} << 1500 << QString {} << true; + QTest::newRow ("malformed-frequency") + << QString {"CQ K1ABC"} << 0 << QString {"CQ K1ABC"} << false; + QTest::newRow ("empty") + << QString {} << 0 << QString {} << false; + } + + void parseDecodeLine () + { + QFETCH (QString, line); + QFETCH (int, frequency); + QFETCH (QString, message); + QFETCH (bool, valid); + + auto const decoded = Jtty::parseDecodeLine (line); + + QCOMPARE (decoded.frequency, frequency); + QCOMPARE (decoded.message, message); + QCOMPARE (decoded.valid, valid); + } + + void wrapMessage_data () + { + QTest::addColumn<QString> ("text"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("short-unchanged") << QString {"HELLO"} << QString {"HELLO"}; + QTest::newRow ("exactly-40-unchanged") + << QString (40, QLatin1Char {'A'}) << QString (40, QLatin1Char {'A'}); + QTest::newRow ("joes-example") + << QString {"MAYBE CLAUDE COULD HELP US MAKE THE 3 MIN TRANSITION SEAMLESS"} + << QString {"MAYBE CLAUDE COULD HELP US MAKE THE 3\n MIN TRANSITION SEAMLESS"}; + QTest::newRow ("break-at-boundary") + << (QString (39, QLatin1Char {'A'}) + QString {" B"}) + << (QString (39, QLatin1Char {'A'}) + QString {"\n B"}); + QTest::newRow ("hard-break-no-blank") + << QString (50, QLatin1Char {'A'}) + << (QString (40, QLatin1Char {'A'}) + QString {"\n "} + + QString (10, QLatin1Char {'A'})); + QTest::newRow ("leading-space-does-not-create-empty-line") + << (QString {" "} + QString (79, QLatin1Char {'A'})) + << (QString {" "} + QString (39, QLatin1Char {'A'}) + QString {"\n "} + + QString (40, QLatin1Char {'A'})); + QTest::newRow ("multiple-wrap-points") + << QString {"AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC DDDDDDDDDD EEEEEEEEEE FFFFFFFFFF GGGGGGGGGG"} + << QString {"AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC\n DDDDDDDDDD EEEEEEEEEE FFFFFFFFFF\n GGGGGGGGGG"}; + } + + void wrapMessage () + { + QFETCH (QString, text); + QFETCH (QString, expected); + + QCOMPARE (Jtty::wrapMessage (text), expected); + } + + void compareMessagesTracksMessageSemantics () + { + auto const unchanged = Jtty::compareMessages ( + QStringLiteral ("CQ K1ABC"), QStringLiteral ("CQ K1ABC")); + QVERIFY (!unchanged.messageChanged); + QVERIFY (!unchanged.extendsMessage); + QVERIFY (!unchanged.startsMessage); + QVERIFY (unchanged.appendedText.isEmpty ()); + + auto const growth = Jtty::compareMessages ( + QStringLiteral ("CQ K1"), QStringLiteral ("CQ K1ABC")); + QVERIFY (growth.messageChanged); + QVERIFY (growth.extendsMessage); + QVERIFY (!growth.startsMessage); + QCOMPARE (growth.appendedText, QStringLiteral ("ABC")); + + auto const replacement = Jtty::compareMessages ( + QStringLiteral ("FIRST"), QStringLiteral ("SECOND")); + QVERIFY (replacement.messageChanged); + QVERIFY (!replacement.extendsMessage); + QVERIFY (!replacement.startsMessage); + QVERIFY (replacement.appendedText.isEmpty ()); + + auto const textAfterEmptyFrame = Jtty::compareMessages ( + QString {}, QStringLiteral ("ABC")); + QVERIFY (textAfterEmptyFrame.messageChanged); + QVERIFY (textAfterEmptyFrame.extendsMessage); + QVERIFY (textAfterEmptyFrame.startsMessage); + QCOMPARE (textAfterEmptyFrame.appendedText, QStringLiteral ("ABC")); + } + + void messageUpdatesDoNotRemoveHistory () + { + QVector<Jtty::MessageUpdate> history { + {1, 1000.f, QStringLiteral ("FIRST"), 1.f, false}, + {2, 1100.f, QStringLiteral ("SECOND"), 2.f, false}, + }; + QVector<Jtty::MessageUpdate> updates { + {2, 1100.f, QStringLiteral ("SECOND"), 2.f, false}, + }; + + QVERIFY (!Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 2); + QCOMPARE (history.at (0).messageId, qint64 {1}); + QCOMPARE (history.at (1).messageId, qint64 {2}); + } + + void messageUpdatesReplaceSameId () + { + QVector<Jtty::MessageUpdate> history { + {8, 1400.f, QStringLiteral ("CQ K1"), 3.f, false}, + }; + QVector<Jtty::MessageUpdate> updates { + {8, 1401.f, QStringLiteral ("CQ K1ABC"), 3.f, true}, + }; + + QVERIFY (Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 1); + QCOMPARE (history.at (0).frequency, 1401.f); + QCOMPARE (history.at (0).text, QStringLiteral ("CQ K1ABC")); + QVERIFY (history.at (0).complete); + } + + void messageUpdatesPreserveCompletionAndInitialStart () + { + QVector<Jtty::MessageUpdate> history { + {12, 1600.f, QStringLiteral ("TEST"), 4.f, true}, + }; + QVector<Jtty::MessageUpdate> updates { + {12, 1600.f, QStringLiteral ("TEST"), 9.f, false}, + }; + + QVERIFY (!Jtty::mergeMessageUpdates (history, updates)); + QVERIFY (history.at (0).complete); + QCOMPARE (history.at (0).sequenceStart, 4.f); + } + + void messageUpdatesDistinguishIdenticalTextById () + { + QVector<Jtty::MessageUpdate> history { + {qint64 {1} << 35, 1600.f, QStringLiteral ("TEST"), 1.f, false}, + }; + QVector<Jtty::MessageUpdate> updates { + {(qint64 {1} << 35) + 1, 1600.f, QStringLiteral ("TEST"), 2.f, false}, + }; + + QVERIFY (Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 2); + QVERIFY (history.at (0).messageId != history.at (1).messageId); + QCOMPARE (history.at (0).text, history.at (1).text); + } + + void messageUpdatesOrderByStartTimeThenId () + { + QVector<Jtty::MessageUpdate> history; + QVector<Jtty::MessageUpdate> updates { + {9, 1000.f, QStringLiteral ("FOURTH"), 5.f, false}, + {4, 2000.f, QStringLiteral ("FIRST"), 1.f, false}, + {7, 900.f, QStringLiteral ("THIRD"), 3.f, false}, + {2, 1800.f, QStringLiteral ("SECOND"), 3.f, false}, + }; + + QVERIFY (Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 4); + QCOMPARE (history.at (0).messageId, qint64 {4}); + QCOMPARE (history.at (1).messageId, qint64 {2}); + QCOMPARE (history.at (2).messageId, qint64 {7}); + QCOMPARE (history.at (3).messageId, qint64 {9}); + } + + void qsoHistoryRetainsAdmittedMessageAcrossDrift () + { + QVERIFY (Jtty::shouldApplyToQsoHistory (false, 1504.f, 1500.f, 5.f)); + QVERIFY (!Jtty::shouldApplyToQsoHistory (false, 1505.f, 1500.f, 5.f)); + QVERIFY (Jtty::shouldApplyToQsoHistory (true, 1510.f, 1500.f, 5.f)); + } +}; + +QTEST_MAIN (TestJttyMessages) +#include "test_jtty_messages.moc" diff --git a/tests/unit/jtty/test_jtty_n1mm.cpp b/tests/unit/jtty/test_jtty_n1mm.cpp new file mode 100644 index 00000000..7f2f167f --- /dev/null +++ b/tests/unit/jtty/test_jtty_n1mm.cpp @@ -0,0 +1,245 @@ +#include <QtTest> + +#include "widgets/JttyN1mm.hpp" +#include "widgets/JttyN1mmOutput.hpp" + +class TestJttyN1mm final : public QObject +{ + Q_OBJECT + + using Kind = Jtty::NativeAtomKind; + using Profile = Jtty::NativeExchangeProfile; + using Status = Jtty::N1mmCompileStatus; + +private slots: + void rejectedOutputCompletesOnceAtOff () + { + Jtty::N1mmOutput output; + output.submit (1); + QVERIFY (output.resolve (1)); + QVERIFY (!output.takeCompletion (false)); + QVERIFY (!output.takeCompletion (false, true)); + output.start (); + output.finish (); + QVERIFY (output.takeCompletion (false)); + QVERIFY (!output.takeCompletion (false, true)); + output.finish (); + QVERIFY (!output.finishRequested ()); + } + + void mixedOutputWaitsForAcceptedAudio () + { + Jtty::N1mmOutput output; + output.start (); + output.submit (1); + QVERIFY (output.resolve (1)); + QVERIFY (!output.takeCompletion (false)); + QVERIFY (output.startRequested ()); + output.submit (2); + output.finish (); + QVERIFY (output.startRequested ()); + QVERIFY (!output.takeCompletion (false)); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.accept (2)); + output.started (); + QVERIFY (output.resolve (2)); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.takeCompletion (false, true)); + } + + void asynchronousRejectionAfterOffCompletesWithoutDrain () + { + Jtty::N1mmOutput output; + output.start (); + output.submit (1); + output.finish (); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.resolve (1)); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.takeCompletion (false)); + } + + void drainBeforeOffAndAbortDoNotDuplicateCompletion () + { + Jtty::N1mmOutput output; + output.submit (1); + output.start (); + QVERIFY (output.accept (1)); + QVERIFY (output.resolve (1)); + QVERIFY (output.takeCompletion (false, true)); + output.finish (); + QVERIFY (!output.takeCompletion (false)); + output.submit (2); + output.abort (); + QVERIFY (!output.resolve (2)); + output.finish (); + QVERIFY (!output.takeCompletion (false, true)); + } + + void everyActionCompiles () + { + struct Example + { + QString message; + Profile profile; + QString canonical; + QVector<Kind> kinds; + }; + QVector<Example> const examples { + {"[[JTTY:CQ]] K1ABC", Profile::None, "CQ K1ABC CQ", {Kind::Call}}, + {"[[JTTY:CALL_EXCH]] W9XYZ 7", Profile::None, "W9XYZ 599 007", + {Kind::Call, Kind::ExchangeNumber}}, + {"[[JTTY:CALL_TU_CQ]] W9XYZ K1ABC", Profile::None, "W9XYZ TU CQ K1ABC CQ", + {Kind::Call, Kind::Call}}, + {"[[JTTY:MYCALL]] K1ABC", Profile::None, "K1ABC", {Kind::Call}}, + {"[[JTTY:HISCALL]] W9XYZ", Profile::None, "W9XYZ", {Kind::Call}}, + {"[[JTTY:TU_NOW_EXCH]] W9XYZ 42", Profile::None, "TU NOW W9XYZ 599 042", + {Kind::Call, Kind::ExchangeNumber}}, + {"[[JTTY:CALL_MY]] W9XYZ K1ABC", Profile::None, "W9XYZ K1ABC", + {Kind::Call, Kind::Call}}, + {"[[JTTY:CALL_TU_MY]] W9XYZ K1ABC", Profile::None, "W9XYZ TU K1ABC", + {Kind::Call, Kind::Call}}, + {"[[JTTY:EXCH]] 1D EMA", Profile::FieldDay, "1D EMA", {Kind::ExchangePair}}, + {"[[JTTY:GRID]] fn42", Profile::None, "FN42", {Kind::Grid4}}, + {"[[JTTY:CONTROL]] qsl tu", Profile::None, "QSL TU", {Kind::Control}} + }; + + for (auto const& example : examples) { + auto const result = Jtty::compileN1mmMessage (example.message, example.profile); + QCOMPARE (result.status, Status::Native); + QCOMPARE (result.canonicalText, example.canonical); + QCOMPARE (result.atoms.size (), example.kinds.size ()); + for (int i = 0; i < result.atoms.size (); ++i) { + QCOMPARE (int {result.atoms.at (i).kind}, static_cast<int> (example.kinds.at (i))); + } + } + } + + void tagMatchingIsCaseAndWhitespaceNormalized () + { + auto const result = Jtty::compileN1mmMessage ( + QStringLiteral (" \t[[jtty:call_tu_cq]] w9xyz\n k1abc ")); + QCOMPARE (result.status, Status::Native); + QCOMPARE (result.canonicalText, QStringLiteral ("W9XYZ TU CQ K1ABC CQ")); + } + + void tagClassification () + { + QString const literal = QStringLiteral (" W9XYZ 599 007"); + auto const untagged = Jtty::compileN1mmMessage (literal); + QCOMPARE (untagged.status, Status::Literal); + QCOMPARE (untagged.literalText, literal); + QVERIFY (untagged.atoms.isEmpty ()); + + auto const notFirst = Jtty::compileN1mmMessage ( + QStringLiteral ("CQ [[JTTY:CQ]] K1ABC")); + QCOMPARE (notFirst.status, Status::Literal); + + auto const malformed = Jtty::compileN1mmMessage ( + QStringLiteral (" [[JTTY:CQ K1ABC")); + QCOMPARE (malformed.status, Status::Error); + QVERIFY (!malformed.error.isEmpty ()); + + auto const malformedStem = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY]] K1ABC")); + QCOMPARE (malformedStem.status, Status::Error); + QVERIFY (!malformedStem.error.isEmpty ()); + + auto const unknown = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:MAGIC]] K1ABC")); + QCOMPARE (unknown.status, Status::Error); + QVERIFY (unknown.error.contains (QStringLiteral ("unknown"))); + } + + void profileDrivenExchange () + { + auto const serial = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] 00042"), Profile::RttyRoundup); + QCOMPARE (serial.status, Status::Native); + QCOMPARE (serial.canonicalText, QStringLiteral ("599 042")); + QCOMPARE (int {serial.atoms.first ().kind}, static_cast<int> (Kind::ExchangeNumber)); + QCOMPARE (serial.atoms.first ().value, qint32 {42}); + + auto const state = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:CALL_EXCH]] W9XYZ az"), Profile::RttyRoundup); + QCOMPARE (state.status, Status::Native); + QCOMPARE (state.canonicalText, QStringLiteral ("W9XYZ 599 AZ")); + QCOMPARE (int {state.atoms.last ().kind}, static_cast<int> (Kind::ExchangeLocation)); + QCOMPARE (int {state.atoms.last ().subtype}, + static_cast<int> (Jtty::LocationKind::StateProvince)); + + auto const dx = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] DX"), Profile::RttyRoundup); + QCOMPARE (dx.status, Status::Native); + QCOMPARE (dx.canonicalText, QStringLiteral ("599 DX")); + QCOMPARE (int {dx.atoms.first ().kind}, static_cast<int> (Kind::ExchangeLocation)); + + auto const fieldDay = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] 32f ema"), Profile::FieldDay); + QCOMPARE (fieldDay.status, Status::Native); + QCOMPARE (fieldDay.canonicalText, QStringLiteral ("32F EMA")); + QCOMPARE (fieldDay.atoms.first ().value, qint32 {32}); + QCOMPARE (int {fieldDay.atoms.first ().role}, 5); + QCOMPARE (QString::fromLatin1 (fieldDay.atoms.first ().text), QStringLiteral ("EMA")); + } + + void payloadValidation_data () + { + QTest::addColumn<QString> ("message"); + QTest::addColumn<int> ("profile"); + + QTest::newRow ("empty") << QStringLiteral ("[[JTTY:CQ]]") << int (Profile::None); + QTest::newRow ("cq-extra") << QStringLiteral ("[[JTTY:CQ]] K1ABC CQ") + << int (Profile::None); + QTest::newRow ("bad-call") << QStringLiteral ("[[JTTY:HISCALL]] NOTACALL") + << int (Profile::None); + QTest::newRow ("call-extra") << QStringLiteral ("[[JTTY:MYCALL]] K1ABC EXTRA") + << int (Profile::None); + QTest::newRow ("missing-exchange") << QStringLiteral ("[[JTTY:CALL_EXCH]] W9XYZ") + << int (Profile::None); + QTest::newRow ("serial-junk") << QStringLiteral ("[[JTTY:EXCH]] 12A") + << int (Profile::None); + QTest::newRow ("serial-overflow") << QStringLiteral ("[[JTTY:EXCH]] 131072") + << int (Profile::RttyRoundup); + QTest::newRow ("unexpanded-hash") << QStringLiteral ("[[JTTY:EXCH]] #") + << int (Profile::RttyRoundup); + QTest::newRow ("field-day-shape") << QStringLiteral ("[[JTTY:EXCH]] 1D") + << int (Profile::FieldDay); + QTest::newRow ("field-day-compact") << QStringLiteral ("[[JTTY:EXCH]] 3AOR") + << int (Profile::FieldDay); + QTest::newRow ("field-day-count") << QStringLiteral ("[[JTTY:EXCH]] 33A EMA") + << int (Profile::FieldDay); + QTest::newRow ("grid-extra") << QStringLiteral ("[[JTTY:GRID]] 599 FN42") + << int (Profile::None); + QTest::newRow ("grid-field") << QStringLiteral ("[[JTTY:GRID]] SA00") + << int (Profile::None); + QTest::newRow ("grid-digit") << QStringLiteral ("[[JTTY:GRID]] FN4A") + << int (Profile::None); + QTest::newRow ("control") << QStringLiteral ("[[JTTY:CONTROL]] THANKS") + << int (Profile::None); + } + + void payloadValidation () + { + QFETCH (QString, message); + QFETCH (int, profile); + auto const result = Jtty::compileN1mmMessage ( + message, static_cast<Profile> (profile)); + QCOMPARE (result.status, Status::Error); + QVERIFY (!result.error.isEmpty ()); + QVERIFY (result.atoms.isEmpty ()); + } + + void contextOverloadUsesSelectedProfile () + { + Jtty::NativeMacroContext context; + context.exchangeProfile = Profile::FieldDay; + auto const result = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] 1D EMA"), context); + QCOMPARE (result.status, Status::Native); + QCOMPARE (int {result.atoms.first ().kind}, static_cast<int> (Kind::ExchangePair)); + } +}; + +QTEST_GUILESS_MAIN (TestJttyN1mm) +#include "test_jtty_n1mm.moc" diff --git a/tests/unit/jtty/test_jtty_overlap_decode.f90 b/tests/unit/jtty/test_jtty_overlap_decode.f90 new file mode 100644 index 00000000..b440d1f3 --- /dev/null +++ b/tests/unit/jtty/test_jtty_overlap_decode.f90 @@ -0,0 +1,202 @@ +program test_jtty_overlap_decode + + ! Overlap two generated JTTY transmissions and decode them through + ! rjtty_sub. This is a stand-in for the private W2PU on-air corpus. + ! + ! 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. + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + character(len=*), parameter :: msg_a='MAYBE YOU SHOULD HELP' + character(len=*), parameter :: msg_b='CLAUDE CO 3 MIN TRANSITION' + integer :: failures,nsps + character(len=16) :: rate_arg + integer :: failures_before_overlap + + nsps=384 + call get_command_argument(1,rate_arg) + 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) + + failures_before_overlap=failures + call expect_complete_pair('4 Hz overlap stays two complete messages', & + msg_a,1500.0,0.2,msg_b,1504.0,0.6,2,failures) + if(failures.gt.failures_before_overlap) then + write(*,'(a)') '4 Hz overlap messages: '//trim(message_summary()) + endif + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_overlap_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_overlap_decode: all checks passed' + +contains + + subroutine expect_complete_pair(description,first_message,first_hz, & + first_dt,second_message,second_hz,second_dt,expected_messages,count) + character(len=*), intent(in) :: description,first_message,second_message + real, intent(in) :: first_hz,first_dt,second_hz,second_dt + integer, intent(in) :: expected_messages + integer, intent(inout) :: count + logical :: found_a,found_b + + call decode_overlap(first_message,first_hz,first_dt,second_message, & + second_hz,second_dt,50.0) + call message_coverage(first_message,second_message,found_a,found_b) + call expect(npending.eq.expected_messages,description//': message count',count) + if(len_trim(first_message).gt.0) then + call expect(found_a,description//': first message complete',count) + endif + if(len_trim(second_message).gt.0) then + call expect(found_b,description//': second message complete',count) + endif + end subroutine expect_complete_pair + + subroutine decode_overlap(first_message,first_hz,first_dt,second_message, & + second_hz,second_dt,ftol) + character(len=*), intent(in) :: first_message,second_message + real, intent(in) :: first_hz,first_dt,second_hz,second_dt,ftol + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: first_tones(MAX_FRAMES*frame_symbols) + integer :: second_tones(MAX_FRAMES*frame_symbols) + integer :: first_symbols,second_symbols + integer :: first_samples,second_samples,first_start,second_start + integer :: total_samples,i,idx + integer :: first_pcm,second_pcm,mixed + integer(int16), allocatable :: pcm(:) + real, allocatable :: first_wave(:),second_wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: first_input,second_input + + call discard_pending_updates() + first_symbols=0 + second_symbols=0 + first_samples=0 + second_samples=0 + first_start=1 + second_start=1 + + if(len_trim(first_message).gt.0) then + first_input=first_message + call genjtty(first_input,first_tones,first_symbols) + first_samples=first_symbols*nsps + first_start=max(1,nint(first_dt*12000.0)+1) + endif + if(len_trim(second_message).gt.0) then + second_input=second_message + call genjtty(second_input,second_tones,second_symbols) + second_samples=second_symbols*nsps + second_start=max(1,nint(second_dt*12000.0)+1) + endif + + total_samples=max(first_start+first_samples-1, & + second_start+second_samples-1)+frame_symbols*nsps + allocate(pcm(total_samples)) + pcm=0_int16 + + if(first_samples.gt.0) then + allocate(first_wave(first_samples),complex_wave(first_samples)) + call gen_jttywave(first_tones,first_symbols,nsps,2.0,12000.0,first_hz, & + complex_wave,first_wave,0,first_samples) + do i=1,first_samples + idx=first_start+i-1 + first_pcm=nint(14000.0*first_wave(i)) + pcm(idx)=int(max(-32767,min(32767,first_pcm)),int16) + enddo + deallocate(first_wave,complex_wave) + endif + + if(second_samples.gt.0) then + allocate(second_wave(second_samples),complex_wave(second_samples)) + call gen_jttywave(second_tones,second_symbols,nsps,2.0,12000.0, & + second_hz,complex_wave,second_wave,0,second_samples) + do i=1,second_samples + idx=second_start+i-1 + second_pcm=nint(14000.0*second_wave(i)) + mixed=int(pcm(idx))+second_pcm + pcm(idx)=int(max(-32767,min(32767,mixed)),int16) + enddo + deallocate(second_wave,complex_wave) + endif + + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,ftol) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,ftol) + deallocate(pcm) + end subroutine decode_overlap + + subroutine message_coverage(first_message,second_message,found_a,found_b) + character(len=*), intent(in) :: first_message,second_message + logical, intent(out) :: found_a,found_b + integer :: i + + found_a=len_trim(first_message).eq.0 + 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)) & + found_a=.true. + endif + if(len_trim(second_message).gt.0) then + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(second_message)) & + found_b=.true. + endif + enddo + end subroutine message_coverage + + function message_summary() result(text) + character(len=240) :: text + character(len=80) :: body + integer :: i,pos + + text='' + pos=1 + do i=1,npending + body=normalized(pending_updates(i)%decoded) + if(pos.gt.1) then + text(pos:pos)='|' + pos=pos+1 + endif + text(pos:pos+len_trim(body)-1)=trim(body) + pos=pos+len_trim(body) + if(pos.ge.len(text)-1) exit + enddo + end function message_summary + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_overlap_decode diff --git a/tests/unit/jtty/test_jtty_pack.f90 b/tests/unit/jtty/test_jtty_pack.f90 new file mode 100644 index 00000000..31541cfb --- /dev/null +++ b/tests/unit/jtty/test_jtty_pack.f90 @@ -0,0 +1,460 @@ +program test_jtty_pack + + use jtty_mod + use packjt77, only: pack28 + character*80 msg0,msg,expected + character*34 c32(MAX_FRAMES) + character*17 cparms + character*1 err + integer, parameter :: expected_errors = 0 + + open(10,file='jtty_msgs.txt',status='old') + write(*,1000) +1000 format('i2.n2 i2.n2 NC NF err Message'/87('-')) + nerr=0 + nz=0 + c32='' + do imsg=1,99 + read(10,'(a80)',end=100) msg0 + call normalize_jtty_message(msg0,expected) + nlength=len_trim(expected) + if(nlength.eq.0) then + write(*,*) + cycle + endif + nz=nz+1 + call pack_jtty(msg0,c32,nframes) + if(nframes.lt.0) then + err='*' + nerr=nerr+1 + cycle + endif + call expect_no_reserved_frame_ids(c32,nframes,msg0) + call unpack_jtty(c32,nframes,msg) + call display_jtty_message(msg) + err=' ' + if(msg.ne.expected) then + err='*' + nerr=nerr+1 + write(12,1010) trim(expected),trim(msg) +1010 format(a/a) + endif + read(c32(1),1012) n2a,i2a + read(c32(2),1012) n2b,i2b +1012 format(28x,2b2) + write(cparms,1018) i2a,n2a,i2b,n2b,nlength,nframes +1018 format(i2,'.',i1,2x,i2,'.',i1,i4,i3) + if(i2a.ge.2) cparms(3:4)=' ' + if(i2b.ge.2) cparms(9:10)=' ' + if(nframes.eq.1) cparms(7:10)=' ' + write(*,1020) cparms,err,trim(msg) +1020 format(a17,2x,a1,2x,a) + enddo + +100 write(*,1100) nz,nerr +1100 format(/'Total messages:',i3,' Number of errors:',i3) + if(nerr.ne.expected_errors) error stop 1 + + call expect_pack('CQ KA1ABC CQ',1,0,0,-1,-1) + call expect_pack('CQ K1ABC CQ',1,0,0,-1,-1) + call expect_pack('K1A',1,0,1,-1,-1) + call expect_pack('WB9XYZ',1,0,1,-1,-1) + call expect_pack('TU WB9XYZ CQ',1,0,2,-1,-1) + call expect_pack('WB9XYZ TU',1,0,3,-1,-1) + call expect_pack('WB9XYZ AGN?',1,1,0,-1,-1) + call expect_pack('TU NOW WB9XYZ',1,1,1,-1,-1) + call expect_pack('WB9XYZ TU CQ KA1ABC CQ',2,0,3,0,0) + call expect_pack('K1ABC TU NOW W1XYZ',2,0,1,1,1) + call expect_pack('WB9XYZ 599 123',2,0,1,2,-1) + call expect_pack('599 MA',1,2,-1,-1,-1) + call expect_pack('599 FN42',1,2,-1,-1,-1) + 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('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) + call expect_pack('599 001',2,-1,-1,-1,-1) + call expect_pack('599 05',2,-1,-1,-1,-1) + call expect_pack('599 BRUCE',2,-1,-1,-1,-1) + call expect_pack('131072',2,3,-1,3,-1) + call expect_pack('000001',2,3,-1,3,-1) + call expect_pack('01D EMA',2,3,-1,3,-1) + 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('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) + call expect_pack('599 0AB',2,-1,-1,-1,-1) + call expect_pack('CQ K1ABC CQ!',3,-1,-1,-1,-1) + call expect_pack('TEST WB9XYZ',2,3,-1,0,1) + call expect_pack('HI WB9XYZ',2,3,-1,3,-1) + call expect_pack('K1ABC HELLO',2,0,1,3,-1) + call expect_pack('TEST AGN NR',2,3,-1,2,-1) + call expect_pack(repeat('A',80),16,3,-1,3,-1) + call expect_pack('',0,-1,-1,-1,-1) + call expect_pack(' ',0,-1,-1,-1,-1) + call expect_pack('599 A',1,3,-1,-1,-1) + call expect_pack('599 BRUCE F',3,-1,-1,-1,-1) + call expect_pack('A599 MA',2,3,-1,3,-1) + call expect_pack('VP2/KF2GHI',2,3,-1,3,-1) + call expect_pack('VP2/KA1ABC',2,3,-1,3,-1) + call expect_pack('QU1RK',1,3,-1,-1,-1) + call expect_pack('TU QU1RKP CQ',3,2,-1,3,-1) + call expect_pack('WB9XYZABC',2,3,-1,3,-1) + call expect_pack('K1A A',1,3,-1,-1,-1) + 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('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')) + call expect_atom('599 FN42',jtty_grid4_atom(JTTY_ROLE_FULL,'FN42')) + call expect_exchange_profiles() + ! Normalization is part of the round-trip contract for operator input. + call expect_pack('cq ka1abc cq',1,0,0,-1,-1) + call expect_pack(' vp2/kf2ghi ',2,3,-1,3,-1) + call expect_pack('A'//char(0)//'B',1,3,-1,-1,-1) + call expect_pack('A~B',1,3,-1,-1,-1) + call expect_pack('HELLO~',1,3,-1,-1,-1) + call expect_pack('HELLO'//char(9)//'WORLD',3,3,-1,3,-1) + call expect_pack('HELLO'//char(10)//'WORLD',3,3,-1,3,-1) + call expect_pack('HELLO'//char(13)//'WORLD',3,3,-1,3,-1) + call expect_unassigned_unpack_empty(1,2) + call expect_unassigned_unpack_empty(1,3) + call expect_structured_unpack_boundary() + call expect_empty_waveform_guard() + call expect_last_frame_flag() + +contains + + subroutine expect_atom(text,atom,exchange_profile) + character(len=*), intent(in) :: text + type(jtty_source_atom), intent(in) :: atom + integer, intent(in), optional :: exchange_profile + character(len=80) :: input + character(len=34) :: frames(MAX_FRAMES),expected_frame + integer :: nframes + logical :: valid + + input=text + call pack_jtty(input,frames,nframes,exchange_profile) + call pack_jtty_atom(atom,expected_frame,.true.,valid) + if(.not.valid .or. nframes.ne.1 .or. frames(1).ne.expected_frame) then + write(*,'(a)') 'Unexpected inferred atom for "'//text//'"' + error stop 1 + endif + end subroutine expect_atom + + 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'] + character(len=80) :: input,decoded + character(len=34) :: baseline(MAX_FRAMES),frames(MAX_FRAMES) + integer :: i,profile,baseline_nf,nframes + + call expect_pack('599 001',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('K1ABC 599 001',2,0,1,2,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('K1ABC 599 001',3,0,1,-1,-1,JTTY_EXCHANGE_UNKNOWN) + call expect_pack('599 05',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 005') + call expect_pack('599 0123',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 123') + call expect_pack('K1ABC 599 05 QSL TU',3,0,1,2,-1,JTTY_EXCHANGE_RTTY,'K1ABC 599 005 QSL TU') + call expect_pack('599 05 599 0123',2,2,-1,2,-1,JTTY_EXCHANGE_RTTY,'599 005 599 123') + call expect_pack('599 000005',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 005') + call expect_pack('599 0',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 000') + call expect_pack('599 0000005',3,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 131072',2,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 05A',2,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('A599 05',2,3,-1,3,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 05!',2,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('05',1,3,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 05',2,-1,-1,-1,-1,JTTY_EXCHANGE_FIELD_DAY) + call expect_pack(repeat('A',72)//' 599 05',16,3,-1,3,-1,JTTY_EXCHANGE_RTTY, & + repeat('A',72)//' 599 005') + call expect_pack(repeat('A',64)//' 599 05 599 0123',15,3,-1,3,-1,JTTY_EXCHANGE_RTTY, & + repeat('A',64)//' 599 005 599 123') + call expect_pack('001',1,3,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_atom('599 001',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,1),JTTY_EXCHANGE_RTTY) + call expect_atom('599 123',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,123),JTTY_EXCHANGE_RTTY) + call expect_atom('599 MA',jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_STATE_PROVINCE,'MA'),JTTY_EXCHANGE_RTTY) + call expect_atom('123',jtty_exch_num_atom(JTTY_ROLE_FIELD_ONLY,JTTY_NUM_GENERIC,123),JTTY_EXCHANGE_RTTY) + call expect_atom('599 123',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_GENERIC,123),JTTY_EXCHANGE_FIELD_DAY) + call expect_atom('599 MA',jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_QTH,'MA'),JTTY_EXCHANGE_FIELD_DAY) + + do i=1,size(examples) + input=examples(i) + call pack_jtty(input,baseline,baseline_nf) + do profile=JTTY_EXCHANGE_UNKNOWN,JTTY_EXCHANGE_RTTY + input=examples(i) + call pack_jtty(input,frames,nframes,profile) + if(nframes.lt.1 .or. nframes.gt.baseline_nf) error stop 'Profile worsened frame count' + if(profile.ne.JTTY_EXCHANGE_RTTY) then + if(nframes.ne.baseline_nf .or. any(frames.ne.baseline)) error stop 'Unexpected non-RTTY inference' + endif + call unpack_jtty(frames,nframes,decoded) + call display_jtty_message(decoded) + if(decoded.ne.input) error stop 'Profile changed rendered text' + enddo + input=examples(i) + call pack_jtty(input,frames,nframes) + if(nframes.ne.baseline_nf .or. any(frames.ne.baseline)) error stop 'Profile leaked between calls' + enddo + input='599 001' + call pack_jtty(input,frames,nframes,-1) + if(nframes.ne.-1 .or. any(frames.ne.'')) error stop 'Accepted invalid negative profile' + call pack_jtty(input,frames,nframes,JTTY_EXCHANGE_RTTY+1) + if(nframes.ne.-1 .or. any(frames.ne.'')) error stop 'Accepted unknown profile' + input=repeat('A',73)//' 599 05' + call pack_jtty(input,frames,nframes,JTTY_EXCHANGE_RTTY) + if(nframes.ne.-1 .or. any(frames.ne.'')) error stop 'Accepted canonical text exceeding 80 characters' + end subroutine expect_exchange_profiles + + subroutine expect_control_phrase_literals() + type(jtty_source_atom) atom + character*80 input,decoded,expected + character*34 frame,frames(MAX_FRAMES) + integer phrase_id,got_nf + logical valid,eom + + do phrase_id=lbound(CONTROL_TEXT,1),ubound(CONTROL_TEXT,1) + input='' + if(phrase_id.eq.JTTY_CONTROL_AGN_NR) then + input=' agn nr ' + else + input=trim(CONTROL_TEXT(phrase_id)) + endif + call normalize_jtty_message(input,expected) + call pack_jtty(input,frames,got_nf) + if(got_nf.ne.1) then + write(*,1030) trim(expected),got_nf +1030 format('Control phrase "',a,'" encoded in ',i0,' frames') + error stop 1 + endif + frame=frames(1) + call unpack_jtty_atom(frame,atom,valid,eom) + if(.not.valid .or. .not.eom .or. atom%kind.ne.JTTY_ATOM_CONTROL .or. & + atom%subtype.ne.phrase_id .or. frames(1)(33:33).ne.'0') then + write(*,1040) trim(expected),phrase_id +1040 format('Control phrase "',a,'" did not encode as CONTROL ',i0) + error stop 1 + endif + call unpack_jtty(frames,got_nf,decoded) + call display_jtty_message(decoded) + if(decoded.ne.expected) then + write(*,1050) trim(expected),trim(decoded) +1050 format('Control phrase "',a,'" decoded as "',a,'"') + error stop 1 + endif + enddo + end subroutine expect_control_phrase_literals + + subroutine display_jtty_message(text) + character*80 text + + do i=1,len_trim(text) + if(text(i:i).eq.'~') text(i:i)=' ' + enddo + end subroutine display_jtty_message + + subroutine expect_pack(text,want_nf,want_i2a,want_n2a,want_i2b,want_n2b,exchange_profile,canonical_text) + character*(*) text + character*80 input,decoded,want_decoded,part,incremental + character*34 frames(MAX_FRAMES),single(MAX_FRAMES) + integer want_nf,want_i2a,want_n2a,want_i2b,want_n2b + integer, intent(in), optional :: exchange_profile + character(len=*), intent(in), optional :: canonical_text + integer got_nf,got_i2a,got_n2a,got_i2b,got_n2b,iframe + logical trailing_sep,is_last,valid + + input='' + input=text + call normalize_jtty_message(input,want_decoded) + if(present(canonical_text)) want_decoded=canonical_text + frames='' + call pack_jtty(input,frames,got_nf,exchange_profile) + if(input.ne.want_decoded) error stop 'Returned message differs from canonical text' + if(got_nf.lt.0) then + write(*,1195) trim(input) +1195 format('Unexpected pack failure for "',a,'"') + error stop 1 + endif + call expect_no_reserved_frame_ids(frames,got_nf,input) + call unpack_jtty(frames,got_nf,decoded) + call display_jtty_message(decoded) + if(decoded.ne.want_decoded) then + write(*,1200) trim(want_decoded),trim(decoded) +1200 format('Round-trip failure for "',a,'"; decoded "',a,'"') + error stop 1 + endif + if(got_nf.ne.want_nf) then + write(*,1210) trim(input),want_nf,got_nf +1210 format('Frame-count failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + incremental='' + do iframe=1,got_nf + single='' + single(1)=frames(iframe) + call unpack_jtty(single,1,part,trailing_sep,is_last,valid) + if(.not.valid .or. (is_last.neqv.(iframe.eq.got_nf))) error stop 'Invalid incremental frame' + incremental=trim(incremental)//trim(part) + if(trailing_sep .and. iframe.lt.got_nf) incremental=trim(incremental)//'~' + if(frames(iframe)(33:33).ne.'0') error stop 'Nonzero reserved bit' + enddo + call display_jtty_message(incremental) + if(incremental.ne.want_decoded) error stop 'Incremental text differs from whole-message text' + if(got_nf.eq.0) return + read(frames(1),'(28x,2b2)') got_n2a,got_i2a + if(want_i2a.ge.0 .and. got_i2a.ne.want_i2a) then + write(*,1220) trim(input),want_i2a,got_i2a +1220 format('First-frame i2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + if(want_n2a.ge.0 .and. got_n2a.ne.want_n2a) then + write(*,1230) trim(input),want_n2a,got_n2a +1230 format('First-frame n2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + if(want_i2b.ge.0) then + read(frames(2),'(28x,2b2)') got_n2b,got_i2b + if(got_i2b.ne.want_i2b) then + write(*,1240) trim(input),want_i2b,got_i2b +1240 format('Second-frame i2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + if(want_n2b.ge.0 .and. got_n2b.ne.want_n2b) then + write(*,1250) trim(input),want_n2b,got_n2b +1250 format('Second-frame n2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + endif + end subroutine expect_pack + + subroutine expect_no_reserved_frame_ids(frames,nframes,input) + character*34 frames(MAX_FRAMES) + character*(*) input + integer nframes, iframe, got_i2, got_n2 + + do iframe=1,nframes + read(frames(iframe),'(28x,2b2)') got_n2, got_i2 + if(got_i2.eq.1 .and. got_n2.ge.2) then + write(*,1260) trim(input),iframe,got_i2,got_n2 +1260 format('Reserved frame id for "',a,'" frame ',i0,': ',i0,'.',i0) + error stop 1 + endif + enddo + end subroutine expect_no_reserved_frame_ids + + subroutine expect_unassigned_unpack_empty(i2,n2) + character*34 frames(MAX_FRAMES) + character*80 decoded + character*13 c13 + integer i2,n2,n28,n32 + + frames='' + c13='K1ABC ' + call pack28(c13,n28) + n32=shiftl(n28,4) + 4*n2 + i2 + write(frames(1),'(b32.32,a2)') n32,'00' + call unpack_jtty(frames,1,decoded) + if(len_trim(decoded).ne.0) then + write(*,1280) i2,n2,trim(decoded) +1280 format('Unassigned frame ',i0,'.',i0,' decoded unexpectedly as "',a,'"') + error stop 1 + endif + end subroutine expect_unassigned_unpack_empty + + subroutine expect_structured_unpack_boundary() + character*34 frames(MAX_FRAMES) + character*80 decoded,expected + character*13 c13 + integer iframe,n28,n32,n30 + + ! A long structured append that straddles column 80 must be truncated exactly. + frames='' + n30=0 + do i=1,5 + n30=64*n30 + jchar('A') + enddo + n32=ishft(n30,2) + 3 + do iframe=1,14 + write(frames(iframe),'(b32.32,a2)') n32,'00' + enddo + c13='KA1ABC ' + call pack28(c13,n28) + n32=shiftl(n28,4) + 4*1 + 1 + write(frames(15),'(b32.32,a2)') n32,'00' + + expected='' + do i=1,70 + expected(i:i)='A' + enddo + expected(71:80)='TU NOW KA1' + call unpack_jtty(frames,15,decoded) + if(len_trim(decoded).ne.80 .or. decoded.ne.expected) then + write(*,1300) len_trim(decoded),trim(decoded) +1300 format('Structured-boundary unpack test decoded length ',i0,' as "',a,'"') + error stop 1 + endif + end subroutine expect_structured_unpack_boundary + + subroutine expect_empty_waveform_guard() + integer, parameter :: TEST_NSPS=4*384 + integer tones(1) + integer nsym, nsps, icmplx, nwave + real bt, fsample, f0 + real wave(TEST_NSPS) + complex cwave(TEST_NSPS) + + tones=0 + nsym=0 + nsps=TEST_NSPS + bt=2.0 + fsample=48000.0 + f0=1500.0 + icmplx=0 + nwave=nsps + + call gen_jttywave(tones,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave) + if(nwave.ne.0) then + write(*,1310) nwave +1310 format('Empty waveform guard returned nwave ',i0) + error stop 1 + endif + end subroutine expect_empty_waveform_guard + + subroutine expect_last_frame_flag() + ! Bit 34 of each 34-bit frame word must be 0 on every frame except the + ! last, and 1 on the last frame of a multi-frame message -- matching how + ! the real decode drivers call unpack_jtty one frame at a time. + character*80 input, decoded + character*34 frames(MAX_FRAMES) + integer got_nf, iframe + logical is_last + + input='TU NOW JA6DEF 599 123' + frames='' + call pack_jtty(input,frames,got_nf) + if(got_nf.lt.2) then + write(*,1400) got_nf +1400 format('expect_last_frame_flag: expected >=2 frames, got ',i0) + error stop 1 + endif + do iframe=1,got_nf + call unpack_jtty(frames(iframe:iframe),1,decoded,is_last_frame=is_last) + if(iframe.lt.got_nf .and. is_last) then + write(*,1410) iframe +1410 format('expect_last_frame_flag: frame ',i0,' unexpectedly flagged as last') + error stop 1 + endif + if(iframe.eq.got_nf .and. .not.is_last) then + write(*,1420) iframe +1420 format('expect_last_frame_flag: final frame ',i0,' not flagged as last') + error stop 1 + endif + enddo + end subroutine expect_last_frame_flag + +end program test_jtty_pack diff --git a/tests/unit/jtty/test_jtty_payload_correlators.f90 b/tests/unit/jtty/test_jtty_payload_correlators.f90 new file mode 100644 index 00000000..a87fd6c4 --- /dev/null +++ b/tests/unit/jtty/test_jtty_payload_correlators.f90 @@ -0,0 +1,107 @@ +program test_jtty_payload_correlators + use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64 + use jtty_payload_correlators + implicit none + + integer(int32), parameter :: lengths(4) = [120,160,192,240] + type(jtty_payload_correlator) :: correlator + complex(real32), allocatable :: samples(:) + complex(real32) :: whole(0:3,46), halves(0:3,46), expected(0:3,46) + integer :: length_index, nss, offset, segment_count + + do length_index = 1, size(lengths) + nss = lengths(length_index) + allocate(samples(0:7+46*nss-1)) + do offset = 0, size(samples)-1 + samples(offset) = cmplx(real(modulo(offset*17,113)-56,real32)/19.0_real32, & + real(modulo(offset*31,127)-63,real32)/23.0_real32,real32) + end do + call jtty_payload_correlator_prepare(correlator,int(nss,int32)) + call jtty_correlate_payload_symbols(correlator,samples,7_int32,whole,halves) + do segment_count = 1, 2 + call separate_reference(samples,7,nss,segment_count,expected) + if (segment_count == 1) then + call require(identical(whole,expected),'shared M1 differs from separate original-order accumulation') + else + call require(identical(halves,expected),'shared M2 differs from separate half-symbol accumulation') + end if + end do + + samples = cmplx(0.0_real32,0.0_real32,real32) + samples(7:7+nss/2-1) = cmplx(1.0_real32,0.0_real32,real32) + samples(7+nss/2:7+nss-1) = cmplx(-1.0_real32,0.0_real32,real32) + call jtty_correlate_payload_symbols(correlator,samples,7_int32,whole,halves) + call require(abs(whole(0,1)) == 0.0_real32,'opposite halves did not cancel in M1') + call require(abs(real(halves(0,1))-real(nss,real32)/sqrt(2.0_real32)) < 0.0001_real32, & + 'M2 failed to retain opposite-phase half energy') + call require(all(abs(whole(:,2:)) == 0.0_real32) .and. & + all(abs(halves(:,2:)) == 0.0_real32),'payload symbol windows overlap') + + samples = cmplx(1.0_real32,0.0_real32,real32) + call jtty_correlate_payload_symbols(correlator,samples(0:7+2*nss-2),7_int32,whole,halves) + call require(abs(whole(0,1)) == real(nss,real32),'complete payload symbol was lost') + call require(all(abs(whole(:,2:)) == 0.0_real32) .and. & + all(abs(halves(:,2:)) == 0.0_real32),'partial symbol was decoded or left stale data') + call jtty_correlate_payload_symbols(correlator,samples,int(size(samples),int32),whole,halves) + call require(all(abs(whole) == 0.0_real32) .and. all(abs(halves) == 0.0_real32), & + 'out-of-range payload left stale observations') + deallocate(samples) + end do + print *, 'test_jtty_payload_correlators: all checks passed' + +contains + + subroutine separate_reference(samples,start,nss,segments,values) + complex(real32), intent(in) :: samples(0:) + integer, intent(in) :: start,nss,segments + complex(real32), intent(out) :: values(0:3,46) + real(real32) :: reference_real(0:nss-1),reference_imaginary(0:nss-1) + real(real32) :: phase,step,sum_real,sum_imaginary,sample_real,sample_imaginary + real(real64) :: energy + integer :: tone,offset,symbol,segment,first,segment_length + + segment_length = nss/segments + do tone = 0, 3 + phase = 0.0_real32 + step = 6.2831853071795864769_real32*real(tone,real32)/real(nss,real32) + do offset = 0, nss-1 + reference_real(offset) = cos(phase) + reference_imaginary(offset) = sin(phase) + phase = phase + step + end do + do symbol = 1, 46 + first = start + (symbol-1)*nss + energy = 0.0_real64 + do segment = 0, segments-1 + sum_real = 0.0_real32 + sum_imaginary = 0.0_real32 + do offset = segment*segment_length, (segment+1)*segment_length-1 + sample_real = real(samples(first+offset),real32) + sample_imaginary = aimag(samples(first+offset)) + sum_real = sum_real + reference_real(offset)*sample_real + & + reference_imaginary(offset)*sample_imaginary + sum_imaginary = sum_imaginary + reference_real(offset)*sample_imaginary - & + reference_imaginary(offset)*sample_real + end do + energy = energy + real(sum_real*sum_real + sum_imaginary*sum_imaginary,real64) + end do + if (segments == 1) then + values(tone,symbol) = cmplx(sum_real,sum_imaginary,real32) + else + values(tone,symbol) = cmplx(real(sqrt(max(0.0_real64,energy)),real32),0.0_real32,real32) + end if + end do + end do + end subroutine separate_reference + + logical function identical(left,right) + complex(real32), intent(in) :: left(:,:),right(:,:) + identical = all(transfer(left,[0_int64],size(left)) == transfer(right,[0_int64],size(right))) + end function identical + + subroutine require(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if (.not.condition) error stop message + end subroutine require +end program test_jtty_payload_correlators diff --git a/tests/unit/jtty/test_jtty_receive_state.f90 b/tests/unit/jtty/test_jtty_receive_state.f90 new file mode 100644 index 00000000..232679ce --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_state.f90 @@ -0,0 +1,201 @@ +program test_jtty_receive_state + use iso_fortran_env, only: int64 + use jtty_mdec, only: decode,message_assembly,MAX_ACTIVE_MESSAGES,MAX_RECENT_FRAMES, & + nactive,active_messages, & + nrecent,npending,pending_updates,reset_decode_search_state, & + discard_pending_updates,start_message,append_active_message, & + remove_active_message,is_recent_frame,remember_recent_frame, & + prune_receive_state,classify_active_candidate + implicit none + + real, parameter :: frame_period=2.0 + type(decode) :: candidate,oldest_candidate + type(message_assembly) :: accepted_message,classification_existing + integer(int64) :: first_id,last_id + integer :: i,index,nrecent_before,npending_before,nframes_gap,nmissing + logical :: accepted,match,is_window_dupe + + call reset_all() + + candidate=make_candidate(1500.0,10.0,'FIRST FRAME',.false.) + call start_message(candidate,accepted_message,accepted) + index=nactive + call expect(accepted .and. index.eq.1 .and. nactive.eq.1, & + 'an open message enters the active store') + call expect(npending.eq.1 .and. .not.pending_updates(1)%complete, & + 'an open message publishes its initial state') + call expect(nrecent.eq.1 .and. is_recent_frame(candidate), & + 'an accepted frame enters recent history') + first_id=active_messages(1)%message_id + + candidate=make_candidate(1500.0,12.0,' COMPLETE',.true.) + call append_active_message(1,candidate,1,accepted_message,accepted) + call expect(nactive.eq.0 .and. npending.eq.1, & + 'completion frees active capacity without losing its update') + call expect(pending_updates(1)%message_id.eq.first_id .and. & + pending_updates(1)%complete .and. & + trim(pending_updates(1)%decoded).eq.'FIRST FRAME COMPLETE', & + 'completion coalesces the final state by logical identity') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'BEFORE',.false.) + call start_message(candidate,accepted_message,accepted) + first_id=active_messages(1)%message_id + candidate=make_candidate(1500.0,16.0,'~AFTER',.true.) + call append_active_message(1,candidate,3,accepted_message,accepted) + call expect(accepted .and. nactive.eq.0 .and. npending.eq.1, & + 'a maximum in-range gap completes one logical message') + call expect(pending_updates(1)%message_id.eq.first_id .and. & + pending_updates(1)%complete .and. & + trim(pending_updates(1)%decoded).eq.'BEFORE~~~~~AFTER', & + 'gap assembly inserts one sentinel and strips continuation filler') + + do nmissing=1,3 + classification_existing%f1=1500.0 + classification_existing%tsync=10.0 + candidate=make_candidate(1500.0,10.0+real(nmissing+1)*frame_period, & + 'AFTER',.true.) + call classify_active_candidate(classification_existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + if(nmissing.le.2) then + call expect(match .and. .not.is_window_dupe .and. & + nframes_gap.eq.nmissing+1, & + 'classification accepts an in-range missing-frame gap') + else + call expect(.not.match, & + 'classification rejects a gap beyond the merge limit') + endif + enddo + + call reset_decode_search_state() + call expect(nactive.eq.0 .and. nrecent.eq.0 .and. npending.eq.1, & + 'a search reset preserves undelivered updates') + candidate=make_candidate(1510.0,20.0,'AFTER RESET',.true.) + call start_message(candidate,accepted_message,accepted) + call expect(accepted .and. nactive.eq.0 .and. npending.eq.2, & + 'a single-frame completion never occupies active capacity') + call expect(pending_updates(2)%message_id.gt.first_id, & + 'logical identities remain monotonic across search resets') + + call reset_all() + do i=1,MAX_ACTIVE_MESSAGES + candidate=make_candidate(1000.0+real(i),real(i),'OPEN',.false.) + call start_message(candidate,accepted_message,accepted) + call expect(accepted .and. nactive.eq.i, & + 'active messages fill capacity without replacement') + enddo + last_id=active_messages(MAX_ACTIVE_MESSAGES)%message_id + nrecent_before=nrecent + npending_before=npending + candidate=make_candidate(2000.0,100.0,'REFUSED',.false.) + call start_message(candidate,accepted_message,accepted) + call expect(.not.accepted, & + 'a full active store declines a new open message') + call expect(nactive.eq.MAX_ACTIVE_MESSAGES .and. & + nrecent.eq.nrecent_before .and. npending.eq.npending_before, & + 'a declined message leaves every store unchanged') + call remove_active_message(7) + call start_message(candidate,accepted_message,accepted) + index=nactive + call expect(accepted .and. nactive.eq.MAX_ACTIVE_MESSAGES, & + 'freeing one active entry restores capacity') + call expect(active_messages(index)%message_id.eq.last_id+1_int64, & + 'a declined message does not consume a logical identity') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'HISTORY',.true.) + call start_message(candidate,accepted_message,accepted) + call expect(is_recent_frame(candidate), & + 'completion does not remove its frame fingerprint') + call prune_receive_state(11.54,frame_period) + call expect(is_recent_frame(candidate), & + 'history remains until the oldest retro window passes it') + call prune_receive_state(11.56,frame_period) + call expect(.not.is_recent_frame(candidate), & + 'history expires after the rediscovery horizon') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'HISTORY',.true.) + call start_message(candidate,accepted_message,accepted) + candidate=make_candidate(1504.0,10.01,'NEAR SIMULTANEOUS',.true.) + call expect(is_recent_frame(candidate), & + 'recent history rejects a near-simultaneous 4 Hz rediscovery') + candidate=make_candidate(1511.9,10.01,'INSIDE FREQUENCY LIMIT',.true.) + call expect(is_recent_frame(candidate), & + 'recent history catches just inside 12 Hz') + candidate=make_candidate(1512.1,10.01,'OUTSIDE FREQUENCY LIMIT',.true.) + call expect(.not.is_recent_frame(candidate), & + 'recent history allows just outside 12 Hz') + candidate=make_candidate(1505.0,10.049,'INSIDE TIME LIMIT',.true.) + call expect(is_recent_frame(candidate), & + 'recent history catches just inside 0.05 seconds') + candidate=make_candidate(1505.0,10.051,'OUTSIDE TIME LIMIT',.true.) + call expect(.not.is_recent_frame(candidate), & + 'recent history allows just outside 0.05 seconds') + candidate=make_candidate(1500.0,12.0,'ADJACENT MESSAGE',.true.) + call expect(.not.is_recent_frame(candidate), & + 'recent history allows a message one full frame later') + + call reset_all() + do i=1,MAX_RECENT_FRAMES + candidate=make_candidate(1000.0+real(i),real(i),'HISTORY',.true.) + call remember_recent_frame(candidate) + enddo + oldest_candidate=make_candidate(1001.0,1.0,'HISTORY',.true.) + candidate=make_candidate(2500.0,1000.0,'AFTER HISTORY CAPACITY',.true.) + call start_message(candidate,accepted_message,accepted) + call expect(accepted .and. npending.eq.1, & + 'full duplicate history does not block message delivery') + call expect(nrecent.eq.MAX_RECENT_FRAMES .and. is_recent_frame(candidate) .and. & + .not.is_recent_frame(oldest_candidate), & + 'full duplicate history replaces its oldest fingerprint') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'PARTIAL',.false.) + call start_message(candidate,accepted_message,accepted) + index=nactive + active_messages(index)%decoded='PARTIAL GROWN' + active_messages(index)%k=len_trim(active_messages(index)%decoded) + call prune_receive_state(17.59,frame_period) + call expect(nactive.eq.1, & + 'an assembly remains active through its continuation horizon') + call prune_receive_state(17.61,frame_period) + call expect(nactive.eq.0, & + 'an abandoned assembly expires beyond its continuation horizon') + call expect(npending.eq.1 .and. & + trim(pending_updates(1)%decoded).eq.'PARTIAL GROWN' .and. & + .not.pending_updates(1)%complete, & + 'expiration preserves the newest partial state for delivery') + + print *, 'test_jtty_receive_state: all checks passed' + +contains + + function make_candidate(frequency,tsync,text,complete) result(value) + real, intent(in) :: frequency,tsync + character(len=*), intent(in) :: text + logical, intent(in) :: complete + type(decode) :: value + + value%f1=frequency + value%tsync=tsync + value%decoded=text + value%is_last_frame=complete + end function make_candidate + + subroutine reset_all() + call reset_decode_search_state() + call discard_pending_updates() + end subroutine reset_all + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + write(*,'(a)') message + error stop 1 + endif + end subroutine expect + +end program test_jtty_receive_state diff --git a/tests/unit/jtty/test_jtty_replay_ownership.cpp b/tests/unit/jtty/test_jtty_replay_ownership.cpp new file mode 100644 index 00000000..36876033 --- /dev/null +++ b/tests/unit/jtty/test_jtty_replay_ownership.cpp @@ -0,0 +1,107 @@ +#include <QtTest> +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <mutex> +#include <thread> + +#include "JttyReplay.hpp" + +namespace +{ +constexpr int step = 3456; +} + +class TestJttyReplayOwnership : public QObject +{ + Q_OBJECT + + void verifyReplayBoundWithLiveInput () + { + std::atomic<int> liveFrames {3 * step}; + std::mutex mutex; + std::condition_variable changed; + bool ready = false, released = false, done = false; + bool producerReleased = false, producerReady = false, appendFinished = false; + std::thread writer {[&] { + { + std::unique_lock<std::mutex> lock {mutex}; + ready = true; + changed.notify_all (); + producerReleased = changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return released; }); + } + if (producerReleased) + liveFrames.store (4 * step); + { + std::lock_guard<std::mutex> lock {mutex}; + done = true; + changed.notify_all (); + } + }}; + { + std::unique_lock<std::mutex> lock {mutex}; + producerReady = changed.wait_for (lock, std::chrono::seconds {5}, [&] { return ready; }); + } + QVector<int> visited; + int const replayFrames = liveFrames.load (); + replayJttyFrames (replayFrames, [&] (int k) { + visited.append (k); + if (k == step) + { + std::unique_lock<std::mutex> lock {mutex}; + released = true; + changed.notify_all (); + appendFinished = changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return done; }); + } + return false; + }); + writer.join (); + QVERIFY (producerReady); + QVERIFY (producerReleased); + QCOMPARE (liveFrames.load (), 4 * step); + QVERIFY (appendFinished); + // Manual replay is a finite request over its starting receive range; + // audio arriving during a decode belongs to subsequent processing. + QCOMPARE (visited, QVector<int> ({step, 2 * step})); + } + +private Q_SLOTS: + void fixed_range_data () + { + QTest::addColumn<int> ("frames"); + QTest::addColumn<QVector<int>> ("expected"); + QTest::newRow ("empty") << 0 << QVector<int> {}; + QTest::newRow ("short") << step - 1 << QVector<int> {}; + QTest::newRow ("boundary") << step << QVector<int> {}; + QTest::newRow ("past-boundary") << step + 1 << QVector<int> {step}; + QTest::newRow ("multiple") << 3 * step << QVector<int> {step, 2 * step}; + } + + void fixed_range () + { + QFETCH (int, frames); + QFETCH (QVector<int>, expected); + QVector<int> visited; + replayJttyFrames (frames, [&] (int k) { visited.append (k); return false; }); + QCOMPARE (visited, expected); + } + + void picked_stop_processed_once () + { + int frames = 8 * step; + int stop = 5000; + QVector<int> visited; + replayJttyFrames (frames, [&] (int k) { + visited.append (k); + return k >= stop; + }); + QCOMPARE (visited, QVector<int> ({step, 2 * step})); + } + + void replay_is_bounded_at_start () { verifyReplayBoundWithLiveInput (); } +}; + +QTEST_GUILESS_MAIN (TestJttyReplayOwnership) +#include "test_jtty_replay_ownership.moc" diff --git a/tests/unit/jtty/test_jtty_source_codec.f90 b/tests/unit/jtty/test_jtty_source_codec.f90 new file mode 100644 index 00000000..dead01d8 --- /dev/null +++ b/tests/unit/jtty/test_jtty_source_codec.f90 @@ -0,0 +1,202 @@ +program test_jtty_source_codec + use jtty_mod + implicit none + type(jtty_source_atom) :: atom,decoded,atoms(2) + character(len=34) :: frame,frames(MAX_FRAMES) + character(len=80) :: text + logical :: valid,eom + integer :: i,nframes + character(len=34), parameter :: CALL_VECTORS(0:5)=[character(len=34) :: & + '0000100110111101111000110101000001','0000100110111101111000110101010001', & + '0000100110111101111000110101100001','0000100110111101111000110101110001', & + '0000100110111101111000110101000101','0000100110111101111000110101010101'] + character(len=34), parameter :: NUM_VECTORS(0:7)=[character(len=34) :: & + '1000000000000000000001000000001001','1000100000000000000001000000001001', & + '1001000000000000000001000000001001','1001100000000000000001000000001001', & + '1010000000000000000001000000001001','1010100000000000000001000000001001', & + '1011000000000000000001000000001001','1011100000000000000001000000001001'] + character(len=34), parameter :: LOC_VECTORS(0:4)=[character(len=34) :: & + '1000000000000110111010000000011001','1000100000000110111010000000011001', & + '1001000000000110111010000000011001','1001100000000110111010000000011001', & + '1010000000000110111010000000011001'] + character(len=34), parameter :: CONTROL_VECTORS(0:17)=[character(len=34) :: & + '0000000000000000000000000001001001','0000000000100000000000000001001001', & + '0000000001000000000000000001001001','0000000001100000000000000001001001', & + '0000000010000000000000000001001001','0000000010100000000000000001001001', & + '0000000011000000000000000001001001','0000000011100000000000000001001001', & + '0000000100000000000000000001001001','0000000100100000000000000001001001', & + '0000000101000000000000000001001001','0000000101100000000000000001001001', & + '0000000110000000000000000001001001','0000000110100000000000000001001001', & + '0000000111000000000000000001001001','0000000111100000000000000001001001', & + '0000001000000000000000000001001001','0000001000100000000000000001001001'] + + do i=0,5 + call expect_vector(jtty_call_atom(i,'K1ABC'),CALL_VECTORS(i)) + enddo + do i=0,7 + call expect_vector(jtty_exch_num_atom(JTTY_ROLE_FULL,i,1),NUM_VECTORS(i)) + enddo + do i=0,4 + call expect_vector(jtty_exch_loc_atom(JTTY_ROLE_FULL,i,'CA'),LOC_VECTORS(i)) + enddo + call expect_vector(jtty_zone_loc_atom(5,'NWT'), & + '0000001011011110010000110100101001') + call expect_vector(jtty_class_section_atom(1,'D',11), & + '0010000010110001011000000000101001') + call expect_vector(jtty_exch_num_time_atom(JTTY_ROLE_FULL,156,17*60+49), & + '1000000100111001000010110100111001') + call expect_vector(jtty_control_atom(JTTY_CONTROL_AGN), & + '0000000000000000000000000001001001') + call expect_vector(jtty_grid4_atom(JTTY_ROLE_FIELD_ONLY,'FN42'), & + '0001001010000110011000000001001001') + call expect_vector(jtty_text5_atom('HELLO'), & + '0100010011100101010101010110001101') + + do i=0,17 + atom=jtty_control_atom(i) + call expect_vector(atom,CONTROL_VECTORS(i)) + call round_trip(atom,text) + if(trim(text).ne.trim(CONTROL_TEXT(i))) error stop 'control rendering mismatch' + enddo + + atoms(1)=jtty_call_atom(JTTY_CALL_CALL,'K1ABC') + atoms(2)=jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,7) + call pack_jtty_atoms(atoms,2,frames,nframes,valid) + if(.not.valid .or. nframes.ne.2) error stop 'atom sequence rejected' + if(frames(1)(33:34).ne.'00' .or. frames(2)(33:34).ne.'01') error stop 'EOM mismatch' + + atom=jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_QTH,'0CA') + call expect_rejected(atom,'noncanonical base36') + call expect_rejected(jtty_exch_loc_atom(1,0,'A-'),'invalid base36 digit') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,0),'CQ zone minimum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,41),'CQ zone maximum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,0),'ITU zone minimum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,91),'ITU zone maximum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_LICENSE_YEAR,10000),'license year') + call expect_rejected(jtty_exch_num_time_atom(1,16384,0),'time serial') + call expect_rejected(jtty_exch_num_time_atom(1,0,1440),'minute') + call expect_rejected(jtty_zone_loc_atom(0,'CA'),'pair zone') + call expect_rejected(jtty_class_section_atom(0,'A',1),'transmitter count') + call expect_rejected(jtty_class_section_atom(33,'A',1),'transmitter count') + call expect_rejected(jtty_class_section_atom(1,'G',1),'class') + call expect_rejected(jtty_class_section_atom(1,'A',0),'section') + call expect_rejected(jtty_class_section_atom(1,'A',87),'section') + call expect_rejected(jtty_grid4_atom(1,'SA00'),'grid field') + call expect_rejected(jtty_grid4_atom(1,'AA0A'),'grid digit') + call expect_rejected(jtty_call_atom(JTTY_CALL_CALL,'BAD'),'malformed call') + + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,0)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,131071)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,1)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,40)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,1)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,90)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_LICENSE_YEAR,9999)) + call expect_legal(jtty_exch_loc_atom(1,0,'00')) + call expect_legal(jtty_exch_loc_atom(1,0,'100')) + call expect_legal(jtty_exch_num_time_atom(1,0,0)) + call expect_legal(jtty_exch_num_time_atom(1,16383,1439)) + call expect_legal(jtty_class_section_atom(1,'A',1)) + call expect_legal(jtty_class_section_atom(32,'F',86)) + call expect_legal(jtty_grid4_atom(1,'AA00')) + call expect_legal(jtty_grid4_atom(1,'RR99')) + + call expect_render(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,999),'599 999') + call expect_render(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,1000),'599 1000') + call expect_render(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,131071),'599 131071') + call expect_render(jtty_exch_num_atom(0,JTTY_NUM_CHECK,7),'07') + call expect_render(jtty_exch_num_atom(0,JTTY_NUM_CHECK,100),'100') + call expect_render(jtty_exch_num_time_atom(1,16383,1439),'599 16383 2359') + + frame=repeat('0',34) + call unpack_jtty_atom(frame,decoded,valid,eom) + if(valid .or. eom) error stop 'all-zero sentinel accepted' + atom=jtty_control_atom(0); call pack_jtty_atom(atom,frame,.true.,valid) + frame(33:33)='1'; call unpack_jtty_atom(frame,decoded,valid,eom) + if(valid .or. eom) error stop 'reserved bit 33 accepted' + atom=jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,1) + call pack_jtty_atom(atom,frame,.true.,valid) + frame(27:27)='1'; call unpack_jtty_atom(frame,decoded,valid,eom) + if(valid .or. eom) error stop 'reserved STRUCT30 field accepted' + atom=jtty_control_atom(0); call pack_jtty_atom(atom,frame,.true.,valid) + frame(28:30)='101'; call expect_invalid_frame(frame,'reserved family') + atom=jtty_control_atom(0); call pack_jtty_atom(atom,frame,.true.,valid) + frame(1:4)='0010'; call expect_invalid_frame(frame,'reserved MISC subtype') + atom=jtty_zone_loc_atom(1,'CA'); call pack_jtty_atom(atom,frame,.true.,valid) + frame(1:3)='010'; call expect_invalid_frame(frame,'reserved pair schema') + + write(*,'(a)') 'test_jtty_source_codec: all checks passed' + +contains + subroutine expect_vector(source,want) + type(jtty_source_atom), intent(in) :: source + character(len=34), intent(in) :: want + type(jtty_source_atom) :: result + character(len=34) :: got + logical :: ok,last + call pack_jtty_atom(source,got,.true.,ok) + if(.not.ok .or. got.ne.want) then + write(*,'(a,/,a,/,a)') 'golden vector mismatch',want,got + error stop 1 + endif + call unpack_jtty_atom(got,result,ok,last) + if(.not.ok .or. .not.last) error stop 'golden vector did not unpack' + end subroutine expect_vector + + subroutine round_trip(source,rendered) + type(jtty_source_atom), intent(in) :: source + character(len=80), intent(out) :: rendered + type(jtty_source_atom) :: result + character(len=34) :: got + logical :: ok,last + call pack_jtty_atom(source,got,.true.,ok) + if(.not.ok) error stop 'round-trip pack failed' + call unpack_jtty_atom(got,result,ok,last) + if(.not.ok) error stop 'round-trip unpack failed' + call render_jtty_atom(result,rendered,ok) + if(.not.ok) error stop 'round-trip render failed' + end subroutine round_trip + + subroutine expect_legal(source) + type(jtty_source_atom), intent(in) :: source + character(len=34) :: got + logical :: ok + call pack_jtty_atom(source,got,.true.,ok) + if(.not.ok) error stop 'legal boundary rejected' + end subroutine expect_legal + + subroutine expect_render(source,want) + type(jtty_source_atom), intent(in) :: source + character(len=*), intent(in) :: want + character(len=80) :: got + call round_trip(source,got) + if(trim(got).ne.want) then + write(*,'(a,/,a,/,a)') 'canonical rendering mismatch',want,trim(got) + error stop 1 + endif + end subroutine expect_render + + subroutine expect_rejected(source,label) + type(jtty_source_atom), intent(in) :: source + character(len=*), intent(in) :: label + character(len=34) :: got + logical :: ok + call pack_jtty_atom(source,got,.true.,ok) + if(ok) then + write(*,'(a,a)') 'invalid atom accepted: ',label + error stop 1 + endif + end subroutine expect_rejected + + subroutine expect_invalid_frame(got,label) + character(len=34), intent(in) :: got + character(len=*), intent(in) :: label + type(jtty_source_atom) :: result + logical :: ok,last + call unpack_jtty_atom(got,result,ok,last) + if(ok .or. last) then + write(*,'(a,a)') 'invalid frame accepted or completed EOM: ',label + error stop 1 + endif + end subroutine expect_invalid_frame +end program test_jtty_source_codec diff --git a/tests/unit/jtty/test_jtty_sticky_retry.f90 b/tests/unit/jtty/test_jtty_sticky_retry.f90 new file mode 100644 index 00000000..719b1ecf --- /dev/null +++ b/tests/unit/jtty/test_jtty_sticky_retry.f90 @@ -0,0 +1,155 @@ +program test_jtty_sticky_retry + + ! decode_and_merge's sticky-sync retry rescues a continuation frame whose + ! own sync symbols are too degraded for the blind search to find, by + ! redecoding directly at the position remembered from the slot it + ! continues -- bypassing the blind search's sync-quality gate entirely. + ! Two bugs in that retry (found in PR #337 review by David Christle, + ! fixed in 48b9e6d74) meant it could silently fail or read the wrong + ! frequency's data. Reproducing the real stochastic conditions that + ! trigger it (weak SNR, fading) isn't reliable for a regression test, so + ! this instead forces it deterministically: frame 2's 13 sync tones are + ! shifted by 2 (mod 4), guaranteeing zero matches against the true sync + ! pattern -- so the blind search's nsync<=6 gate rejects it outright, + ! regardless of what the coarse candidate search finds -- while frame + ! 2's 46 payload tones are left untouched. If the retry works, it merges + ! anyway; if not, frame 2's contribution is silently missing. A second, + ! in-band signal is superimposed so the shared c1 work array actually + ! gets shifted away from the target's own frequency before the retry + ! runs -- see the comment at its construction below for why. + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + integer :: failures + + failures=0 + call run_case('WB9XYZ 599 0123',3,failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_sticky_retry: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_sticky_retry: all checks passed' + +contains + + subroutine run_case(message,nframes,count) + character(len=*), intent(in) :: message + integer, intent(in) :: nframes + integer, intent(inout) :: count + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: tones(MAX_FRAMES*frame_symbols) + integer :: qrm_tones(frame_symbols) + integer :: nsym,qrm_nsym,nsamples,total_samples,ib,i0 + integer(int16), allocatable :: pcm(:) + real, allocatable :: wave(:),qrm_wave(:),combined(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: input,qrm_input + + call discard_pending_updates() + input=message + call genjtty(input,tones,nsym) + call expect(nsym.eq.nframes*frame_symbols, & + 'the message has the expected frame count',count) + + ! Frame 2's sync tones start right after frame 1's 59 symbols. + ib=frame_symbols+1 + tones(ib:ib+size(is13)-1)=mod(is13+2,4) + + ! rjtty_sub only processes a window once nchunk (1.25 frame periods) + ! more data is available past its start; without a trailing pad past + ! the message's own end, the internal quarter-step sweep runs out of + ! data before ever reaching the window that would check frame 2's + ! continuation, blind or sticky-retry alike (matches the same padding + ! test_jtty_adjacent_decode.f90 uses for the same reason). + nsamples=nsym*nsps + total_samples=nsamples+frame_symbols*nsps + allocate(wave(nsamples),complex_wave(total_samples),combined(total_samples)) + allocate(pcm(total_samples)) + call gen_jttywave(tones,nsym,nsps,2.0,12000.0,1500.0, & + complex_wave,wave,0,nsamples) + combined=0. + combined(1:nsamples)=wave + + ! twkfreq unconditionally re-shifts the shared c1 work array for + ! every candidate the blind search tries this call, whether or not + ! it decodes -- so by the time the sticky retry runs, c1 reflects + ! whichever candidate was tried last, not necessarily the target's + ! own frequency. A single clean signal with no competing candidate + ! doesn't exercise that (verified: reverting 48b9e6d74 didn't fail + ! this test until the interferer below was added) -- an in-band + ! interferer (within ftol=50 Hz of f0=1500, so channel 0's own + ! search sees it) gives c1 something else to be shifted to. Tiled + ! from one short message repeated across the buffer, at lower + ! amplitude so it can't preempt the target's own frame 1 decode. + qrm_input='N2PPI' + call genjtty(qrm_input,qrm_tones,qrm_nsym) + allocate(qrm_wave(qrm_nsym*nsps)) + call gen_jttywave(qrm_tones,qrm_nsym,nsps,2.0,12000.0,1540.0, & + complex_wave(1:qrm_nsym*nsps),qrm_wave,0,qrm_nsym*nsps) + i0=1 + do while(i0.le.total_samples) + ib=min(total_samples,i0+qrm_nsym*nsps-1) + combined(i0:ib)=combined(i0:ib)+0.3*qrm_wave(1:ib-i0+1) + i0=i0+qrm_nsym*nsps + enddo + + pcm=int(nint(30000.0*combined),int16) + + ! nfb=1499 (not the usual Wide Graph range) keeps channels 1 and 2 -- + ! whose hardwired bands, [1200,1500] and [1500,1800], meet exactly at + ! the target's own f0 -- from independently retrying the same slot + ! themselves and masking a channel-0-specific failure: the target's + ! own estimated frequency lands a couple of Hz above 1500, just + ! inside channel 2's band too, so without this its own sticky retry + ! can coincidentally rescue the frame channel 0's retry failed to. + call rjtty_sub(pcm,1,nsps,200,1499,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,1499,1500.0,50.0) + + call expect(npending.eq.2,'the decoder keeps the target and interferer', & + count) + call expect(found_complete(message), & + 'the full message decodes despite the corrupted sync',count) + + deallocate(pcm,wave,complex_wave,combined,qrm_wave) + end subroutine run_case + + logical function found_complete(message) + character(len=*), intent(in) :: message + integer :: i + + found_complete=.false. + do i=1,npending + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(message) .and. & + pending_updates(i)%complete) found_complete=.true. + enddo + end function found_complete + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_sticky_retry diff --git a/tests/unit/jtty/test_jtty_structured_decode.f90 b/tests/unit/jtty/test_jtty_structured_decode.f90 new file mode 100644 index 00000000..e74b9c2a --- /dev/null +++ b/tests/unit/jtty/test_jtty_structured_decode.f90 @@ -0,0 +1,330 @@ +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 jtty_fec, only: is13,PAYLOAD_BITS,TOTAL_K,tbcc_encode + use jtty_tbcc_code_profiles + 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, & + JTTY_NUM_SERIAL,JTTY_ATOM_CALL,JTTY_ATOM_EXCH_NUM,JTTY_ATOM_EXCH_LOC, & + JTTY_ATOM_EXCH_PAIR, & + JTTY_ATOM_CONTROL,JTTY_ATOM_GRID4,JTTY_LOC_STATE_PROVINCE, & + JTTY_PAIR_CLASS_SECTION,JTTY_CONTROL_QSL_TU,JTTY_ROLE_FIELD_ONLY, & + JTTY_ENCODE_OK,JTTY_ENCODE_INVALID_DESCRIPTOR, & + JTTY_ENCODE_UNKNOWN_SECTION + implicit none + + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: failures + + interface + function jtty_cpp_n1mm_smoke(tones,nsym) result(status) bind(C) + import :: c_int + 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) + 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) + import :: c_int + integer(c_int), intent(out) :: tones(*),nsym + integer(c_int) :: status + end function jtty_cpp_rtty_smoke + subroutine genjtty_atoms(atoms,natoms,itone,nsym) + use jtty_mod, only: jtty_source_atom + type(jtty_source_atom), intent(in) :: atoms(:) + integer, intent(in) :: natoms + integer, intent(out) :: itone(*) + integer, intent(out) :: nsym + end subroutine genjtty_atoms + subroutine genjtty_atoms_c(atoms,natoms,itone,nsym,status) bind(C,name='genjtty_atoms_c') + import :: c_int,jtty_source_atom_c + type(jtty_source_atom_c), intent(in) :: atoms(*) + integer(c_int), value, intent(in) :: natoms + integer(c_int), intent(out) :: itone(*) + integer(c_int), intent(out) :: nsym + integer(c_int), intent(out) :: status + end subroutine genjtty_atoms_c + end interface + + failures=0 + call reject_reserved_struct_family(failures) + call decode_native_call_and_serial(failures) + call decode_c_adapter_atoms(failures) + call reject_invalid_c_descriptors(failures) + call decode_cpp_compiled_n1mm(failures) + call decode_compact_text(failures) + call decode_profile_text(failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_structured_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_structured_decode: all checks passed' + +contains + + subroutine decode_profile_text(count) + integer, intent(inout) :: count + integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols,status + + status=jtty_cpp_rtty_smoke(tones,nsymbols) + 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 + end subroutine decode_profile_text + + subroutine decode_compact_text(count) + integer, intent(inout) :: count + 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) + 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 + + text='TEST WB9XYZ 599 123 QSL TU' + call genjtty(text,tones,nsymbols) + call expect(nsymbols.eq.4*frame_symbols,'mixed text generates four frames',count) + if(nsymbols.ne.4*frame_symbols) return + call decode_waveform(tones,nsymbols,10.0) + call expect(npending.eq.1,'mixed text produces one update on the transmitted channel',count) + if(npending.eq.1) then + call expect(trim(normalized(pending_updates(1)%decoded)).eq.trim(text) .and. & + pending_updates(1)%complete .and. nactive.eq.0, & + 'mixed TEXT5/call/exchange/control preserves spacing and EOM',count) + endif + end subroutine decode_compact_text + + subroutine decode_cpp_compiled_n1mm(count) + integer, intent(inout) :: count + integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols,status + + status=jtty_cpp_n1mm_smoke(tones,nsymbols) + call expect(status.eq.JTTY_ENCODE_OK .and. nsymbols.eq.2*frame_symbols, & + 'C++ compiled descriptors cross the native encoder ABI',count) + if(status.ne.JTTY_ENCODE_OK .or. nsymbols.ne.2*frame_symbols) return + call decode_waveform(tones,int(nsymbols)) + call expect(npending.eq.1,'C++ compiled N1MM message produces one update',count) + if(npending.ne.1) return + call expect(trim(normalized(pending_updates(1)%decoded)).eq.'W9XYZ 32D EMA' .and. & + pending_updates(1)%complete .and. nactive.eq.0, & + 'C++ call/exchange descriptors preserve canonical text and EOM',count) + end subroutine decode_cpp_compiled_n1mm + + subroutine decode_native_call_and_serial(count) + integer, intent(inout) :: count + type(jtty_source_atom) :: atoms(2) + integer :: tones(MAX_FRAMES*frame_symbols),nsymbols + + atoms(1)=jtty_call_atom(JTTY_CALL_CALL,'WB9XYZ') + atoms(2)=jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,1234) + call genjtty_atoms(atoms,size(atoms),tones,nsymbols) + + call expect(nsymbols.eq.size(atoms)*frame_symbols, & + '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) + end subroutine decode_native_call_and_serial + + subroutine decode_c_adapter_atoms(count) + integer, intent(inout) :: count + type(jtty_source_atom_c) :: atoms(6) + 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) + call initialize_c_atom(atoms(1),JTTY_ATOM_CALL,JTTY_CALL_CALL,0,0,'K1ABC') + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_NUM,JTTY_NUM_SERIAL, & + JTTY_ROLE_FULL,12,'') + call initialize_c_atom(atoms(3),JTTY_ATOM_EXCH_LOC,JTTY_LOC_STATE_PROVINCE, & + 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 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) + end subroutine decode_c_adapter_atoms + + subroutine reject_invalid_c_descriptors(count) + integer, intent(inout) :: count + type(jtty_source_atom_c) :: atom(1) + 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') + atom(1)%reserved=1 + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects nonzero reserved byte',count) + call expect(status.eq.JTTY_ENCODE_INVALID_DESCRIPTOR, & + 'C adapter identifies invalid descriptor',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_CALL,JTTY_CALL_CALL,0,0,'K1ABC') + atom(1)%text='A' + 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) + + call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,0,0,1,'EMA') + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects non-CLASS_SECTION pair schema',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_GRID4,0,0,0,'SA00') + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects invalid GRID4',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_CONTROL,18,0,0,'') + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects unassigned control phrase',count) + end subroutine reject_invalid_c_descriptors + + 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 + character(len=*), intent(in) :: text + integer :: i,n + + atom%kind=kind; atom%subtype=subtype; atom%role=role; atom%reserved=0 + atom%value=value; atom%text=c_null_char + n=min(8,len_trim(text)) + do i=1,n + atom%text(i)=text(i:i) + enddo + end subroutine initialize_c_atom + + subroutine reject_reserved_struct_family(count) + integer, intent(inout) :: count + character(len=34) :: frame,frames(MAX_FRAMES) + character(len=80) :: decoded + integer(int32) :: payload(PAYLOAD_BITS),encoded(TOTAL_K) + integer :: tones(frame_symbols) + logical :: source_valid,is_last_frame + + ! With an otherwise-zero STRUCT30 body, n32=22 selects reserved family 101. + write(frame(1:32),'(b32.32)') 22_int32 + frame(33:34)='01' + frames='' + frames(1)=frame + call unpack_jtty(frames,1,decoded,is_last_frame=is_last_frame, & + source_valid=source_valid) + call expect(.not.source_valid, & + 'reserved STRUCT30 family is source-invalid',count) + call expect(.not.is_last_frame, & + 'source-invalid frame cannot report EOM',count) + + read(frame,'(34i1)') payload + call tbcc_encode(payload,encoded,JTTY_TBCC_PROFILE_1167_1545_80F) + tones(1:size(is13))=is13 + tones(size(is13)+1:frame_symbols)=encoded + call decode_waveform(tones,frame_symbols) + call expect(npending.eq.0 .and. nactive.eq.0, & + 'CRC/FEC-valid source-invalid frame creates no message or update',count) + end subroutine reject_reserved_struct_family + + subroutine decode_waveform(tones,nsymbols,channel_width) + integer, intent(in) :: tones(:),nsymbols + real, intent(in), optional :: channel_width + integer :: nsamples,total_samples,nfa,nfb + real :: tolerance + integer(int16), allocatable :: pcm(:) + real, allocatable :: wave(:) + complex, allocatable :: complex_wave(:) + + nsamples=nsymbols*nsps + total_samples=(nsymbols+frame_symbols)*nsps + allocate(wave(nsamples),complex_wave(nsamples),pcm(total_samples)) + call gen_jttywave(tones,nsymbols,nsps,2.0,12000.0,1500.0, & + complex_wave,wave,0,nsamples) + pcm=0_int16 + pcm(1:nsamples)=int(nint(30000.0*wave),int16) + + nfa=200; nfb=2800; tolerance=50.0 + if(present(channel_width)) then + tolerance=channel_width + nfa=ceiling(1500.0-tolerance) + nfb=floor(1500.0+tolerance) + endif + call discard_pending_updates() + call rjtty_sub(pcm,1,nsps,nfa,nfb,1500.0,tolerance) + call rjtty_sub(pcm,total_samples,nsps,nfa,nfb,1500.0,tolerance) + + deallocate(pcm,wave,complex_wave) + end subroutine decode_waveform + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + result_value=display_message_text(value) + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_structured_decode diff --git a/tests/unit/jtty/test_jtty_surface_ranges.f90 b/tests/unit/jtty/test_jtty_surface_ranges.f90 new file mode 100644 index 00000000..97f9b65c --- /dev/null +++ b/tests/unit/jtty/test_jtty_surface_ranges.f90 @@ -0,0 +1,98 @@ +program test_jtty_surface_ranges + use iso_fortran_env, only: int16 + use fftw3, only: fftwf_cleanup + use jtty_fec, only: is13,TOTAL_K + use jtty_mod, only: MAX_FRAMES + use jtty_mdec, only: npending,pending_updates,discard_pending_updates, & + jtty_release_fft_resources + implicit none + integer, parameter :: ncases=8 + integer, parameter :: rates(ncases)=[240,320,384,240,480,480,384,240] + integer, parameter :: scenarios(ncases)=[1,1,1,4,2,1,3,1] + integer :: icase + complex :: fft_scratch(1) + + ! Direct tests own the frequency-window Cartesian product. Keep integration + ! cases for every FFT geometry and each distinct surface-search behavior. + do icase=1,ncases + if(icase.eq.ncases) then + ! Prove that a populated geometry can be recreated after teardown. + call jtty_release_fft_resources() + call four2a(fft_scratch,-1,1,1,1) + call fftwf_cleanup() + endif + call verify_surface_case(rates(icase),scenarios(icase)) + enddo + + call jtty_release_fft_resources() + print *, 'JTTY surface range tests passed' + +contains + + subroutine verify_surface_case(nsps,icase) + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer, intent(in) :: nsps,icase + integer :: nsym,nsamples,nlead,total_samples + integer :: tones(MAX_FRAMES*frame_symbols),nfa,nfb + integer(int16), allocatable :: pcm(:) + real, allocatable :: wave(:) + complex, allocatable :: cwave(:) + real :: hz,fc,width + character(len=80) :: message + + call discard_pending_updates() + hz=1500.0 + fc=hz + width=50.0 + nfa=200 + nfb=2800 + select case(icase) + case(2) + ! Auxiliary channels follow graph limits away from their nominal bands. + hz=2700.0 + fc=900.0 + width=3.0 + nfa=2600 + nfb=2750 + case(3) + ! The QSO channel remains usable with an inverted graph range. + hz=400.0 + fc=hz + width=3.0 + nfa=1800 + nfb=1200 + case(4) + ! Narrow, non-bin-aligned limits still need the smoothing halo. + hz=1504.0 + fc=hz + width=0.5 + nfa=1504 + nfb=1505 + end select + + message='N2PPI' + call genjtty(message,tones,nsym) + nsamples=nsym*nsps + nlead=1800 + ! One 1.25-frame chunk contains the lead-in and complete signal. A + ! longer buffer only schedules empty trailing decoder windows. + total_samples=frame_symbols*nsps+(frame_symbols*nsps)/4 + if(nlead+nsamples.gt.total_samples) & + error stop 'surface fixture exceeds one decoder chunk' + allocate(pcm(total_samples),wave(nsamples),cwave(nsamples)) + call gen_jttywave(tones,nsym,nsps,2.0,12000.0,hz,cwave,wave,0,nsamples) + pcm=0_int16 + pcm(nlead+1:nlead+nsamples)=int(nint(14000.0*wave),int16) + call rjtty_sub(pcm,1,nsps,nfa,nfb,fc,width) + call rjtty_sub(pcm,total_samples,nsps,nfa,nfb,fc,width) + if(npending.ne.1) then + print *, 'Unexpected message count',nsps,icase,npending + stop 1 + endif + if(trim(pending_updates(1)%decoded).ne.'N2PPI' .or. & + .not.pending_updates(1)%complete) then + print *, 'Unexpected message',nsps,icase,pending_updates(1)%decoded + stop 1 + endif + end subroutine verify_surface_case +end program diff --git a/tests/unit/jtty/test_jtty_tbcc_code_profile.f90 b/tests/unit/jtty/test_jtty_tbcc_code_profile.f90 new file mode 100644 index 00000000..f49bcf60 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tbcc_code_profile.f90 @@ -0,0 +1,115 @@ +program test_jtty_tbcc_code_profile + use, intrinsic :: iso_fortran_env, only: int32, real32 + use jtty_tbcc_code_profiles + use jtty_tbcc_decoder, only: jtty_tbcc_decode + use jtty_tbcc_list_decoder, only: jtty_tbcc_crc_valid + use jtty_mdec, only: jtty_tbcc_reencode_for_subtraction + use tbcc, only: PAYLOAD_BITS, TOTAL_K, encode_crc12, tbcc_encode, & + tbcc_wava_fsk_decode + implicit none + + integer(int32), parameter :: golden_payload(PAYLOAD_BITS) = [ & + 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0, & + 1,0,0,1,0,0,1,0,0,1 ] + integer(int32), parameter :: golden_information_bits(TOTAL_K) = [ & + 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0, & + 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0 ] + integer(int32), parameter :: golden_encoded_bits(2, TOTAL_K) = reshape([ & + 1,0, 0,0, 0,1, 0,0, 1,0, 1,1, 0,1, 1,1, 0,1, 1,1, & + 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, & + 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, & + 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, & + 0,0, 0,1, 1,1, 0,0, 1,0, 1,0 ], [2, TOTAL_K]) + integer(int32), parameter :: golden_tones(TOTAL_K) = [ & + 3,0,1,0,3,2,1,2,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1, & + 2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,3,3 ] + + call expect_descriptor() + call expect_golden_code() + + print *, 'test_jtty_tbcc_code_profile: all checks passed' + +contains + + subroutine expect_descriptor() + type(jtty_tbcc_code_profile) :: unsupported + + call require(jtty_tbcc_code_profile_is_valid(JTTY_TBCC_PROFILE_1167_1545_80F), & + 'established code descriptor is invalid') + call require(jtty_tbcc_code_profile_is_supported(JTTY_TBCC_PROFILE_1167_1545_80F), & + 'established code descriptor is unsupported') + call require(JTTY_TBCC_PROFILE_1167_1545_80F%memory_nu == 9_int32 .and. & + JTTY_TBCC_PROFILE_1167_1545_80F%state_count == 512_int32, & + 'established code trellis dimensions changed') + call require(JTTY_TBCC_PROFILE_1167_1545_80F%generator_0 == int(o'1167', int32) .and. & + JTTY_TBCC_PROFILE_1167_1545_80F%generator_1 == int(o'1545', int32), & + 'established generator polynomials changed') + call require(JTTY_TBCC_PROFILE_1167_1545_80F%outer_polynomial == int(z'80F', int32), & + 'established outer polynomial changed') + + unsupported = JTTY_TBCC_PROFILE_1167_1545_80F + unsupported%generator_1 = int(o'1547', int32) + call require(jtty_tbcc_code_profile_is_valid(unsupported), & + 'unsupported-code fixture is not structurally valid') + call require(.not.jtty_tbcc_code_profile_is_supported(unsupported), & + 'noncanonical code was reported as supported') + end subroutine expect_descriptor + + subroutine expect_golden_code() + integer(int32) :: encoded_information(2, TOTAL_K), encoded_bits(2, TOTAL_K) + integer(int32) :: invalid_information(TOTAL_K) + integer(int32) :: tones(TOTAL_K), subtraction_tones(TOTAL_K) + integer(int32) :: decoded(PAYLOAD_BITS) + real(real32) :: tone_energies(0:3, TOTAL_K) + complex(real32) :: correlations(0:3, TOTAL_K) + logical :: success + + call encode_crc12(golden_payload, encoded_information, JTTY_TBCC_PROFILE_1167_1545_80F) + call require(all(encoded_information(1, :) == golden_information_bits), & + 'outer-check bits changed from the golden vector') + call require(jtty_tbcc_crc_valid(JTTY_TBCC_PROFILE_1167_1545_80F, & + encoded_information(1, :)), 'golden outer-check word was rejected') + invalid_information = encoded_information(1, :) + invalid_information(TOTAL_K) = 1_int32 - invalid_information(TOTAL_K) + call require(.not.jtty_tbcc_crc_valid(JTTY_TBCC_PROFILE_1167_1545_80F, & + invalid_information), 'outer check accepted a corrupted word') + + call tbcc_encode(golden_payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F, encoded_bits) + call require(all(encoded_bits == golden_encoded_bits), & + 'encoded bits changed from the golden vector') + call require(all(tones == golden_tones), 'tones changed from the golden vector') + + call make_noiseless_observations(tones, tone_energies, correlations) + call tbcc_wava_fsk_decode(tone_energies, 4_int32, 2_int32, decoded, success, & + reserved_zero_bit=33_int32, code_profile=JTTY_TBCC_PROFILE_1167_1545_80F) + call require(success .and. all(decoded == golden_payload), 'WAVA decode failed') + call jtty_tbcc_decode(correlations, correlations, decoded, success) + call require(success .and. all(decoded == golden_payload), 'coherent decode failed') + + call jtty_tbcc_reencode_for_subtraction(golden_payload, subtraction_tones) + call require(all(subtraction_tones == golden_tones), & + 'subtraction re-encoding did not reproduce the established tones') + end subroutine expect_golden_code + + subroutine make_noiseless_observations(tones, tone_energies, correlations) + integer(int32), intent(in) :: tones(TOTAL_K) + real(real32), intent(out) :: tone_energies(0:3, TOTAL_K) + complex(real32), intent(out) :: correlations(0:3, TOTAL_K) + integer(int32) :: symbol + + tone_energies = 0.0_real32 + correlations = cmplx(0.0_real32, 0.0_real32, real32) + do symbol = 1, TOTAL_K + tone_energies(tones(symbol), symbol) = 100.0_real32 + correlations(tones(symbol), symbol) = cmplx(100.0_real32, 0.0_real32, real32) + end do + end subroutine make_noiseless_observations + + subroutine require(condition, message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if (.not.condition) error stop message + end subroutine require + +end program test_jtty_tbcc_code_profile diff --git a/tests/unit/jtty/test_jtty_tbcc_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 new file mode 100644 index 00000000..50fb6f63 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 @@ -0,0 +1,143 @@ +program test_jtty_tbcc_decoder + use, intrinsic :: iso_fortran_env, only: int32, int64, real32 + use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F + use jtty_tbcc_decoder, only: jtty_tbcc_decode, jtty_tbcc_decode_result + use tbcc, only: PAYLOAD_BITS, TOTAL_K, tbcc_encode + implicit none + + complex(real32) :: correlations(0:3, TOTAL_K), halves(0:3, TOTAL_K) + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS), tones(TOTAL_K) + type(jtty_tbcc_decode_result) :: result + logical :: success + integer(int32) :: bit_index + + do bit_index = 1, PAYLOAD_BITS + payload(bit_index) = modulo(bit_index + bit_index/3, 2) + end do + payload(33) = 0_int32 + halves = cmplx(0.0_real32, 0.0_real32, real32) + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, correlations) + + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(success, 'coherence ladder rejected a noiseless payload') + call require(all(decoded == payload), 'coherence ladder changed the payload') + call require(result%accepted_hypothesis_rank == 1_int32, & + 'noiseless payload was not the first hypothesis') + call require(result%coherent_block_length == 1_int32, & + 'noiseless payload did not stop at one-symbol coherence') + call require(result%evaluated_rung_count == 1_int32, & + 'noiseless payload evaluated unnecessary coherence rungs') + call require(.not.result%used_half_symbol_observation, & + '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') + + payload(33) = 1_int32 + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, correlations) + decoded = huge(0_int32) + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(.not.success, 'coherence ladder accepted reserved bit one') + call require(all(decoded == 0_int32), & + 'reserved-bit rejection left a stale payload') + + halves = correlations + 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, 'half-symbol fallback accepted reserved bit one') + call require(all(decoded == 0_int32), & + 'half-symbol reserved-bit rejection left a stale payload') + + payload(33) = 0_int32 + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, halves) + decoded = huge(0_int32) + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(success .and. all(decoded == payload), 'half-symbol fallback failed to rescue payload') + call require(result%used_half_symbol_observation .and. result%coherent_block_length == 1, & + 'half-symbol fallback used the wrong observation or coherence') + call require(result%evaluated_rung_count == 4, 'fallback skipped an M1 rung') + halves = cmplx(0.0_real32, 0.0_real32, real32) + + payload = 0_int32 + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, correlations) + decoded = huge(0_int32) + 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') + + 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_coherent_decodes() + + print *, 'test_jtty_tbcc_decoder: all checks passed' + +contains + + 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], & + ranks(2) = [2,1], evaluated_rungs(2) = [2,1] + integer(int64) :: state + integer :: fixture, symbol, tone, bit + real(real32) :: in_phase, quadrature + + do bit = 1, PAYLOAD_BITS + payload(bit) = modulo(bit + bit/3,2) + end do + payload(33) = 0 + call tbcc_encode(payload,tones,JTTY_TBCC_PROFILE_1167_1545_80F) + halves = cmplx(0.0_real32,0.0_real32,real32) + do fixture = 1, size(seeds) + state = seeds(fixture) + do symbol = 1, TOTAL_K + do tone = 0, 3 + state = modulo(48271_int64*state,2147483647_int64) + in_phase = real(state,real32)/2147483647.0_real32 - 0.5_real32 + state = modulo(48271_int64*state,2147483647_int64) + quadrature = real(state,real32)/2147483647.0_real32 - 0.5_real32 + correlations(tone,symbol) = cmplx(in_phase,quadrature,real32) + end do + correlations(tones(symbol),symbol) = correlations(tones(symbol),symbol) + & + cmplx(0.55_real32,0.0_real32,real32) + end do + call jtty_tbcc_decode(correlations,halves,decoded,success,result) + call require(success .and. all(decoded == payload),'coherent rung failed to decode fixed payload') + call require(result%coherent_block_length == lengths(fixture), 'coherent decode used wrong rung') + call require(result%accepted_hypothesis_rank == ranks(fixture), 'coherent decode candidate rank changed') + call require(result%evaluated_rung_count == evaluated_rungs(fixture), & + 'accepted candidate triggered unnecessary confirmation or fallback') + call require(.not.result%used_half_symbol_observation, 'coherent decode fell through to M2') + end do + end subroutine expect_coherent_decodes + + subroutine make_noiseless_correlations(symbols, values) + integer(int32), intent(in) :: symbols(TOTAL_K) + complex(real32), intent(out) :: values(0:3, TOTAL_K) + integer(int32) :: symbol + + values = cmplx(0.0_real32, 0.0_real32, real32) + do symbol = 1, TOTAL_K + values(symbols(symbol), symbol) = cmplx(100.0_real32, 0.0_real32, real32) + end do + end subroutine make_noiseless_correlations + + subroutine require(condition, message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if (.not.condition) error stop message + end subroutine require + +end program test_jtty_tbcc_decoder diff --git a/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 new file mode 100644 index 00000000..d8b4eed7 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 @@ -0,0 +1,300 @@ +program test_jtty_tbcc_list_decoder + use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64 + use jtty_tbcc_code_profiles, only: jtty_tbcc_code_profile, & + JTTY_TBCC_PROFILE_1167_1545_80F + use tbcc, only: tbcc_encode, encode_crc12 + use jtty_tbcc_list_decoder + implicit none + + call expect_optimized_reference_parity() + call expect_noiseless_tailbiting_decode() + call expect_reserved_bit_pruning() + call expect_deterministic_hypothesis_budget() + call expect_coherent_normalization() + + print *, 'test_jtty_tbcc_list_decoder: all checks passed' + +contains + + subroutine expect_optimized_reference_parity() + integer(int32), parameter :: coherent_lengths(3) = [1_int32, 2_int32, 4_int32] + integer(int32), parameter :: survivor_widths(2) = [1_int32, 4_int32] + type(jtty_tbcc_decoder_plan) :: plan + type(jtty_tbcc_decoder_workspace) :: workspace + 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 + + do wraps = 1, 2 + do coherent_index = 1, size(coherent_lengths) + do width_index = 1, size(survivor_widths) + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, & + coherent_lengths(coherent_index), survivor_widths(width_index), wraps, & + JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + coherent_lengths(coherent_index), survivor_widths(width_index), wraps, .false.) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + coherent_lengths(coherent_index), survivor_widths(width_index), wraps, .true.) + end do + end do + end do + + ! Equal branch energies exercise deterministic ties and wrap deduplication. + correlations = cmplx(0.0_real32, 0.0_real32, real32) + do width_index = 1, 4 + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, 4_int32, & + width_index, 2_int32, JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + 4_int32, width_index, 2_int32, .false.) + end do + + ! A common large branch collapses distinct accumulated metrics into ties. + do symbol = 1, JTTY_TBCC_INFORMATION_BITS + do tone = 0, 3 + correlations(tone, symbol) = scale(1.0_real32, -18)*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 + correlations(:, 13) = cmplx(scale(1.0_real32, 20), 0.0_real32, real32) + do coherent_index = 1, size(coherent_lengths) + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, & + coherent_lengths(coherent_index), 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + coherent_lengths(coherent_index), 4_int32, 2_int32, .false.) + end do + end subroutine expect_optimized_reference_parity + + subroutine expect_decode_parity(code, plan, workspace, correlations, & + coherent_length, survivor_width, wraps, prune) + type(jtty_tbcc_code_profile), intent(in) :: code + type(jtty_tbcc_decoder_plan), intent(in) :: plan + type(jtty_tbcc_decoder_workspace), intent(inout) :: workspace + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(in) :: coherent_length, survivor_width, wraps + logical, intent(in) :: prune + integer(int32) :: reference_bits(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: optimized_bits(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: reference_states(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: optimized_states(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: reference_count, optimized_count, reference_pool, optimized_pool + integer(int64) :: reference_ids(JTTY_TBCC_MAX_HYPOTHESES) + integer(int64) :: optimized_ids(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: reference_clean(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: optimized_clean(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: reference_wava(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: optimized_wava(JTTY_TBCC_MAX_HYPOTHESES) + logical :: reference_crc(JTTY_TBCC_MAX_HYPOTHESES) + logical :: optimized_crc(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: tracked_bits(JTTY_TBCC_INFORMATION_BITS) = 0_int32 + integer(int32) :: reference_pool_rank, optimized_pool_rank, reference_h_rank, optimized_h_rank + logical :: reference_present, optimized_present + + call jtty_tbcc_list_wava_reference(correlations, code, coherent_length, & + survivor_width, wraps, JTTY_TBCC_MAX_HYPOTHESES, reference_bits, & + reference_ids, reference_clean, reference_wava, reference_states, & + reference_crc, reference_count, reference_pool, prune_reserved_zero=prune, & + reference_bits=tracked_bits, reference_present=reference_present, & + reference_pool_rank=reference_pool_rank, reference_h_rank=reference_h_rank) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, optimized_bits, & + optimized_ids, optimized_clean, optimized_wava, optimized_states, & + optimized_crc, optimized_count, optimized_pool, prune_reserved_zero=prune, & + reference_bits=tracked_bits, reference_present=optimized_present, & + reference_pool_rank=optimized_pool_rank, reference_h_rank=optimized_h_rank) + + if (reference_count /= optimized_count .or. reference_pool /= optimized_pool .or. & + any(reference_bits /= optimized_bits) .or. any(reference_ids /= optimized_ids) .or. & + .not.real_arrays_agree(reference_clean, optimized_clean) .or. & + .not.real_arrays_agree(reference_wava, optimized_wava) .or. & + any(reference_states /= optimized_states) .or. & + any(reference_crc .neqv. optimized_crc) .or. & + (reference_present .neqv. optimized_present) .or. & + reference_pool_rank /= optimized_pool_rank .or. reference_h_rank /= optimized_h_rank) & + error stop 'TBCC list decoder optimized/reference mismatch' + end subroutine expect_decode_parity + + subroutine expect_noiseless_tailbiting_decode() + type(jtty_tbcc_code_profile) :: code + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: information_bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: tones(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: candidates(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states(JTTY_TBCC_MAX_HYPOTHESES), candidate_count, pool_count + integer(int64) :: identities(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean_metrics(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: path_metrics(JTTY_TBCC_MAX_HYPOTHESES), rescored_metric + logical :: crc_valid(JTTY_TBCC_MAX_HYPOTHESES), closed + + code = JTTY_TBCC_PROFILE_1167_1545_80F + call make_codeword(.false., information_bits, tones) + call make_noiseless_correlations(tones, correlations) + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, candidates, identities, clean_metrics, path_metrics, & + states, crc_valid, candidate_count, pool_count, prune_reserved_zero=.true.) + + if (candidate_count < 1_int32 .or. pool_count < candidate_count) & + error stop 'TBCC list decoder returned no noiseless candidate' + if (any(candidates(:, 1) /= information_bits) .or. .not.crc_valid(1)) & + error stop 'TBCC list decoder noiseless candidate mismatch' + if (states(1) /= jtty_tbcc_tailbiting_state(code, information_bits)) & + error stop 'TBCC list decoder tail-biting state mismatch' + call jtty_tbcc_score_candidate(code, correlations, 4_int32, candidates(:, 1), & + rescored_metric, closed) + if (.not.closed .or. rescored_metric /= clean_metrics(1) .or. & + abs(clean_metrics(1) - 46.0_real64) > 1.0e-12_real64) & + error stop 'TBCC list decoder final L2 block or clean rescore mismatch' + end subroutine expect_noiseless_tailbiting_decode + + subroutine expect_reserved_bit_pruning() + type(jtty_tbcc_code_profile) :: code + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: information_bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: tones(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: candidates(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states(JTTY_TBCC_MAX_HYPOTHESES), candidate_count, pool_count + integer(int64) :: identities(JTTY_TBCC_MAX_HYPOTHESES), forbidden_identity + real(real64) :: clean_metrics(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: path_metrics(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_valid(JTTY_TBCC_MAX_HYPOTHESES) + + code = JTTY_TBCC_PROFILE_1167_1545_80F + call make_codeword(.true., information_bits, tones) + call make_noiseless_correlations(tones, correlations) + forbidden_identity = jtty_tbcc_candidate_identity(information_bits) + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, candidates, identities, clean_metrics, path_metrics, & + states, crc_valid, candidate_count, pool_count, prune_reserved_zero=.false.) + if (candidate_count < 1_int32 .or. identities(1) /= forbidden_identity) & + error stop 'TBCC list decoder unpruned control mismatch' + + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, candidates, identities, clean_metrics, path_metrics, & + states, crc_valid, candidate_count, pool_count, prune_reserved_zero=.true.) + if (candidate_count > 0_int32) then + if (any(candidates(JTTY_TBCC_RESERVED_BIT, 1:candidate_count) /= 0_int32)) & + error stop 'TBCC list decoder reserved-bit pruning failed' + if (any(identities(1:candidate_count) == forbidden_identity)) & + error stop 'TBCC list decoder retained reserved-invalid identity' + end if + end subroutine expect_reserved_bit_pruning + + subroutine expect_deterministic_hypothesis_budget() + type(jtty_tbcc_code_profile) :: code + 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) + integer(int32) :: states_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: count_a, count_b, pool_a, pool_b, rank + 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) :: path_a(JTTY_TBCC_MAX_HYPOTHESES), path_b(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_a(JTTY_TBCC_MAX_HYPOTHESES), crc_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: one_bit(JTTY_TBCC_INFORMATION_BITS, 1), one_state(1) + integer(int32) :: one_count, one_pool + integer(int64) :: one_id(1) + real(real64) :: one_clean(1), one_path(1) + logical :: one_crc(1) + + code = JTTY_TBCC_PROFILE_1167_1545_80F + correlations = cmplx(0.0_real32, 0.0_real32, real32) + call jtty_tbcc_list_wava(correlations, code, 4_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, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, bits_b, ids_b, clean_b, path_b, states_b, & + crc_b, count_b, pool_b, prune_reserved_zero=.true.) + + if (count_a /= JTTY_TBCC_MAX_HYPOTHESES .or. count_b /= count_a .or. & + pool_a < count_a .or. pool_b /= pool_a) & + error stop 'TBCC list decoder did not enforce the H4 budget' + if (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(path_a, path_b) .or. any(crc_a .neqv. crc_b)) & + error stop 'TBCC list decoder tie order is not deterministic' + do rank = 2, count_a + if (ids_a(rank) <= ids_a(rank - 1)) & + error stop 'TBCC list decoder did not deduplicate tied identities' + end do + + call jtty_tbcc_list_wava(correlations, code, 4_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 (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' + end subroutine expect_deterministic_hypothesis_budget + + subroutine expect_coherent_normalization() + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: tones4(4), tones2(2) + real(real64) :: metric + + correlations = cmplx(0.0_real32, 0.0_real32, real32) + tones4 = [0_int32, 1_int32, 2_int32, 3_int32] + correlations(0, 3) = cmplx(1.0_real32, 0.0_real32, real32) + correlations(1, 4) = cmplx(2.0_real32, 0.0_real32, real32) + correlations(2, 5) = cmplx(3.0_real32, 0.0_real32, real32) + correlations(3, 6) = cmplx(4.0_real32, 0.0_real32, real32) + metric = jtty_tbcc_coherent_metric(correlations, 3_int32, tones4) + if (metric /= 25.0_real64) error stop 'TBCC L4 normalization mismatch' + + tones2 = [1_int32, 3_int32] + correlations(1, 45) = cmplx(2.0_real32, 0.0_real32, real32) + correlations(3, 46) = cmplx(4.0_real32, 0.0_real32, real32) + metric = jtty_tbcc_coherent_metric(correlations, 45_int32, tones2) + if (metric /= 18.0_real64) error stop 'TBCC final L2 normalization mismatch' + end subroutine expect_coherent_normalization + + subroutine make_codeword(set_reserved_bit, information_bits, tones) + logical, intent(in) :: set_reserved_bit + integer(int32), intent(out) :: information_bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(out) :: tones(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: payload(34), encoded(2, JTTY_TBCC_INFORMATION_BITS), bit_index + + do bit_index = 1, size(payload) + payload(bit_index) = modulo(5*bit_index + bit_index/3, 2) + end do + payload(JTTY_TBCC_RESERVED_BIT) = merge(1_int32, 0_int32, set_reserved_bit) + call encode_crc12(payload, encoded, JTTY_TBCC_PROFILE_1167_1545_80F) + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + information_bits = encoded(1, :) + end subroutine make_codeword + + subroutine make_noiseless_correlations(tones, correlations) + integer(int32), intent(in) :: tones(JTTY_TBCC_INFORMATION_BITS) + complex(real32), intent(out) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: symbol + + correlations = cmplx(0.0_real32, 0.0_real32, real32) + do symbol = 1, JTTY_TBCC_INFORMATION_BITS + correlations(tones(symbol), symbol) = cmplx(1.0_real32, 0.0_real32, real32) + end do + end subroutine make_noiseless_correlations + + pure logical function real_arrays_agree(left, right) result(agree) + real(real64), intent(in) :: left(:), right(:) + integer(int32) :: element + + agree = size(left) == size(right) + if (.not.agree) return + do element = 1, size(left) + if (left(element) == right(element)) cycle + if (abs(left(element)-right(element)) <= 64.0_real64*epsilon(0.0_real64)* & + max(1.0_real64, abs(left(element)), abs(right(element)))) cycle + agree = .false. + return + end do + end function real_arrays_agree + +end program test_jtty_tbcc_list_decoder diff --git a/tests/unit/jtty/test_jtty_txstream.cpp b/tests/unit/jtty/test_jtty_txstream.cpp new file mode 100644 index 00000000..d71be2a6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_txstream.cpp @@ -0,0 +1,487 @@ +#include <QtTest/QtTest> +#include <QSignalSpy> +#include <QPointer> +#include <QThread> +#include <QVector> + +#include "Audio/AudioDevice.hpp" +#include "Audio/TxAudioQueue.hpp" +#include "Audio/TxIdentity.hpp" +#include "Audio/TxPlaybackEvidence.hpp" +#include "Audio/TxRequest.hpp" +#include "Modulator/JttyPcmFifo.hpp" +#include "Modulator/JttyTxStream.hpp" + +// Unit tests for the JTTY async transmit source. These exercise the FIFO / +// served-sample mechanics, the drain predicate, and the drained() edge signal +// without any audio hardware: readData() is driven through the public +// QIODevice::read() API after opening the device with initialize(). + +class TestJttyTxStream : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase (); + void gaplessConcatAndSilencePad (); + void clearResetsCounters (); + void clearThenEnqueueSkipsOldSamples (); + void clearDuringPartialPlaybackSkipsRemainder (); + void pendingResetProgressExcludesAbortedAudio (); + void fifoOverflowRejectsWithoutTruncating (); + void fifoWrappedEnqueuePreservesOrder (); + void enqueueFitPredicate (); + void fifoDrainStateCarriesEpochAndTotal (); + void fifoDrainAfterResetUsesNewEpochAndTotal (); + void fifoEpochBoundaryAfterNaturalDrainResetsTotal (); + void drainedPredicate (); + void readDoesNotEmitDrainedDirectly (); + void timerEmitsDrainedEdge (); + void drainedEmittedFromWorkerThread (); + void sourceCommitUsesCurrentRealExtent (); + void staleQueueEpochDoesNotStart (); + void sourceCommitIsEmittedOncePerStart (); +}; + +namespace +{ + // Default drain guard baked into JttyTxStream when start() has not run (no + // device buffer to measure). Mirrors DEFAULT_DRAIN_GUARD in JttyTxStream.cpp. + constexpr int DEFAULT_GUARD = 9600; + + TxEvidence::TxRequest jttyRequest (qint64 sessionId, qint64 generation, + qint64 queueEpoch = -1) + { + TxEvidence::TxRequest request; + request.mode = QStringLiteral ("JTTY"); + request.session_id = TxEvidence::TxSessionId {sessionId}; + request.generation = TxEvidence::TxGeneration {generation}; + request.queue_epoch = TxAudioQueueEpoch { + queueEpoch >= 0 ? queueEpoch : sessionId}; + return request; + } + + TxAudioQueueEpoch queueEpoch (qint64 value) + { + return TxAudioQueueEpoch {value}; + } + + QVector<qint16> readFrames (JttyTxStream & s, int frames) + { + QByteArray buf (frames * 2, '\xff'); + qint64 got = s.read (buf.data (), buf.size ()); + QVector<qint16> out; + if (got <= 0) return out; + int n = int (got / 2); + qint16 const * p = reinterpret_cast<qint16 const *> (buf.constData ()); + for (int i = 0; i < n; ++i) out.append (p[i]); + return out; + } +} + +void TestJttyTxStream::initTestCase () +{ + qRegisterMetaType<TxAudioQueueDrainState> ("TxAudioQueueDrainState"); +} + +void TestJttyTxStream::gaplessConcatAndSilencePad () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (1); + queue.clear (epoch); + JttyTxStream s {queue}; + QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); + + // Two messages queued before any are consumed: they must chain with no gap. + QVERIFY (queue.enqueue (QVector<qint16> {10, 20, 30}, epoch).accepted); + QVERIFY (queue.enqueue (QVector<qint16> {40, 50}, epoch).accepted); + QCOMPARE (queue.progress ().total_samples, qint64 (5)); + + // Pull 7 frames: 5 real samples concatenated in order, then silence padding. + QVector<qint16> got = readFrames (s, 7); + QCOMPARE (got.size (), 7); + QCOMPARE (got, (QVector<qint16> {10, 20, 30, 40, 50, 0, 0})); + + QCOMPARE (queue.progress ().served_samples, qint64 (5)); // padding is not counted as real + + // A late message resumes real audio after the silence (late-message path). + QVERIFY (queue.enqueue (QVector<qint16> {60}, epoch).accepted); + QCOMPARE (queue.progress ().total_samples, qint64 (6)); + QVector<qint16> more = readFrames (s, 2); + QCOMPARE (more, (QVector<qint16> {60, 0})); + QCOMPARE (queue.progress ().served_samples, qint64 (6)); +} + +void TestJttyTxStream::clearResetsCounters () +{ + TxAudioQueue queue; + auto const firstEpoch = queueEpoch (1); + queue.clear (firstEpoch); + JttyTxStream s {queue}; + QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3}, firstEpoch).accepted); + (void) readFrames (s, 2); + queue.clear (queueEpoch (2)); + QCOMPARE (queue.progress ().total_samples, qint64 (0)); + QCOMPARE (queue.progress ().served_samples, qint64 (0)); + // After clear the device pads pure silence. + QCOMPARE (readFrames (s, 3), (QVector<qint16> {0, 0, 0})); +} + +void TestJttyTxStream::clearThenEnqueueSkipsOldSamples () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 1)); + fifo.clear (2); + QVERIFY (fifo.enqueue (QVector<qint16> {4, 5}, 2)); + + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QCOMPARE (fifo.queuedReal (), qint64 (2)); + + QVector<qint16> got; + for (int i = 0; i < 4; ++i) got.append (fifo.pullSample (2)); + QCOMPARE (got, (QVector<qint16> {4, 5, 0, 0})); + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (2)); +} + +void TestJttyTxStream::clearDuringPartialPlaybackSkipsRemainder () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3, 4, 5}, 1)); + QCOMPARE (fifo.pullSample (2), qint16 (1)); + QCOMPARE (fifo.pullSample (2), qint16 (2)); + + fifo.clear (2); + QCOMPARE (fifo.totalReal (), qint64 (0)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QCOMPARE (fifo.queuedReal (), qint64 (0)); + + QVERIFY (fifo.enqueue (QVector<qint16> {6}, 2)); + QCOMPARE (fifo.pullSample (2), qint16 (6)); + QCOMPARE (fifo.pullSample (2), qint16 (0)); + QCOMPARE (fifo.totalReal (), qint64 (1)); + QCOMPARE (fifo.servedReal (), qint64 (1)); +} + +void TestJttyTxStream::pendingResetProgressExcludesAbortedAudio () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3, 4, 5}, 1)); + QCOMPARE (fifo.pullSample (2), qint16 (1)); + QCOMPARE (fifo.pullSample (2), qint16 (2)); + + fifo.clear (2); + QVERIFY (fifo.enqueue (QVector<qint16> {6, 7}, 2)); + + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QCOMPARE (fifo.queuedReal (), qint64 (2)); + QCOMPARE (fifo.pullSample (2), qint16 (6)); + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (1)); + QCOMPARE (fifo.queuedReal (), qint64 (1)); +} + +void TestJttyTxStream::fifoOverflowRejectsWithoutTruncating () +{ + JttyPcmFifo fifo {4}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 11)); + QVERIFY (!fifo.enqueue (QVector<qint16> {4, 5}, 11)); + QCOMPARE (fifo.totalReal (), qint64 (3)); + + QVector<qint16> got; + for (int i = 0; i < 5; ++i) got.append (fifo.pullSample (2)); + QCOMPARE (got, (QVector<qint16> {1, 2, 3, 0, 0})); +} + +void TestJttyTxStream::fifoWrappedEnqueuePreservesOrder () +{ + JttyPcmFifo fifo {5}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3, 4}, 11)); + QCOMPARE (fifo.pullSample (2), qint16 (1)); + QCOMPARE (fifo.pullSample (2), qint16 (2)); + QCOMPARE (fifo.pullSample (2), qint16 (3)); + + QVERIFY (fifo.enqueue (QVector<qint16> {5, 6, 7}, 11)); + + QVector<qint16> got; + for (int i = 0; i < 5; ++i) got.append (fifo.pullSample (2)); + QCOMPARE (got, (QVector<qint16> {4, 5, 6, 7, 0})); + QCOMPARE (fifo.totalReal (), qint64 (7)); + QCOMPARE (fifo.servedReal (), qint64 (7)); +} + +void TestJttyTxStream::enqueueFitPredicate () +{ + QVERIFY (jttyPcmEnqueueFits (4, 0, 4)); + QVERIFY (jttyPcmEnqueueFits (4, 2, 2)); + QVERIFY (jttyPcmEnqueueFits (4, 4, 0)); + QVERIFY (!jttyPcmEnqueueFits (4, 1, 4)); + QVERIFY (!jttyPcmEnqueueFits (4, 5, 1)); + QVERIFY (!jttyPcmEnqueueFits (0, 0, 1)); + QVERIFY (!jttyPcmEnqueueFits (4, -1, 1)); +} + +void TestJttyTxStream::fifoDrainStateCarriesEpochAndTotal () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 21)); + for (int i = 0; i < 5; ++i) (void) fifo.pullSample (2); + + auto drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (21)); + QCOMPARE (drain.totalAtDrain, qint64 (3)); + + QVERIFY (fifo.enqueue (QVector<qint16> {4}, 21)); + for (int i = 0; i < 3; ++i) (void) fifo.pullSample (2); + drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (21)); + QCOMPARE (drain.totalAtDrain, qint64 (4)); + + fifo.clear (22); + QCOMPARE (fifo.totalReal (), qint64 (0)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QVERIFY (!fifo.takeDrainReady ().ready); +} + +void TestJttyTxStream::fifoDrainAfterResetUsesNewEpochAndTotal () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 21)); + fifo.clear (22); + QVERIFY (!fifo.takeDrainReady ().ready); + QVERIFY (fifo.enqueue (QVector<qint16> {4, 5}, 22)); + + for (int i = 0; i < 4; ++i) (void) fifo.pullSample (2); + auto drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (22)); + QCOMPARE (drain.totalAtDrain, qint64 (2)); +} + +void TestJttyTxStream::fifoEpochBoundaryAfterNaturalDrainResetsTotal () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 21)); + for (int i = 0; i < 5; ++i) (void) fifo.pullSample (2); + + auto drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (21)); + QCOMPARE (drain.totalAtDrain, qint64 (3)); + + fifo.clear (22); + QVERIFY (fifo.enqueue (QVector<qint16> {4, 5}, 22)); + for (int i = 0; i < 4; ++i) (void) fifo.pullSample (2); + + drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (22)); + QCOMPARE (drain.totalAtDrain, qint64 (2)); +} + +void TestJttyTxStream::drainedPredicate () +{ + // Nothing queued yet => not drained. + QVERIFY (!jttyTxDrained (0, 0, 100, 0, 10)); + + // Real audio still to be pulled => not drained. + QVERIFY (!jttyTxDrained (3, 5, 50, 5, 10)); + + // All pulled but trailing silence has not yet covered the buffer depth. + QVERIFY (!jttyTxDrained (5, 5, 12, 5, 10)); // 12-5 = 7 < 10 + + // All pulled and trailing silence covers the buffer depth => drained. + QVERIFY (jttyTxDrained (5, 5, 15, 5, 10)); // 15-5 = 10 >= 10 + QVERIFY (jttyTxDrained (5, 5, 99, 5, 10)); +} + +void TestJttyTxStream::readDoesNotEmitDrainedDirectly () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (31); + queue.clear (epoch); + JttyTxStream s {queue}; + QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); + QSignalSpy spy (&s, &JttyTxStream::drained); + + QVERIFY (queue.enqueue (QVector<qint16> {7, 7, 7}, epoch).accepted); + (void) readFrames (s, 3 + DEFAULT_GUARD); + QCOMPARE (spy.count (), 0); +} + +void TestJttyTxStream::timerEmitsDrainedEdge () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (41); + queue.clear (epoch); + JttyTxStream s {queue}; + QSignalSpy spy (&s, &JttyTxStream::drained); + + QVERIFY (queue.enqueue (QVector<qint16> {7, 7, 7}, epoch).accepted); + s.start (jttyRequest (41, 1), nullptr); + + // Serve the 3 real samples plus exactly the guard worth of trailing silence. + (void) readFrames (s, 3 + DEFAULT_GUARD); + QTRY_COMPARE (spy.count (), 1); + auto drain = qvariant_cast<TxAudioQueueDrainState> (spy.at (0).at (0)); + QCOMPARE (drain.epoch, epoch); + QCOMPARE (drain.total_at_drain, qint64 (3)); + + // Further silence must not re-emit (edge-triggered). + (void) readFrames (s, 1000); + QCOMPARE (spy.count (), 1); + + // A new message clears the drain edge; draining again emits once more. + QVERIFY (queue.enqueue (QVector<qint16> {9}, epoch).accepted); + (void) readFrames (s, 1 + DEFAULT_GUARD); + QTRY_COMPARE (spy.count (), 2); + drain = qvariant_cast<TxAudioQueueDrainState> (spy.at (1).at (0)); + QCOMPARE (drain.epoch, epoch); + QCOMPARE (drain.total_at_drain, qint64 (4)); + s.stop (); +} + +void TestJttyTxStream::drainedEmittedFromWorkerThread () +{ + // Integration test: drive the stream the way the app does, with the object + // moved onto a dedicated worker thread (m_audioThread in production). The + // drain timer is a parented child, so it must ride to the worker thread and + // tick there; a value-member timer could not be started cross-thread and + // drained() would never fire (this test would then time out). start() and the + // audio pull run on the worker thread; drained() must cross back to the + // main-thread receiver. + TxAudioQueue queue; + auto const epoch = queueEpoch (51); + queue.clear (epoch); + auto * stream = new JttyTxStream {queue}; + QPointer<JttyTxStream> streamWitness {stream}; + qint64 drainedSession {-1}; + qint64 drainedTotal {-1}; + int drainedCount {0}; + QObject receiver; + // Qt 5's QSignalSpy records through a direct connection, so explicitly queue + // cross-thread test state onto a main-thread receiver. + connect (stream, &JttyTxStream::drained, &receiver, + [&drainedSession, &drainedTotal, &drainedCount] + (TxAudioQueueDrainState drain) { + drainedSession = drain.epoch.value (); + drainedTotal = drain.total_at_drain; + ++drainedCount; + }, Qt::QueuedConnection); + + QVERIFY (queue.enqueue (QVector<qint16> {7, 7, 7}, epoch).accepted); + + QThread worker; + stream->moveToThread (&worker); + connect (&worker, &QThread::finished, stream, &QObject::deleteLater); + + // Queue before starting the worker so thread creation establishes the + // cross-thread handoff. + QMetaObject::invokeMethod (stream, [stream] { + stream->start (jttyRequest (51, 1), nullptr); + QByteArray buf ((3 + DEFAULT_GUARD) * 2, '\0'); + stream->read (buf.data (), buf.size ()); + }, Qt::QueuedConnection); + worker.start (); + + QTRY_COMPARE_WITH_TIMEOUT (drainedCount, 1, 2000); + QCOMPARE (drainedSession, qint64 (51)); + QCOMPARE (drainedTotal, qint64 (3)); + + // The stream owns timers that must stop and be destroyed on their thread. + QVERIFY (QMetaObject::invokeMethod ( + stream, "stop", Qt::BlockingQueuedConnection)); + worker.quit (); + QVERIFY (worker.wait (2000)); + QVERIFY (streamWitness.isNull ()); +} + +void TestJttyTxStream::sourceCommitUsesCurrentRealExtent () +{ + auto const snapshot = makeJttyTxStartSnapshot (jttyRequest (61, 7), 3); + QCOMPARE (snapshot.session_id.value (), qint64 (61)); + QCOMPARE (snapshot.generation.value (), qint64 (7)); + QCOMPARE (snapshot.mode, QString {"JTTY"}); + QCOMPARE (snapshot.sample_rate_hz, 48000); + QCOMPARE (snapshot.committed_end_sample, qint64 (3)); + QVERIFY (!snapshot.target_known); + QVERIFY (!snapshot.diagnostic.isEmpty ()); + + TxAudioQueue queue; + auto const epoch = queueEpoch (61); + queue.clear (epoch); + JttyTxStream stream {queue}; + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3}, epoch).accepted); + TxEvidence::TxStartSnapshot committed; + int commitCount {0}; + connect (&stream, &JttyTxStream::txSourceCommitted, &stream, + [&committed, &commitCount] (TxEvidence::TxStartSnapshot snapshot) { + committed = snapshot; + ++commitCount; + }); + + stream.start (jttyRequest (61, 7), nullptr); + QCOMPARE (commitCount, 1); + QCOMPARE (committed.committed_end_sample, qint64 (2)); + (void) readFrames (stream, 3 + DEFAULT_GUARD); + QCOMPARE (queue.progress ().served_samples, qint64 (3)); + stream.stop (); +} + +void TestJttyTxStream::staleQueueEpochDoesNotStart () +{ + TxAudioQueue queue; + auto const current = queueEpoch (81); + queue.clear (current); + QVERIFY (queue.enqueue (QVector<qint16> {7, 8, 9}, current).accepted); + + JttyTxStream stream {queue}; + TxEvidence::TxStartSnapshot committed; + int commitCount {0}; + connect (&stream, &JttyTxStream::txSourceCommitted, &stream, + [&committed, &commitCount] (TxEvidence::TxStartSnapshot snapshot) { + committed = snapshot; + ++commitCount; + }); + stream.start (jttyRequest (80, 1), nullptr); + QVERIFY (!stream.isActive ()); + QCOMPARE (commitCount, 0); + + stream.start (jttyRequest (81, 2), nullptr); + QVERIFY (stream.isActive ()); + QCOMPARE (commitCount, 1); + QCOMPARE (committed.committed_end_sample, qint64 (2)); + stream.stop (); +} + +void TestJttyTxStream::sourceCommitIsEmittedOncePerStart () +{ + TxAudioQueue queue; + JttyTxStream stream {queue}; + QVector<TxEvidence::TxStartSnapshot> commits; + connect (&stream, &JttyTxStream::txSourceCommitted, &stream, + [&commits] (TxEvidence::TxStartSnapshot snapshot) {commits.append (snapshot);}); + + queue.clear (queueEpoch (71)); + stream.start (jttyRequest (71, 1), nullptr); + stream.start (jttyRequest (71, 1), nullptr); + QCOMPARE (commits.size (), 1); + QCOMPARE (commits.at (0).committed_end_sample, qint64 (-1)); + stream.stop (); + + queue.clear (queueEpoch (72)); + stream.start (jttyRequest (72, 2), nullptr); + QCOMPARE (commits.size (), 2); + QCOMPARE (commits.at (0).session_id.value (), qint64 (71)); + QCOMPARE (commits.at (1).session_id.value (), qint64 (72)); + QCOMPARE (commits.at (1).generation.value (), qint64 (2)); + stream.stop (); +} + +QTEST_MAIN (TestJttyTxStream) +#include "test_jtty_txstream.moc" diff --git a/tests/unit/jtty/test_jtty_windowed_decode.f90 b/tests/unit/jtty/test_jtty_windowed_decode.f90 new file mode 100644 index 00000000..19bb345f --- /dev/null +++ b/tests/unit/jtty/test_jtty_windowed_decode.f90 @@ -0,0 +1,160 @@ +program test_jtty_windowed_decode + + ! rjtty_sub_windowed bounds the scan to [istart0,istop] instead of the + ! whole buffer -- used by MainWindow::jttyDecodeAgainAt() for a WideGraph + ! click-driven re-decode. Two messages placed far apart in time: a window + ! covering only one message must find only that one; a window covering + ! both (or the unwindowed rjtty_sub) must find both; and decoded content + ! for a message fully inside its window must match the unwindowed result + ! exactly (windowing must not corrupt what it does decode). + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + character(len=*), parameter :: msg_a='MAYBE YOU SHOULD HELP' + character(len=*), parameter :: msg_b='CLAUDE CO 3 MIN TRANSITION' + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + real, parameter :: dt_a=0.2, dt_b=40.0 + integer :: failures + integer :: first_start,second_start,first_samples,second_samples,total_samples + integer(int16), allocatable :: pcm(:) + character(len=80) :: decoded_a_full,decoded_a_windowed + + failures=0 + + call build_pair(pcm,total_samples,first_start,first_samples,second_start,second_samples) + + ! Baseline: unwindowed scan finds both messages. + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,50.0) + call expect(found(msg_a),'unwindowed: first message found',failures) + call expect(found(msg_b),'unwindowed: second message found',failures) + decoded_a_full=decoded_text(msg_a) + + ! Window covering only the first message: second must not appear. + call discard_pending_updates() + call rjtty_sub_windowed(pcm,1,nsps,200,2800,1500.0,50.0,1,1) + call rjtty_sub_windowed(pcm,first_start+first_samples+2*chunk(), & + nsps,200,2800,1500.0,50.0,1,first_start+first_samples+2*chunk()) + call expect(found(msg_a),'window on first message: first message found',failures) + call expect(.not.found(msg_b),'window on first message: second message absent',failures) + decoded_a_windowed=decoded_text(msg_a) + call expect(trim(decoded_a_windowed).eq.trim(decoded_a_full), & + 'windowed decode content matches unwindowed content',failures) + + ! Window covering only the second message: first must not appear. + call discard_pending_updates() + call rjtty_sub_windowed(pcm,1,nsps,200,2800,1500.0,50.0, & + max(1,second_start-2*chunk()),total_samples) + call rjtty_sub_windowed(pcm,total_samples,nsps,200,2800,1500.0,50.0, & + max(1,second_start-2*chunk()),total_samples) + call expect(.not.found(msg_a),'window on second message: first message absent',failures) + call expect(found(msg_b),'window on second message: second message found',failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_windowed_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_windowed_decode: all checks passed' + +contains + + integer function chunk() + integer :: nframe + nframe=59*nsps + chunk=nframe+nframe/4 + end function chunk + + subroutine build_pair(pcm,total_samples,first_start,first_samples, & + second_start,second_samples) + integer(int16), allocatable, intent(out) :: pcm(:) + integer, intent(out) :: total_samples,first_start,first_samples + integer, intent(out) :: second_start,second_samples + integer :: first_tones(MAX_FRAMES*frame_symbols) + integer :: second_tones(MAX_FRAMES*frame_symbols) + integer :: first_symbols,second_symbols,i,idx,pcm_val + real, allocatable :: first_wave(:),second_wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: first_input,second_input + + first_input=msg_a + call genjtty(first_input,first_tones,first_symbols) + first_samples=first_symbols*nsps + first_start=max(1,nint(dt_a*12000.0)+1) + + second_input=msg_b + call genjtty(second_input,second_tones,second_symbols) + second_samples=second_symbols*nsps + second_start=max(1,nint(dt_b*12000.0)+1) + + total_samples=max(first_start+first_samples-1, & + second_start+second_samples-1)+frame_symbols*nsps + allocate(pcm(total_samples)) + pcm=0_int16 + + allocate(first_wave(first_samples),complex_wave(first_samples)) + call gen_jttywave(first_tones,first_symbols,nsps,2.0,12000.0,1500.0, & + complex_wave,first_wave,0,first_samples) + do i=1,first_samples + idx=first_start+i-1 + pcm_val=nint(14000.0*first_wave(i)) + pcm(idx)=int(max(-32767,min(32767,pcm_val)),int16) + enddo + deallocate(first_wave,complex_wave) + + allocate(second_wave(second_samples),complex_wave(second_samples)) + call gen_jttywave(second_tones,second_symbols,nsps,2.0,12000.0,1504.0, & + complex_wave,second_wave,0,second_samples) + do i=1,second_samples + idx=second_start+i-1 + pcm_val=nint(14000.0*second_wave(i)) + pcm(idx)=int(max(-32767,min(32767,pcm_val)),int16) + enddo + deallocate(second_wave,complex_wave) + end subroutine build_pair + + logical function found(message) + character(len=*), intent(in) :: message + integer :: i + found=.false. + do i=1,npending + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(message)) found=.true. + enddo + end function found + + function decoded_text(message) result(text) + character(len=*), intent(in) :: message + character(len=80) :: text + integer :: i + text='' + do i=1,npending + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(message)) & + text=normalized(pending_updates(i)%decoded) + enddo + end function decoded_text + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_windowed_decode diff --git a/tests/unit/jtty/test_mmttyif.cpp b/tests/unit/jtty/test_mmttyif.cpp new file mode 100644 index 00000000..8333d6c9 --- /dev/null +++ b/tests/unit/jtty/test_mmttyif.cpp @@ -0,0 +1,265 @@ +#include <QtTest> + +#include <memory> + +#include <QCoreApplication> +#include <QHostAddress> +#include <QSignalSpy> +#include <QTcpServer> +#include <QTcpSocket> + +#include "widgets/MMTTYIF.hpp" + +namespace +{ + int constexpr maximumHeaderBytes {64}; + int constexpr maximumPayloadBytes {64 * 1024}; +} + +class TestMMTTYIF final + : public QObject +{ + Q_OBJECT + +private slots: + void init () + { + server_.reset (new QTcpServer); + // MMTTYIF connects to 127.0.0.1 (IPv4). Bind the same family so Windows + // does not leave the server on ::1 while the client dials IPv4. + QVERIFY (server_->listen (QHostAddress {QStringLiteral ("127.0.0.1")}, 0)); + QCoreApplication::processEvents (); + + interface_.reset (new MMTTYIF); + interface_->initialize (server_->serverPort ()); + + QTRY_VERIFY_WITH_TIMEOUT (server_->hasPendingConnections (), 5000); + peer_ = server_->nextPendingConnection (); + QVERIFY (peer_); + QTRY_VERIFY_WITH_TIMEOUT (interface_->isConnected (), 5000); + } + + void cleanup () + { + interface_.reset (); + peer_ = nullptr; + server_.reset (); + QCoreApplication::processEvents (); + } + + void parsesFragmentedFrame () + { + QSignalSpy text {interface_.get (), &MMTTYIF::app_tx_string}; + + QVERIFY (writeToInterface ("<TXTEXT:11>HELLO")); + QTest::qWait (20); + QCOMPARE (text.count (), 0); + + QVERIFY (writeToInterface (" WORLD")); + QTRY_COMPARE_WITH_TIMEOUT (text.count (), 1, 1000); + QCOMPARE (text.at (0).at (0).toString (), QString {"HELLO WORLD"}); + } + + void dispatchesFragmentedTaggedTextBeforeStart () + { + QStringList events; + connect (interface_.get (), &MMTTYIF::app_tx_string, this, + [&events] (QString const& message) { events.append ("text:" + message); }); + connect (interface_.get (), &MMTTYIF::app_start_tx, this, + [&events] { events.append (QStringLiteral ("start")); }); + + QByteArray const payload {"[[JTTY:CALL_EXCH]] W9XYZ 7"}; + QByteArray frame {"<TXTEXT:"}; + frame += QByteArray::number (payload.size ()); + frame += '>'; + frame += payload; + int const split = frame.size () - 5; + + QVERIFY (writeToInterface (frame.left (split))); + QTest::qWait (20); + QVERIFY (events.isEmpty ()); + + QVERIFY (writeToInterface (frame.mid (split) + "<XMIT:2>ON")); + QTRY_COMPARE_WITH_TIMEOUT (events.size (), 2, 1000); + QCOMPARE (events.at (0), QStringLiteral ("text:[[JTTY:CALL_EXCH]] W9XYZ 7")); + QCOMPARE (events.at (1), QStringLiteral ("start")); + } + + void parsesCoalescedFrames () + { + QSignalSpy text {interface_.get (), &MMTTYIF::app_tx_string}; + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + + QVERIFY (writeToInterface ("<TXTEXT:5>A<B>C<XMIT:2>ON")); + + QTRY_COMPARE_WITH_TIMEOUT (text.count (), 1, 1000); + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QCOMPARE (text.at (0).at (0).toString (), QString {"A<B>C"}); + } + + void dispatchesControlCommands () + { + QSignalSpy stop {interface_.get (), &MMTTYIF::app_stop_tx}; + QSignalSpy abort {interface_.get (), &MMTTYIF::app_abort_tx}; + QSignalSpy close {interface_.get (), &MMTTYIF::app_is_quitting}; + + QVERIFY (writeToInterface ("<XMIT:3>OFF<ABORT>ABORT<CLOSE>CLOSE")); + + QTRY_COMPARE_WITH_TIMEOUT (stop.count (), 1, 1000); + QTRY_COMPARE_WITH_TIMEOUT (abort.count (), 1, 1000); + QTRY_COMPARE_WITH_TIMEOUT (close.count (), 1, 1000); + } + + void delaysOutputCompleteUntilDrainReport () + { + QSignalSpy stop {interface_.get (), &MMTTYIF::app_stop_tx}; + peer_->readAll (); + + QVERIFY (writeToInterface ("<XMIT:3>OFF")); + QTRY_COMPARE_WITH_TIMEOUT (stop.count (), 1, 1000); + QTest::qWait (20); + QCOMPARE (peer_->bytesAvailable (), qint64 {0}); + + interface_->report_output_complete (); + QTRY_VERIFY_WITH_TIMEOUT (peer_->bytesAvailable () > 0, 1000); + QCOMPARE (peer_->readAll (), QByteArray {"<OUTPUTCOMPLETE>"}); + } + + void parsesFragmentedImplicitControl () + { + QSignalSpy abort {interface_.get (), &MMTTYIF::app_abort_tx}; + QSignalSpy received {interface_.get (), &MMTTYIF::message_received}; + + QVERIFY (writeToInterface ("<ABORT>AB")); + QTRY_VERIFY_WITH_TIMEOUT (received.count () >= 1, 1000); + QCOMPARE (abort.count (), 0); + + QVERIFY (writeToInterface ("ORT")); + QTRY_COMPARE_WITH_TIMEOUT (abort.count (), 1, 1000); + } + + void recoversAfterInvalidLength () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QVERIFY (writeToInterface ("<TXTEXT:-1><TXTEXT:nope><XMIT:2>ON")); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QTRY_VERIFY_WITH_TIMEOUT (logs.count () >= 2, 1000); + } + + void acceptsMaximumDeclaredPayload () + { + QSignalSpy text {interface_.get (), &MMTTYIF::app_tx_string}; + QByteArray const payload (maximumPayloadBytes, 'a'); + QByteArray frame {"<TXTEXT:"}; + frame += QByteArray::number (payload.size ()); + frame += '>'; + frame += payload; + + QVERIFY (writeToInterface (frame)); + + QTRY_COMPARE_WITH_TIMEOUT (text.count (), 1, 2000); + QCOMPARE (text.at (0).at (0).toString (), QString (maximumPayloadBytes, 'A')); + } + + void rejectsOversizedDeclaredPayload () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QByteArray frame {"<TXTEXT:"}; + frame += QByteArray::number (maximumPayloadBytes + 1); + frame += "><XMIT:2>ON"; + QVERIFY (writeToInterface (frame)); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "payload length exceeds"), 1000); + } + + void rejectsSignedMaximumLength () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QVERIFY (writeToInterface ("<TXTEXT:2147483647><XMIT:2>ON")); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "payload length exceeds"), 1000); + } + + void rejectsOversizedUndeclaredPayload () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy abort {interface_.get (), &MMTTYIF::app_abort_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + QSignalSpy received {interface_.get (), &MMTTYIF::message_received}; + + QByteArray firstFragment {"<ABORT>"}; + firstFragment += QByteArray (maximumPayloadBytes / 2, 'A'); + QVERIFY (writeToInterface (firstFragment)); + QTRY_VERIFY_WITH_TIMEOUT (received.count () >= 1, 1000); + QCOMPARE (abort.count (), 0); + + QByteArray secondFragment (maximumPayloadBytes / 2 + 1, 'A'); + secondFragment += "<XMIT:2>ON"; + QVERIFY (writeToInterface (secondFragment)); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 2000); + QCOMPARE (abort.count (), 0); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "payload exceeds"), 1000); + } + + void rejectsOverlongIncompleteHeader () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QByteArray header {"<"}; + header += QByteArray (maximumHeaderBytes, 'A'); + QVERIFY (writeToInterface (header)); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "header exceeds"), 1000); + + QVERIFY (writeToInterface ("<XMIT:2>ON")); + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + } + + void rejectsOverlongTerminatedHeader () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QByteArray header {"<"}; + header += QByteArray (maximumHeaderBytes - 1, 'A'); + header += '>'; + QVERIFY (writeToInterface (header)); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "header exceeds"), 1000); + + QVERIFY (writeToInterface ("<XMIT:2>ON")); + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + } + +private: + static bool hasLogContaining (QSignalSpy const& logs, QString const& text) + { + for (auto const& arguments : logs) { + if (arguments.at (0).toString ().contains (text)) return true; + } + return false; + } + + bool writeToInterface (QByteArray const& data) + { + if (!peer_ || peer_->write (data) != data.size ()) return false; + return !peer_->bytesToWrite () || peer_->waitForBytesWritten (1000); + } + + std::unique_ptr<QTcpServer> server_; + std::unique_ptr<MMTTYIF> interface_; + QTcpSocket * peer_ {nullptr}; +}; + +QTEST_GUILESS_MAIN (TestMMTTYIF) + +#include "test_mmttyif.moc" diff --git a/tests/unit/jtty/test_tbcc.f90 b/tests/unit/jtty/test_tbcc.f90 new file mode 100644 index 00000000..97fe50d1 --- /dev/null +++ b/tests/unit/jtty/test_tbcc.f90 @@ -0,0 +1,141 @@ +program test_tbcc + + ! Transition invariants across supported memories and JTTY candidate acceptance. + + use, intrinsic :: iso_fortran_env, only: real32, int32 + use tbcc + implicit none + + call expect_incoming_tones() + call expect_empty_and_tied_candidates() + call expect_encode_decode_roundtrip() + call expect_reserved_zero_bit_filters_candidates() + + print *, 'test_tbcc: all checks passed' + +contains + + subroutine expect_incoming_tones() + integer, parameter :: memories(5) = [9, 12, 10, 11, 9] + integer, parameter :: gray_tones(0:3) = [0, 1, 3, 2] + integer :: n, predecessor, bit, destination, register_value, expected + + do n = 1, size(memories) + call tbcc_init(memories(n)) + if (size(incoming_tones, 2) /= num_states) error stop 'incorrect transition table size' + do predecessor = 0, num_states-1 + do bit = 0, 1 + register_value = 2*predecessor + bit + destination = mod(register_value, num_states) + expected = gray_tones(2*mod(popcnt(iand(register_value, g0_poly)), 2) + & + mod(popcnt(iand(register_value, g1_poly)), 2)) + if (incoming_tones(predecessor/(num_states/2), destination) /= expected) & + error stop 'incoming tone differs from encoder polynomial parity' + end do + end do + end do + end subroutine expect_incoming_tones + + subroutine expect_empty_and_tied_candidates() + integer :: decoded(PAYLOAD_BITS) + real(real32) :: energies(0:3, TOTAL_K) + logical :: success + + call tbcc_init(9) + energies = 1.0_real32 + call tbcc_wava_fsk_decode(energies, 0, 2, decoded, success) + if (success .or. any(decoded /= 0)) error stop 'empty candidate list must fail cleanly' + + ! Equal branch metrics select the all-one circular path, which fails CRC. + call tbcc_wava_fsk_decode(energies, 4, 2, decoded, success) + if (success .or. any(decoded /= 0)) error stop 'tied candidate CRC rejection changed' + end subroutine expect_empty_and_tied_candidates + + subroutine expect_encode_decode_roundtrip() + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS) + integer(int32) :: tone_symbols(TOTAL_K) + real(real32) :: tone_energies(0:3, TOTAL_K) + logical :: success + integer :: i, t + + call tbcc_init(9) + + do i = 1, PAYLOAD_BITS + payload(i) = mod(i, 2) ! deterministic, not all-zero + end do + + call tbcc_encode(payload, tone_symbols) + + ! Noiseless channel: all of a symbol's energy on the transmitted tone. + tone_energies = 0.0_real32 + do t = 1, TOTAL_K + tone_energies(tone_symbols(t), t) = 1.0_real32 + end do + + call tbcc_wava_fsk_decode(tone_energies, 4, 2, decoded, success) + if (.not. success) then + print *, 'test_tbcc: noiseless decode failed' + error stop 1 + end if + if (any(decoded /= payload)) then + print *, 'test_tbcc: noiseless decode mismatch' + error stop 1 + end if + end subroutine expect_encode_decode_roundtrip + + subroutine expect_reserved_zero_bit_filters_candidates() + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS) + integer(int32) :: tone_symbols(TOTAL_K) + real(real32) :: tone_energies(0:3, TOTAL_K) + logical :: success + integer :: i, t, one_bit_pos + + call tbcc_init(9) + + do i = 1, PAYLOAD_BITS + payload(i) = mod(i, 2) + end do + ! A payload-bit position this payload sets to 1, so requiring it to be + ! 0 must reject this exact (otherwise noiseless-decodable) codeword. + one_bit_pos = 0 + do i = 1, PAYLOAD_BITS + if (payload(i) == 1) then + one_bit_pos = i + exit + end if + end do + if (one_bit_pos == 0) then + print *, 'test_tbcc: test payload unexpectedly all-zero' + error stop 1 + end if + + call tbcc_encode(payload, tone_symbols) + tone_energies = 0.0_real32 + do t = 1, TOTAL_K + tone_energies(tone_symbols(t), t) = 1.0_real32 + end do + + ! Control case: no reserved_zero_bit, decode succeeds as above. + call tbcc_wava_fsk_decode(tone_energies, 4, 2, decoded, success) + if (.not. success) then + print *, 'test_tbcc: control decode (no reserved_zero_bit) failed' + error stop 1 + end if + + ! With the filter on a bit this payload actually sets to 1, the only + ! codeword consistent with these noiseless tone energies fails the + ! filter, so decoding must now report failure. + decoded = huge(0_int32) + call tbcc_wava_fsk_decode(tone_energies, 4, 2, decoded, success, & + reserved_zero_bit=one_bit_pos) + if (success) then + print *, 'test_tbcc: reserved_zero_bit did not filter the candidate' + error stop 1 + end if + if (any(decoded /= 0_int32)) then + print *, 'test_tbcc: failed decode did not clear its payload' + error stop 1 + end if + end subroutine expect_reserved_zero_bit_filters_candidates + +end program test_tbcc |
