diff options
| author | Christoph Berg <myon@debian.org> | 2026-10-09 14:12:35 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2026-10-09 14:12:35 +0200 |
| commit | ffc62c792c9a5196cb4ce7a353287dfe20db6524 (patch) | |
| tree | 1269efa852935b183daae4bb33a58d1b4d2ffb53 /tests/unit/jtty | |
| parent | 059831534c7e884f0a607ed86b582fd00d821731 (diff) | |
New upstream version 3.3.0~beta1+dfsgupstream/3.3.0_beta1+dfsg
Diffstat (limited to 'tests/unit/jtty')
23 files changed, 3154 insertions, 289 deletions
diff --git a/tests/unit/jtty/CMakeLists.txt b/tests/unit/jtty/CMakeLists.txt index 8dd698d0..2ba22568 100644 --- a/tests/unit/jtty/CMakeLists.txt +++ b/tests/unit/jtty/CMakeLists.txt @@ -151,9 +151,64 @@ add_executable (test_jtty_messages test_jtty_messages.cpp) target_link_libraries (test_jtty_messages Qt5::Test) add_test (NAME test_jtty_messages COMMAND test_jtty_messages) -add_executable (test_jtty_draft_acceptance test_jtty_draft_acceptance.cpp) -target_link_libraries (test_jtty_draft_acceptance Qt5::Test) -add_test (NAME test_jtty_draft_acceptance COMMAND test_jtty_draft_acceptance) +add_executable (test_jtty_continuous_decode test_jtty_continuous_decode.f90) +target_include_directories (test_jtty_continuous_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_continuous_decode) +add_test (NAME test_jtty_continuous_decode COMMAND test_jtty_continuous_decode) +set_tests_properties (test_jtty_continuous_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_continuous_decode: all checks passed" + TIMEOUT 300 +) + +add_executable (test_jtty_spectrum + test_jtty_spectrum.cpp + ${CMAKE_SOURCE_DIR}/widgets/JttySpectrum.cpp) +target_link_libraries (test_jtty_spectrum PRIVATE Qt5::Test) +wsjt_link_common_fortran (test_jtty_spectrum) +add_test (NAME test_jtty_spectrum COMMAND test_jtty_spectrum) + +add_executable (test_jtty_waterfall + test_jtty_waterfall.cpp + ${CMAKE_SOURCE_DIR}/widgets/plotter.cpp) +target_link_libraries (test_jtty_waterfall PRIVATE wsjt_qt Qt5::Test) +wsjt_link_common_fortran (test_jtty_waterfall) +add_test (NAME test_jtty_waterfall COMMAND test_jtty_waterfall) +set_tests_properties (test_jtty_waterfall PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_executable (test_jtty_recording + test_jtty_recording.cpp + ${CMAKE_SOURCE_DIR}/JttyRecording.cpp) +target_link_libraries (test_jtty_recording wsjt_qt wsjt_qtmm Qt5::Test Qt5::Multimedia) +add_test (NAME test_jtty_recording COMMAND test_jtty_recording) + +add_executable (test_jtty_receive_history test_jtty_receive_history.cpp) +target_link_libraries (test_jtty_receive_history Qt5::Test) +add_test (NAME test_jtty_receive_history COMMAND test_jtty_receive_history) + +add_executable (test_jtty_receive_line test_jtty_receive_line.cpp) +target_link_libraries (test_jtty_receive_line Qt5::Test Qt5::Gui) +add_test (NAME test_jtty_receive_line COMMAND test_jtty_receive_line) +set_tests_properties (test_jtty_receive_line PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_executable (test_jtty_receive_results + test_jtty_receive_results.cpp + ${CMAKE_SOURCE_DIR}/JttyReceiveResultController.cpp + ${CMAKE_SOURCE_DIR}/Radio.cpp) +target_link_libraries (test_jtty_receive_results Qt5::Test Qt5::Gui) +add_test (NAME test_jtty_receive_results COMMAND test_jtty_receive_results) +set_tests_properties (test_jtty_receive_results PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_executable (test_jtty_tx_lifecycle test_jtty_tx_lifecycle.cpp) +target_link_libraries (test_jtty_tx_lifecycle Qt5::Test) +add_test (NAME test_jtty_tx_lifecycle COMMAND test_jtty_tx_lifecycle) + +add_executable (test_jtty_transmit_queue test_jtty_transmit_queue.cpp) +target_link_libraries (test_jtty_transmit_queue Qt5::Test) +add_test (NAME test_jtty_transmit_queue COMMAND test_jtty_transmit_queue) + +add_executable (test_jtty_live_entry test_jtty_live_entry.cpp) +target_link_libraries (test_jtty_live_entry Qt5::Test) +add_test (NAME test_jtty_live_entry COMMAND test_jtty_live_entry) add_executable (test_jtty_n1mm test_jtty_n1mm.cpp) target_link_libraries (test_jtty_n1mm Qt5::Test) diff --git a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp index 1d666113..c2b3b45b 100644 --- a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp +++ b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp @@ -6,7 +6,7 @@ extern "C" void genjtty_atoms_c (Jtty::NativeAtomDescriptor const atoms[], int natoms, int tones[], int* nsym, int* status); -extern "C" void genjtty_profile_ (char*, int const*, int*, int*, fortran_charlen_t); +extern "C" void genjtty_profile_ (char*, int const*, int*, int*, int*, int const*, fortran_charlen_t); extern "C" int jtty_cpp_n1mm_smoke (int tones[], int* nsym) { @@ -22,7 +22,7 @@ extern "C" int jtty_cpp_n1mm_smoke (int tones[], int* nsym) return status; } -extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[], int chained) +extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[]) { Jtty::NativeMacroContext const context {QStringLiteral ("K1ABC"), {}, 0}; auto const compiled = Jtty::compileNativeMacro ( @@ -30,7 +30,7 @@ extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[], int chain *nsym = 0; int status = static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); if (compiled.isNative ()) { - auto const frame = Jtty::transmitFrame (compiled.text, chained != 0).toLatin1 (); + auto const frame = Jtty::transmitFrame (compiled.text).toLatin1 (); std::copy (frame.cbegin (), frame.cend (), text); genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), tones, nsym, &status); @@ -59,18 +59,22 @@ extern "C" int jtty_cpp_rtty_smoke (int tones[], int* nsym) } genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), tones, nsym, &status); if (status != static_cast<int> (Jtty::NativeEncodeStatus::Ok) || *nsym <= 0) return status; - auto text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + auto text = Jtty::transmitFrame (example.raw).toLatin1 (); int packedSymbols {}; + std::array<int, 16> frameStarts {}; + int const isFinal = 1; auto profile = static_cast<int> (context.exchangeProfile); - genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, text.size ()); + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, + frameStarts.data (), &isFinal, text.size ()); if (packedSymbols != *nsym || !std::equal (tones, tones + *nsym, packedTones.cbegin ()) || - text != Jtty::transmitFrame (example.canonical, false).toLatin1 ()) { + text != Jtty::transmitFrame (example.canonical).toLatin1 ()) { return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); } - text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + text = Jtty::transmitFrame (example.raw).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 ()) { + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, + frameStarts.data (), &isFinal, text.size ()); + if (packedSymbols != 2 * *nsym || text != Jtty::transmitFrame (example.raw).toLatin1 ()) { return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); } } diff --git a/tests/unit/jtty/test_jtty_continuous_decode.f90 b/tests/unit/jtty/test_jtty_continuous_decode.f90 new file mode 100644 index 00000000..38de8224 --- /dev/null +++ b/tests/unit/jtty/test_jtty_continuous_decode.f90 @@ -0,0 +1,316 @@ +program test_jtty_continuous_decode + use iso_c_binding, only: c_int, c_int16_t, c_int64_t, c_float, c_double, c_char + use jtty_receive_context + use jtty_mdec, only: UPDATE_GROWING, UPDATE_COMPLETE, UPDATE_EXPIRED, UPDATE_RECEPTION_ENDED + use jtty_fec, only: is13, TOTAL_K + use jtty_mod, only: MAX_FRAMES + implicit none + + integer, parameter :: nsps=384, rate=12000, step=59*nsps/4, block=3456 + integer, parameter :: max_events=256 + integer, parameter :: review_interval=16*rate + integer(c_int64_t), parameter :: high_origin=2_c_int64_t**40 + character(len=*), parameter :: wanted='WB9XYZ 599 0123' + character(len=*), parameter :: overlap_strong='MAYBE YOU SHOULD HELP' + character(len=*), parameter :: overlap_weak='CLAUDE CO 3 MIN TRANSITION' + type :: update_event + integer(c_int64_t) :: id=0 + character(len=80) :: text='' + real(c_double) :: start=0,latest=0 + real(c_float) :: frequency=0 + integer(c_int) :: terminal=0 + end type update_event + type(update_event) :: reference(max_events),rotated(max_events),interleaved(max_events) + integer(c_int16_t), allocatable :: pcm(:),partial(:) + integer :: nreference,nrotated,ninterleaved + + allocate(pcm(200*rate)) + pcm=0 + call add_message(pcm,2401,.false.) + call add_message(pcm,374*step+1,.true.) + + call run_stream(pcm,0_c_int64_t,0,.false.,reference,nreference) + call run_stream(pcm,0_c_int64_t,180*rate,.false.,rotated,nrotated) + call compare_events(reference,nreference,rotated,nrotated,0.0_c_double) + call run_stream(pcm,high_origin,7*rate,.true.,interleaved,ninterleaved) + call compare_events(reference,nreference,interleaved,ninterleaved,real(high_origin,c_double)/rate) + call expect(count_complete(reference,nreference).eq.2, & + 'strong and damaged-sync messages complete inside and across the 180-second boundary') + call expect(count_growth(reference,nreference).ge.2,'multi-frame messages publish growing updates') + + allocate(partial(15*rate)) + partial=0 + partial(1:3*rate)=pcm(1:3*rate) + call check_terminal(partial,3*rate,UPDATE_RECEPTION_ENDED) + call check_terminal(partial,size(partial),UPDATE_EXPIRED) + + pcm=0 + call mix_message(pcm,2401,overlap_strong,1500.0,14000.0) + call mix_message(pcm,7201,overlap_weak,1504.0,12000.0) + call mix_message(pcm,374*step+2401,overlap_strong,1500.0,14000.0) + call mix_message(pcm,374*step+7201,overlap_weak,1504.0,12000.0) + call run_stream(pcm,0_c_int64_t,0,.false.,reference,nreference,2800) + call expect_overlap(reference,nreference) + call run_stream(pcm,0_c_int64_t,180*rate,.false.,rotated,nrotated,2800) + call compare_events(reference,nreference,rotated,nrotated,0.0_c_double) + call run_stream(pcm,high_origin,7*rate,.true.,interleaved,ninterleaved,2800) + call compare_events(reference,nreference,interleaved,ninterleaved,real(high_origin,c_double)/rate) + + print *, 'test_jtty_continuous_decode: all checks passed' + +contains + + subroutine add_message(samples,start,damaged_sync) + integer(c_int16_t), intent(inout) :: samples(:) + integer, intent(in) :: start + logical, intent(in) :: damaged_sync + integer :: tones(MAX_FRAMES*(size(is13)+TOTAL_K)),qrm_tones(size(is13)+TOTAL_K) + integer :: symbols,n,qrm_symbols,i,offset,span,value + real, allocatable :: wave(:),qrm(:),combined(:) + complex, allocatable :: analytic(:) + character(len=80) :: message + + message=wanted + call genjtty(message,tones,symbols) + call expect(symbols.eq.3*59,'fixture retains its three-frame encoding') + if(damaged_sync) tones(60:60+size(is13)-1)=mod(is13+2,4) + n=symbols*nsps + allocate(wave(n),analytic(n+59*nsps),combined(n+59*nsps)) + call gen_jttywave(tones,symbols,nsps,2.0,12000.0,1500.0,analytic,wave,0,n) + combined=0 + combined(1:n)=wave + if(damaged_sync) then + message='N2PPI' + call genjtty(message,qrm_tones,qrm_symbols) + allocate(qrm(qrm_symbols*nsps)) + call gen_jttywave(qrm_tones,qrm_symbols,nsps,2.0,12000.0,1540.0,analytic,qrm,0,size(qrm)) + offset=1 + do while(offset.le.size(combined)) + span=min(size(qrm),size(combined)-offset+1) + combined(offset:offset+span-1)=combined(offset:offset+span-1)+0.3*qrm(1:span) + offset=offset+span + enddo + endif + do i=1,size(combined) + value=nint(30000.0*combined(i)) + samples(start+i-1)=int(max(-32767,min(32767,value)),c_int16_t) + enddo + end subroutine add_message + + subroutine mix_message(samples,start,text,frequency,amplitude) + integer(c_int16_t), intent(inout) :: samples(:) + integer, intent(in) :: start + character(len=*), intent(in) :: text + real, intent(in) :: frequency,amplitude + integer :: tones(MAX_FRAMES*(size(is13)+TOTAL_K)),symbols,n,i,mixed + real, allocatable :: wave(:) + complex, allocatable :: analytic(:) + character(len=80) :: message + + message=text + call genjtty(message,tones,symbols) + n=symbols*nsps + allocate(wave(n),analytic(n)) + call gen_jttywave(tones,symbols,nsps,2.0,12000.0,frequency,analytic,wave,0,n) + call expect(start+n-1+59*nsps.le.size(samples), & + 'the overlapping transmission and final search/retro padding fit the fixture') + do i=1,n + mixed=int(samples(start+i-1))+nint(amplitude*wave(i)) + samples(start+i-1)=int(max(-32767,min(32767,mixed)),c_int16_t) + enddo + end subroutine mix_message + + subroutine run_stream(samples,origin,storage_size,review,events,event_count,high_frequency) + integer(c_int16_t), intent(in) :: samples(:) + integer(c_int64_t), intent(in) :: origin + integer, intent(in) :: storage_size + logical, intent(in) :: review + type(update_event), intent(out) :: events(:) + integer, intent(out) :: event_count + integer, optional, intent(in) :: high_frequency + integer(c_int) :: live,manual,processed,ignored + integer :: available,first,rotations,discard_count,nfb,review_restarts + integer :: next_review_sample,last_review_restart + integer(c_int64_t) :: required + type(update_event) :: discarded(max_events) + + event_count=0 + nfb=1499 + if(present(high_frequency)) nfb=high_frequency + rotations=0 + review_restarts=0 + next_review_sample=0 + last_review_restart=0 + first=1 + live=jtty_rx_create() + call expect(live.ne.0,'live decoder context is available') + call jtty_rx_begin(live,1_c_int64_t,origin,origin,nsps) + manual=0 + if(review) then + manual=jtty_rx_create() + call expect(manual.ne.0,'review has independent decoder state') + call jtty_rx_begin(manual,2_c_int64_t,0_c_int64_t,0_c_int64_t,nsps) + endif + available=0 + do while(available.lt.size(samples)) + available=min(available+block,size(samples)) + do + processed=jtty_rx_process(live,samples(first:),available-first+1, & + origin+int(first-1,c_int64_t),origin+int(available,c_int64_t),1,200,nfb,1500.0,50.0) + call expect(processed.ge.0,'retained audio covers the forward and retro search windows') + call collect(live,events,event_count) + if(processed.eq.0) exit + if(review .and. available.ge.next_review_sample) then + ignored=jtty_rx_process(manual,samples,9*rate,0_c_int64_t,int(9*rate,c_int64_t), & + 1,200,nfb,1500.0,50.0) + call expect(ignored.ge.0,'review decoding remains independently valid') + discard_count=0 + call collect(manual,discarded,discard_count) + if(ignored.eq.0) then + call jtty_rx_end(manual,UPDATE_RECEPTION_ENDED) + discard_count=0 + call collect(manual,discarded,discard_count) + call jtty_rx_begin(manual,2_c_int64_t,0_c_int64_t,0_c_int64_t,nsps) + review_restarts=review_restarts+1 + last_review_restart=available + next_review_sample=next_review_sample+review_interval + endif + endif + enddo + if(storage_size.gt.0 .and. available-first+1.ge.storage_size) then + required=jtty_rx_next_required_sample(live)-origin + if(required.gt.int(first-1,c_int64_t)) then + first=int(required)+1 + rotations=rotations+1 + endif + endif + enddo + if(storage_size.gt.0) call expect(rotations.gt.0,'the fixture actually rotates storage') + if(storage_size.eq.7*rate) call expect(rotations.gt.20,'short storage repeats many rotations') + if(review) call expect(review_restarts.gt.10,'review decoding remains active through later storage boundaries') + if(review) call expect(last_review_restart.ge.180*rate,'review decoding continues past the 180-second boundary') + call jtty_rx_end(live,UPDATE_RECEPTION_ENDED) + call collect(live,events,event_count) + call jtty_rx_destroy(live) + if(manual.ne.0) call jtty_rx_destroy(manual) + end subroutine run_stream + + subroutine collect(handle,events,event_count) + integer(c_int), intent(in) :: handle + type(update_event), intent(inout) :: events(:) + integer, intent(inout) :: event_count + character(kind=c_char) :: text(80*30) + integer(c_int64_t) :: ids(30) + real(c_float) :: frequencies(30) + real(c_double) :: starts(30),latest(30) + integer(c_int) :: terminals(30),snrs(30),n + integer :: i,j + + do + n=jtty_rx_take_updates(handle,30,text,ids,frequencies,starts,latest,terminals,snrs) + do i=1,n + call expect(event_count.lt.size(events),'update collection remains bounded') + event_count=event_count+1 + do j=1,80 + events(event_count)%text(j:j)=text((i-1)*80+j) + enddo + events(event_count)%id=ids(i) + events(event_count)%frequency=frequencies(i) + events(event_count)%start=starts(i) + events(event_count)%latest=latest(i) + events(event_count)%terminal=terminals(i) + enddo + if(n.lt.30) exit + enddo + end subroutine collect + + subroutine compare_events(expected,nexpected,actual,nactual,time_offset) + type(update_event), intent(in) :: expected(:),actual(:) + integer, intent(in) :: nexpected,nactual + real(c_double), intent(in) :: time_offset + integer :: i,j + + call expect(nexpected.eq.nactual,'storage and context changes preserve every message update') + do i=1,nexpected + call expect(expected(i)%text.eq.actual(i)%text,'storage and context changes preserve exact text') + call expect(expected(i)%terminal.eq.actual(i)%terminal,'terminal reasons remain unchanged') + call expect(abs(expected(i)%frequency-actual(i)%frequency).lt.0.001,'frequency estimates remain unchanged') + call expect(abs(expected(i)%start-(actual(i)%start-time_offset)).lt.0.000001_c_double, & + 'message start timestamps remain stable at large sample origins') + call expect(abs(expected(i)%latest-(actual(i)%latest-time_offset)).lt.0.000001_c_double, & + 'latest-frame timestamps remain stable at large sample origins') + do j=1,i + call expect((expected(i)%id.eq.expected(j)%id).eqv.(actual(i)%id.eq.actual(j)%id), & + 'growing updates preserve logical identity without merging separate messages') + enddo + enddo + end subroutine compare_events + + subroutine expect_overlap(events,n) + type(update_event), intent(in) :: events(:) + integer, intent(in) :: n + integer :: i + logical :: complete + + complete=count_complete(events,n,overlap_strong).eq.2 .and. count_complete(events,n,overlap_weak).eq.2 + if(.not.complete) then + do i=1,n + write(*,'(i0,1x,f8.3,1x,f8.3,1x,a)') events(i)%terminal,events(i)%start,events(i)%frequency,trim(events(i)%text) + enddo + endif + call expect(complete,'both stronger and weaker overlapping messages complete inside and across the boundary') + end subroutine expect_overlap + + integer function count_complete(events,n,message) + type(update_event), intent(in) :: events(:) + integer, intent(in) :: n + character(len=*), optional, intent(in) :: message + integer :: i + character(len=80) :: expected + + count_complete=0 + expected=wanted + if(present(message)) expected=message + do i=1,n + if(trim(events(i)%text).eq.trim(expected) .and. events(i)%terminal.eq.UPDATE_COMPLETE) & + count_complete=count_complete+1 + enddo + end function count_complete + + integer function count_growth(events,n) + type(update_event), intent(in) :: events(:) + integer, intent(in) :: n + + count_growth=count(events(1:n)%terminal.eq.UPDATE_GROWING) + end function count_growth + + subroutine check_terminal(samples,stop,reason) + integer(c_int16_t), intent(in) :: samples(:) + integer, intent(in) :: stop,reason + integer(c_int) :: handle,processed + type(update_event) :: events(max_events) + integer :: n + + handle=jtty_rx_create() + call jtty_rx_begin(handle,3_c_int64_t,0_c_int64_t,0_c_int64_t,nsps) + processed=jtty_rx_process(handle,samples,stop,0_c_int64_t,int(stop,c_int64_t),1000,200,1499,1500.0,50.0) + call expect(processed.gt.0,'partial-message fixture is decoded') + if(reason.eq.UPDATE_RECEPTION_ENDED) call jtty_rx_end(handle,reason) + n=0 + call collect(handle,events,n) + call expect(n.gt.0,'partial messages remain deliverable') + call expect(any(events(1:n)%terminal.eq.reason),'partial message reports its actual terminal reason') + call expect(.not.any(events(1:n)%terminal.eq.UPDATE_COMPLETE),'interruption is not a completed transmission') + call jtty_rx_destroy(handle) + end subroutine check_terminal + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(condition) return + write(*,'(a)') message + error stop 1 + end subroutine expect + +end program test_jtty_continuous_decode diff --git a/tests/unit/jtty/test_jtty_draft_acceptance.cpp b/tests/unit/jtty/test_jtty_draft_acceptance.cpp deleted file mode 100644 index f321aaf5..00000000 --- a/tests/unit/jtty/test_jtty_draft_acceptance.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include <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_get_updates.f90 b/tests/unit/jtty/test_jtty_get_updates.f90 index 0ecf61dc..7baaae6c 100644 --- a/tests/unit/jtty/test_jtty_get_updates.f90 +++ b/tests/unit/jtty/test_jtty_get_updates.f90 @@ -9,19 +9,20 @@ program test_jtty_get_updates integer(int64) :: message_ids(BATCH_SIZE) real :: frequencies(BATCH_SIZE),start_tsync(BATCH_SIZE) logical*1 :: eom(BATCH_SIZE) + integer :: snr(BATCH_SIZE) type(message_assembly) :: message integer :: i,count call discard_pending_updates() - message=make_message(41_int64,1500.4,1.25,'CQ K1ABC') + message=make_message(41_int64,1500.4,1.25,'CQ K1ABC',snr=-7.3) call queue_message_update(message,.false.) message%decoded='CQ K1ABC FN20' call queue_message_update(message,.true.) call expect(npending.eq.1, & 'updates for one logical message coalesce before delivery') - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.1 .and. npending.eq.0, & 'retrieving an update drains it exactly once') call expect(message_ids(1).eq.41_int64 .and. & @@ -30,13 +31,15 @@ program test_jtty_get_updates call expect(abs(frequencies(1)-1500.4).lt.0.001 .and. & abs(start_tsync(1)-1.25).lt.0.001 .and. eom(1), & 'the batch preserves structured message metadata') - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(snr(1).eq.-7, & + 'the batch reports the rounded start_snrdb carried by message_assembly') + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.0, 'a drained update is not returned again') message=make_message(42_int64,1501.0,2.5,'UNCHANGED TEXT') call queue_message_update(message,.false.) call queue_message_update(message,.true.) - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.1 .and. eom(1) .and. & trim(block_text(text_blocks,1)).eq.'UNCHANGED TEXT', & 'completion metadata coalesces when message text is unchanged') @@ -51,7 +54,7 @@ program test_jtty_get_updates call expect(npending.eq.35, & 'the pending store retains more than one ABI batch') - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.BATCH_SIZE .and. npending.eq.5, & 'the first batch drains the oldest thirty updates') do i=1,BATCH_SIZE @@ -64,7 +67,7 @@ program test_jtty_get_updates 'the first batch preserves completion state') enddo - call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) call expect(count.eq.5 .and. npending.eq.0, & 'a second batch drains every remaining update') do i=1,5 @@ -76,16 +79,18 @@ program test_jtty_get_updates contains - function make_message(id,frequency,tsync,text) result(value) + function make_message(id,frequency,tsync,text,snr) result(value) integer(int64), intent(in) :: id real, intent(in) :: frequency,tsync character(len=*), intent(in) :: text + real, intent(in), optional :: snr type(message_assembly) :: value value%message_id=id value%f1=frequency value%tsync=tsync value%start_tsync=tsync + if(present(snr)) value%start_snrdb=snr value%decoded=text value%k=len_trim(value%decoded) end function make_message diff --git a/tests/unit/jtty/test_jtty_live_entry.cpp b/tests/unit/jtty/test_jtty_live_entry.cpp new file mode 100644 index 00000000..9f9f7d2f --- /dev/null +++ b/tests/unit/jtty/test_jtty_live_entry.cpp @@ -0,0 +1,86 @@ +#include <QtTest> + +#include "widgets/JttyLiveEntry.hpp" + +class TestJttyLiveEntry final + : public QObject +{ + Q_OBJECT + +private slots: + + void emptyTextCommitsNothing () + { + auto const plan = Jtty::planIncrementalCommit (QString {}); + QVERIFY (plan.text.isEmpty ()); + QCOMPARE (plan.length, 0); + } + + void fewerThanHoldbackWordsCommitsNothing () + { + // Exactly maxCompactAtomWords complete words: still all held back. + auto const plan = Jtty::planIncrementalCommit (QStringLiteral ("CQ K1ABC CQ ")); + QVERIFY (plan.text.isEmpty ()); + QCOMPARE (plan.length, 0); + } + + void callSplitAcrossHoldbackNeverCommitsPartway () + { + // The motivating case: TEXT5's fixed 5-char windows would slice "CQ K1ABC" mid-callsign if released early. + for (auto const& text : {QStringLiteral ("CQ "), QStringLiteral ("CQ K1ABC ")}) { + auto const plan = Jtty::planIncrementalCommit (text); + QVERIFY2 (plan.text.isEmpty (), qPrintable (text)); + } + } + + void wordBeyondHoldbackReleasesOnlyTheEarlierWords () + { + // A 4th word pushes the first word out past the 3-word holdback. + auto const plan = Jtty::planIncrementalCommit ( + QStringLiteral ("CQ K1ABC CQ DE ")); + QCOMPARE (plan.text, QStringLiteral ("CQ ")); + QCOMPARE (plan.length, 3); + } + + void releasedPrefixExactlyMatchesOriginalText () + { + QString const text = QStringLiteral ("FIRST SECOND THIRD FOURTH FIFTH "); + auto const plan = Jtty::planIncrementalCommit (text); + QCOMPARE (text.left (plan.length), plan.text); + // 5 complete words, holdback 3: releases the first 2. + QCOMPARE (plan.text, QStringLiteral ("FIRST SECOND ")); + } + + void trailingPartialWordIsNeverReleased () + { + // Same words as the previous case, but the 5th is still mid-typing (no trailing space), so only 4 are complete. + auto const plan = Jtty::planIncrementalCommit ( + QStringLiteral ("FIRST SECOND THIRD FOURTH FIF")); + QCOMPARE (plan.text, QStringLiteral ("FIRST ")); + } + + void forceFlushReleasesEverythingRegardlessOfHoldback () + { + QString const text = QStringLiteral ("CQ K1ABC"); + auto const plan = Jtty::planIncrementalCommit (text, true); + QCOMPARE (plan.text, text); + QCOMPARE (plan.length, text.size ()); + } + + void forceFlushOnEmptyTextCommitsNothing () + { + auto const plan = Jtty::planIncrementalCommit (QString {}, true); + QVERIFY (plan.text.isEmpty ()); + QCOMPARE (plan.length, 0); + } + + void customHoldbackIsHonoured () + { + auto const plan = Jtty::planIncrementalCommit ( + QStringLiteral ("ONE TWO THREE "), false, 1); + QCOMPARE (plan.text, QStringLiteral ("ONE TWO ")); + } +}; + +QTEST_GUILESS_MAIN (TestJttyLiveEntry) +#include "test_jtty_live_entry.moc" diff --git a/tests/unit/jtty/test_jtty_messages.cpp b/tests/unit/jtty/test_jtty_messages.cpp index 7c38dfa4..033966e4 100644 --- a/tests/unit/jtty/test_jtty_messages.cpp +++ b/tests/unit/jtty/test_jtty_messages.cpp @@ -86,10 +86,10 @@ private slots: QCOMPARE (int {movedDefault.atoms.at (0).subtype}, static_cast<int> (Jtty::CallAction::Call)); - auto const unknownPlaceholder = Jtty::compileNativeMacro ( + auto const knownSnrPlaceholder = Jtty::compileNativeMacro ( 8, QString {"599 %R"}, context); - QCOMPARE (unknownPlaceholder.status, Jtty::NativeMacroStatus::LiteralFallback); - QCOMPARE (unknownPlaceholder.text, QString {"599 %R"}); + QCOMPARE (knownSnrPlaceholder.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (knownSnrPlaceholder.text, QString {"599 -10"}); auto const editedLegacyCase = Jtty::compileNativeMacro ( 2, QString {"%h 599 %n"}, context); @@ -480,7 +480,7 @@ private slots: static_cast<int> (Jtty::ExchangeRole::FieldOnly)); } - void configuredSubsquareProducesGrid4WithoutChangingLiteralExpansion () + void configuredSubsquareProducesGrid4InBothNativeAndLiteralExpansion () { Jtty::NativeMacroContext const context { QString {"K1ABC"}, QString {"W9XYZ"}, 1, @@ -492,7 +492,7 @@ private slots: auto const literal = Jtty::compileNativeMacro (QString {"GRID %G"}, context); QCOMPARE (literal.status, Jtty::NativeMacroStatus::LiteralFallback); - QCOMPARE (literal.text, QString {"GRID fn42ab"}); + QCOMPARE (literal.text, QString {"GRID FN42"}); } void invalidGridIsRejected_data () @@ -537,7 +537,7 @@ private slots: Jtty::NativeExchangeProfile::RttyRoundup, QString {" dx "}, QString {"fn42"}}; auto const compiled = Jtty::compileNativeMacro (QString {"TEST %E %G"}, context); QCOMPARE (compiled.status, Jtty::NativeMacroStatus::LiteralFallback); - QCOMPARE (compiled.text, QString {"TEST 007 fn42"}); + QCOMPARE (compiled.text, QString {"TEST 007 FN42"}); QVERIFY (compiled.error.isEmpty ()); } @@ -546,34 +546,34 @@ private slots: QTest::addColumn<QString> ("message"); QTest::addColumn<QString> ("expected"); QTest::addColumn<bool> ("substituted"); - QTest::addColumn<bool> ("truncated"); QTest::newRow ("empty") << QString {} << QString {} - << false << false; + << false; QTest::newRow ("supported") << QString {"CQ KA1ABC CQ"} << QString {"CQ KA1ABC CQ"} - << false << false; + << false; QTest::newRow ("lowercase-preserved") << QString {"cq ka1abc cq"} << QString {"cq ka1abc cq"} - << false << false; + << false; QTest::newRow ("tab") << QString {"HELLO\tWORLD"} << QString {"HELLO#WORLD"} - << true << false; - QTest::newRow ("cr-lf") << QString {"HELLO\r\nWORLD"} << QString {"HELLO##WORLD"} - << true << false; + << true; + // '\n'/'\r' are now forced segment boundaries, not unsupported characters. + QTest::newRow ("cr-lf") << QString {"HELLO\r\nWORLD"} << QString {"HELLO\n\nWORLD"} + << false; QTest::newRow ("nul") << (QString {"A"} + QChar::Null + QString {"B"}) << QString {"A B"} - << true << false; + << true; QTest::newRow ("display-space-marker") << QString {"A~B"} << QString {"A B"} - << true << false; + << true; QTest::newRow ("exactly-80") << QString (80, QLatin1Char {'A'}) << QString (80, QLatin1Char {'A'}) - << false << false; - QTest::newRow ("truncated") << QString (81, QLatin1Char {'A'}) << QString (80, QLatin1Char {'A'}) - << false << true; + << false; + QTest::newRow ("long-input-preserved") << QString (81, QLatin1Char {'A'}) << QString (81, QLatin1Char {'A'}) + << false; QTest::newRow ("unsupported-past-limit") << (QString (80, QLatin1Char {'A'}) + QString {"\t"}) - << QString (80, QLatin1Char {'A'}) - << false << true; - QTest::newRow ("substitution-and-truncation") + << (QString (80, QLatin1Char {'A'}) + QString {"#"}) + << true; + QTest::newRow ("substitution-preserves-suffix") << (QString (79, QLatin1Char {'A'}) + QString {"\tB"}) - << (QString (79, QLatin1Char {'A'}) + QString {"#"}) - << true << true; + << (QString (79, QLatin1Char {'A'}) + QString {"#B"}) + << true; } void prepareTransmitText () @@ -581,72 +581,113 @@ private slots: QFETCH (QString, message); QFETCH (QString, expected); QFETCH (bool, substituted); - QFETCH (bool, truncated); auto const prepared = Jtty::prepareTransmitText (message); QCOMPARE (prepared.text, expected); QCOMPARE (prepared.substituted, substituted); - QCOMPARE (prepared.truncated, truncated); - QCOMPARE (prepared.changed (), substituted || truncated); - } - - void withChainedSpacing_data () - { - QTest::addColumn<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 {' '}); + QTest::newRow ("padded-to-width") + << QString {"CQ KA1ABC CQ"} << padded (QString {"CQ KA1ABC CQ"}); + QTest::newRow ("at-max-length-stays-exact") + << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}) + << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}); + QTest::newRow ("empty-all-spaces") + << QString {} << QString (Jtty::maxTransmitLength, QLatin1Char {' '}); + QTest::newRow ("oversized-rejected") + << QString (Jtty::maxTransmitLength + 1, QLatin1Char {'A'}) << QString {}; } void transmitFrame () { QFETCH (QString, message); - QFETCH (bool, isChained); QFETCH (QString, expected); - QString const frame = Jtty::transmitFrame (message, isChained); + QString const frame = Jtty::transmitFrame (message); QCOMPARE (frame, expected); - QCOMPARE (frame.size (), Jtty::maxTransmitLength); + QCOMPARE (frame.size (), message.size () > Jtty::maxTransmitLength + ? 0 : Jtty::maxTransmitLength); + } + + void transmitSegmentsCoverCompleteInput_data () + { + QTest::addColumn<QString> ("source"); + QTest::addColumn<int> ("firstLength"); + QTest::addColumn<int> ("segmentCount"); + + QTest::newRow ("79-characters") << QString (79, QLatin1Char {'A'}) << 79 << 1; + QTest::newRow ("80-characters") << QString (80, QLatin1Char {'A'}) << 80 << 1; + QTest::newRow ("81-characters") << QString (81, QLatin1Char {'A'}) << 80 << 2; + QTest::newRow ("word-boundary") + << (QString (70, QLatin1Char {'A'}) + QString {" WORDS CONTINUE"}) << 77 << 2; + QTest::newRow ("space-at-capacity") + << (QString (79, QLatin1Char {'A'}) + QString {" SUFFIX"}) << 80 << 2; + QTest::newRow ("space-after-capacity") + << (QString {"FIRST "} + QString (74, QLatin1Char {'A'}) + QString {" SUFFIX"}) + << 80 << 2; + QTest::newRow ("leading-space-before-long-token") + << (QString {" "} + QString (160, QLatin1Char {'A'})) << 80 << 3; + QTest::newRow ("many-spaces") << QString (200, QLatin1Char {' '}) << 80 << 3; + QTest::newRow ("substitution-after-first-segment") + << (QString (80, QLatin1Char {'A'}) + QString {"\tSUFFIX"}) << 80 << 2; + } + + void transmitSegmentsCoverCompleteInput () + { + QFETCH (QString, source); + QFETCH (int, firstLength); + QFETCH (int, segmentCount); + + QString const prepared = Jtty::prepareTransmitText (source).text; + QString reconstructed; + int offset {0}; + int count {0}; + while (offset < prepared.size ()) { + auto const segment = Jtty::nextTransmitTextSegment (prepared, offset); + QCOMPARE (segment.offset, offset); + QVERIFY (segment.length > 0); + QVERIFY (segment.length <= Jtty::maxTransmitLength); + QCOMPARE (segment.text, prepared.mid (offset, segment.length)); + if (count == 0) QCOMPARE (segment.length, firstLength); + reconstructed += segment.text; + offset += segment.length; + ++count; + } + QCOMPARE (count, segmentCount); + QCOMPARE (reconstructed, prepared); + } + + void transmitSegmentRetryRetainsSourceOffset () + { + QString const source {"PREFIX FIRST SECOND THIRD SUFFIX"}; + auto const initial = Jtty::nextTransmitTextSegment (source, 7, 19); + QCOMPARE (initial.text, QString {"FIRST SECOND THIRD "}); + auto const retry = Jtty::nextTransmitTextSegment (source, initial.offset, 12); + QCOMPARE (retry.offset, initial.offset); + QCOMPARE (retry.text, QString {"FIRST SECOND"}); + auto const next = Jtty::nextTransmitTextSegment (source, retry.offset + retry.length); + QCOMPARE (retry.text + next.text, source.mid (7)); + } + + void transmitSegmentEmptyAndInvalidRanges () + { + QVERIFY (Jtty::nextTransmitTextSegment (QString {}, 0).text.isEmpty ()); + QVERIFY (Jtty::nextTransmitTextSegment (QString {"ABC"}, -1).text.isEmpty ()); + QVERIFY (Jtty::nextTransmitTextSegment (QString {"ABC"}, 3).text.isEmpty ()); + QVERIFY (Jtty::nextTransmitTextSegment (QString {"ABC"}, 0, 0).text.isEmpty ()); + QCOMPARE (Jtty::nextTransmitTextSegment (QString (100, QLatin1Char {'A'}), 0, 100).length, + Jtty::maxTransmitLength); } void wavCaptureValid_data () @@ -746,6 +787,13 @@ private slots: QCOMPARE (Jtty::jttyLineTimeLabel (QDateTime {}), QString {}); } + void formatJttyTxLineLeavesSnrColumnBlank () + { + QCOMPARE (Jtty::formatJttyTxLine (1500.f, QString {"CQ K1ABC CQ"}), + QString {"1500 CQ K1ABC CQ"}); + QCOMPARE (Jtty::formatJttyTxLine (1500.4f, QString {}), QString {"1500 "}); + } + void parseDecodeLine_data () { QTest::addColumn<QString> ("line"); @@ -816,6 +864,39 @@ private slots: QCOMPARE (Jtty::wrapMessage (text), expected); } + void formatJttyDecodeLine_data () + { + QTest::addColumn<float> ("frequency"); + QTest::addColumn<int> ("snr"); + QTest::addColumn<QString> ("message"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("negative-two-digit-snr") + << 1513.f << -10 << QString {"CQ VA7TTO CQ"} + << QString {"1513 -10 CQ VA7TTO CQ"}; + QTest::newRow ("positive-snr-no-forced-sign") + << 1500.f << 5 << QString {"K1ABC W9XYZ"} + << QString {"1500 5 K1ABC W9XYZ"}; + QTest::newRow ("three-digit-frequency-padded") + << 500.f << 0 << QString {"HELLO"} + << QString {" 500 0 HELLO"}; + QTest::newRow ("multi-digit-snr") + << 1500.f << -100 << QString {"WEAK"} + << QString {"1500 -100 WEAK"}; + QTest::newRow ("empty-message-omits-snr") + << 1500.f << -10 << QString {} << QString {"1500"}; + } + + void formatJttyDecodeLine () + { + QFETCH (float, frequency); + QFETCH (int, snr); + QFETCH (QString, message); + QFETCH (QString, expected); + + QCOMPARE (Jtty::formatJttyDecodeLine (frequency, snr, message), expected); + } + void compareMessagesTracksMessageSemantics () { auto const unchanged = Jtty::compareMessages ( @@ -932,6 +1013,91 @@ private slots: QVERIFY (!Jtty::shouldApplyToQsoHistory (false, 1505.f, 1500.f, 5.f)); QVERIFY (Jtty::shouldApplyToQsoHistory (true, 1510.f, 1500.f, 5.f)); } + + void snrFormattingHasLeadingSignAndZeroPad () + { + QCOMPARE (Jtty::formatSnr (-10), QString {"-10"}); + QCOMPARE (Jtty::formatSnr (5), QString {"+05"}); + QCOMPARE (Jtty::formatSnr (-5), QString {"-05"}); + QCOMPARE (Jtty::formatSnr (0), QString {"+00"}); + QCOMPARE (Jtty::formatSnr (100), QString {"+100"}); + } + + void ft8StyleTemplatesMatchSpec () + { + QCOMPARE (Jtty::ft8StyleMacroTemplate (1), QString {"%H %M %G"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (2), QString {"%H %M %R"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (3), QString {"%H %M R%R"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (4), QString {"%H %M RRR"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (5), QString {"%H %M 73"}); + QCOMPARE (Jtty::ft8StyleMacroTemplate (6), QString {"CQ %M %G"}); + QVERIFY (Jtty::ft8StyleMacroTemplate (7).isEmpty ()); + QVERIFY (Jtty::ft8StyleMacroTemplate (8).isEmpty ()); + } + + void ft8StyleLiteralExpansionSubstitutesGridAndSnr () + { + // %G's own truncate-to-4 behavior for extended subsquare grids is covered + // separately by configuredSubsquareProducesGrid4InBothNativeAndLiteralExpansion; + // a plain 4-char grid here keeps this test focused on the %R substitution. + Jtty::NativeMacroContext context {QString {"K1ABC"}, QString {"W9XYZ"}, 0}; + context.grid = QStringLiteral ("FN20"); + context.snr = -7; + + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (1), context), + QString {"W9XYZ K1ABC FN20"}); + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (2), context), + QString {"W9XYZ K1ABC -07"}); + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (3), context), + QString {"W9XYZ K1ABC R-07"}); + QCOMPARE (Jtty::expandLiteralMacro (Jtty::ft8StyleMacroTemplate (6), context), + QString {"CQ K1ABC FN20"}); + } + + void messageStyleHelpersDistinguishContestAndFt8 () + { + QCOMPARE (Jtty::messageStyleSettingsKey (Jtty::MessageStyle::Contest, 3), + QString {"JTTY_msg3"}); + QCOMPARE (Jtty::messageStyleSettingsKey (Jtty::MessageStyle::Ft8, 3), + QString {"JTTY_FT8_msg3"}); + QCOMPARE (Jtty::messageStyleDefaultTemplate (Jtty::MessageStyle::Contest, 1), + Jtty::nativeMacroTemplate (1)); + QCOMPARE (Jtty::messageStyleDefaultTemplate (Jtty::MessageStyle::Ft8, 1), + Jtty::ft8StyleMacroTemplate (1)); + } + + void fillerTextIsRecognizedStandalone () + { + QVERIFY (Jtty::isJttyFillerText (Jtty::jttyFillerText)); + QVERIFY (Jtty::isJttyFillerText (QStringLiteral ("<<<<<"))); + QVERIFY (!Jtty::isJttyFillerText (QString {})); + QVERIFY (!Jtty::isJttyFillerText (QStringLiteral ("FOX"))); + QVERIFY (!Jtty::isJttyFillerText (QStringLiteral ("FOX <<<<<"))); + } + + void fillerStripLeavesRealTextUnaffected () + { + QCOMPARE (Jtty::stripJttyFillerText (QStringLiteral ("FOX JUMPED OVER")), + QStringLiteral ("FOX JUMPED OVER")); + } + + void fillerStripRemovesEmbeddedRunRegardlessOfSpacing () + { + // Squished with no separator, as a receiver could decode if neither side's own packing added a boundary space. + QCOMPARE (Jtty::stripJttyFillerText (QStringLiteral ("OVER<<<<< <<<<<THE")), + QStringLiteral ("OVER THE")); + // Normally spaced. + QCOMPARE (Jtty::stripJttyFillerText (QStringLiteral ("OVER <<<<< <<<<< THE")), + QStringLiteral ("OVER THE")); + // Only the first filler frame has arrived so far (message still growing). + QCOMPARE (Jtty::stripJttyFillerText (QStringLiteral ("OVER <<<<<")), + QStringLiteral ("OVER")); + } + + void fillerStripOfPureFillerIsEmpty () + { + QVERIFY (Jtty::stripJttyFillerText (Jtty::jttyFillerText).isEmpty ()); + } }; QTEST_MAIN (TestJttyMessages) diff --git a/tests/unit/jtty/test_jtty_n1mm.cpp b/tests/unit/jtty/test_jtty_n1mm.cpp index 7f2f167f..9dd42c90 100644 --- a/tests/unit/jtty/test_jtty_n1mm.cpp +++ b/tests/unit/jtty/test_jtty_n1mm.cpp @@ -2,6 +2,7 @@ #include "widgets/JttyN1mm.hpp" #include "widgets/JttyN1mmOutput.hpp" +#include "widgets/JttyMmttyHandoff.hpp" class TestJttyN1mm final : public QObject { @@ -76,6 +77,182 @@ private slots: QVERIFY (!output.takeCompletion (false, true)); } + void externalAbortResolvesOutstandingRequests () + { + Jtty::N1mmOutput output; + output.submit (1); + output.start (); + QVERIFY (output.accept (1)); + QVERIFY (output.pending ()); + + output.externalAbort (); + QVERIFY (!output.resolve (1)); + QVERIFY (output.takeCompletion (false, true)); + QVERIFY (!output.takeCompletion (false, true)); + } + + void externalAbortCompletesRejectedTransaction () + { + Jtty::N1mmOutput output; + output.submit (1); + output.start (); + QVERIFY (output.resolve (1)); + + output.externalAbort (); + QVERIFY (output.takeCompletion (false)); + } + + void timeoutCompletesOnce () + { + Jtty::N1mmOutput output; + output.submit (1); + output.start (); + output.externalAbort (); + + QVERIFY (output.takeCompletion (false)); + QVERIFY (!output.takeCompletion (false)); + output.finish (); + QVERIFY (!output.takeCompletion (false, true)); + } + + void explicitAbortSilentlyDiscardsOutput () + { + Jtty::N1mmOutput output; + output.submit (1); + output.start (); + QVERIFY (output.accept (1)); + + output.abort (); + QVERIFY (!output.resolve (1)); + QVERIFY (!output.takeCompletion (false, true)); + } + + void mmttyHandoffWaitsForPriorStop () + { + Jtty::MmttyHandoff handoff {25}; + QCOMPARE (handoff.timeoutMs (), 25); + handoff.queue (11); + handoff.waitForStop (); + + QVERIFY (handoff.active ()); + QCOMPARE (handoff.requestIds (), QVector<qint64> {11}); + QVERIFY (handoff.stopCompleted ()); + QVERIFY (!handoff.active ()); + QCOMPARE (handoff.requestIds (), QVector<qint64> {11}); + } + + void mmttyHandoffPreservesOrderAndAbort () + { + Jtty::MmttyHandoff handoff; + handoff.queue (21); + handoff.queue (22); + handoff.waitForStop (); + QCOMPARE (handoff.requestIds (), QVector<qint64> ({21, 22})); + + handoff.abort (); + QVERIFY (handoff.empty ()); + QVERIFY (!handoff.stopCompleted ()); + } + + void mmttyHandoffBoundsPendingRequests () + { + Jtty::MmttyHandoff handoff; + handoff.waitForStop (); + for (qint64 id = 1; id <= 64; ++id) QVERIFY (handoff.queue (id)); + QVERIFY (!handoff.queue (65)); + QCOMPARE (handoff.requestIds ().last (), qint64 (64)); + + handoff.submitted (1); + QVERIFY (handoff.queue (65)); + QVERIFY (!handoff.queue (66)); + handoff.abort (); + QVERIFY (handoff.queue (66)); + } + + void mmttyHandoffTimeoutRejectsAllQueuedRequests () + { + Jtty::MmttyHandoff handoff; + handoff.queue (31); + handoff.queue (32); + handoff.waitForStop (); + + QCOMPARE (handoff.expire (), QVector<qint64> ({31, 32})); + QVERIFY (handoff.empty ()); + QVERIFY (!handoff.active ()); + } + + void activeFt8ValidTextStopsBeforeSubmission () + { + using Action = Jtty::MmttyHandoff::SubmitAction; + QCOMPARE (Jtty::MmttyHandoff::planSubmission (true, false, true), + Action::StopThenSubmit); + + Jtty::MmttyHandoff handoff; + handoff.queue (41); + handoff.waitForStop (); + QVERIFY (handoff.active ()); + QVERIFY (handoff.stopCompleted ()); + QCOMPARE (handoff.requestIds (), QVector<qint64> {41}); + } + + void xmitOnRemainsDeferredAcrossHandoff () + { + Jtty::N1mmOutput output; + Jtty::MmttyHandoff handoff; + output.start (); + handoff.waitForStop (); + + QVERIFY (handoff.stopCompleted ()); + QVERIFY (output.startRequested ()); + output.submit (42); + QVERIFY (output.accept (42)); + output.started (); + QVERIFY (!output.startRequested ()); + } + + void invalidTextDoesNotDisturbActiveFt8 () + { + using Action = Jtty::MmttyHandoff::SubmitAction; + auto const compiled = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:UNKNOWN]] TEST")); + QCOMPARE (compiled.status, Jtty::N1mmCompileStatus::Error); + QCOMPARE (Jtty::MmttyHandoff::planSubmission (false, false, true), + Action::Reject); + + Jtty::MmttyHandoff handoff; + QVERIFY (!handoff.active ()); + QVERIFY (handoff.empty ()); + } + + void multipleTextsSubmitInOrderAfterStop () + { + Jtty::MmttyHandoff handoff; + handoff.queue (51); + handoff.queue (52); + handoff.waitForStop (); + QVERIFY (handoff.stopCompleted ()); + QCOMPARE (handoff.requestIds (), QVector<qint64> ({51, 52})); + + handoff.submitted (51); + handoff.submitted (52); + QVERIFY (handoff.empty ()); + } + + void abortDuringHandoffSilentlyDiscardsOutput () + { + Jtty::N1mmOutput output; + Jtty::MmttyHandoff handoff; + output.submit (61); + output.start (); + handoff.queue (61); + handoff.waitForStop (); + + handoff.abort (); + output.abort (); + QVERIFY (handoff.empty ()); + QVERIFY (!output.takeCompletion (false, true)); + } + void everyActionCompiles () { struct Example diff --git a/tests/unit/jtty/test_jtty_overlap_decode.f90 b/tests/unit/jtty/test_jtty_overlap_decode.f90 index b440d1f3..97777859 100644 --- a/tests/unit/jtty/test_jtty_overlap_decode.f90 +++ b/tests/unit/jtty/test_jtty_overlap_decode.f90 @@ -5,8 +5,8 @@ program test_jtty_overlap_decode ! ! The 4 Hz case reproduces leftover extra-slot fragments: a real next ! frame lands just outside the 3 Hz continuation gate and opens a new - ! message instead of staying on its assembly. Isolated and 2 Hz cases are - ! controls that already pass. + ! message instead of staying on its assembly. The 2 Hz case is a control + ! for assembly with closer overlap. Both cases require two complete messages. use iso_fortran_env, only: int16 use jtty_fec, only: is13, TOTAL_K @@ -25,10 +25,6 @@ program test_jtty_overlap_decode if(len_trim(rate_arg).gt.0) read(rate_arg,*) nsps failures=0 - call expect_complete_pair('isolated first message',msg_a,1500.0,0.2, & - '',1500.0,0.6,1,failures) - call expect_complete_pair('isolated second message','',1500.0,0.2, & - msg_b,1504.0,0.6,1,failures) call expect_complete_pair('2 Hz overlap stays two complete messages', & msg_a,1500.0,0.2,msg_b,1502.0,0.6,2,failures) @@ -148,11 +144,13 @@ contains found_b=len_trim(second_message).eq.0 do i=1,npending if(len_trim(first_message).gt.0) then - if(trim(normalized(pending_updates(i)%decoded)).eq.trim(first_message)) & + if(pending_updates(i)%complete .and. & + trim(normalized(pending_updates(i)%decoded)).eq.trim(first_message)) & found_a=.true. endif if(len_trim(second_message).gt.0) then - if(trim(normalized(pending_updates(i)%decoded)).eq.trim(second_message)) & + if(pending_updates(i)%complete .and. & + trim(normalized(pending_updates(i)%decoded)).eq.trim(second_message)) & found_b=.true. endif enddo diff --git a/tests/unit/jtty/test_jtty_pack.f90 b/tests/unit/jtty/test_jtty_pack.f90 index 31541cfb..2ffd23ab 100644 --- a/tests/unit/jtty/test_jtty_pack.f90 +++ b/tests/unit/jtty/test_jtty_pack.f90 @@ -2,6 +2,7 @@ program test_jtty_pack use jtty_mod use packjt77, only: pack28 + use packjt77_grammar, only: pack77_arrl_section_index character*80 msg0,msg,expected character*34 c32(MAX_FRAMES) character*17 cparms @@ -71,6 +72,10 @@ program test_jtty_pack call expect_pack('FN42',1,2,-1,-1,-1) call expect_pack('1D EMA',1,2,-1,-1,-1) call expect_pack('32F EMA',1,2,-1,-1,-1) + call expect_pack('1F DX',1,2,-1,-1,-1) + call expect_pack('2A CT',1,2,-1,-1,-1) + call expect_pack('10A CT',1,2,-1,-1,-1) + call expect_pack('32F DX',1,2,-1,-1,-1) call expect_pack('0',1,2,-1,-1,-1) call expect_pack('131071',1,2,-1,-1,-1) call expect_pack('599 131071',1,2,-1,-1,-1) @@ -83,6 +88,9 @@ program test_jtty_pack call expect_pack('33D EMA',2,3,-1,3,-1) call expect_pack('1G EMA',2,3,-1,3,-1) call expect_pack('1D ZZZ',2,3,-1,3,-1) + call expect_pack('1D EMAX',2,3,-1,3,-1) + call expect_pack('K1ABC 1D EMAX QSL TU',4,0,1,3,-1) + call expect_pack('K1ABC 1D EMAX X QSL TU',4,0,1,3,-1) call expect_pack('599 SA00',2,-1,-1,-1,-1) call expect_pack('599 A!',2,-1,-1,-1,-1) call expect_pack('599 XYZ',1,2,-1,-1,-1) @@ -107,6 +115,8 @@ program test_jtty_pack call expect_pack('PSE AGN NR',2,-1,-1,-1,-1) call expect_pack('AGN NR PSE',2,2,-1,3,-1) call expect_control_phrase_literals() + call expect_atom('1F DX',jtty_class_section_atom(1,'F',pack77_arrl_section_index('DX '))) + call expect_atom('2A CT',jtty_class_section_atom(2,'A',pack77_arrl_section_index('CT '))) call expect_atom('599 123',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_GENERIC,123)) call expect_atom('123',jtty_exch_num_atom(JTTY_ROLE_FIELD_ONLY,JTTY_NUM_GENERIC,123)) call expect_atom('599 MA',jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_QTH,'MA')) @@ -150,7 +160,7 @@ contains subroutine expect_exchange_profiles() character(len=80), parameter :: examples(*)=[character(len=80) :: & '599 001','K1ABC 599 001','599 05','599 0123','001','599 123', & - '599 MA','599 131071','599 0AB','1D EMA','CQ K1ABC CQ','K1A A'] + '599 MA','599 131071','599 0AB','1D EMA','1F DX','10A CT','32F DX','CQ K1ABC CQ','K1A A'] character(len=80) :: input,decoded character(len=34) :: baseline(MAX_FRAMES),frames(MAX_FRAMES) integer :: i,profile,baseline_nf,nframes diff --git a/tests/unit/jtty/test_jtty_receive_history.cpp b/tests/unit/jtty/test_jtty_receive_history.cpp new file mode 100644 index 00000000..1f5dad36 --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_history.cpp @@ -0,0 +1,87 @@ +#include <QtTest> +#include <algorithm> +#include <vector> + +#include "JttyReceiveHistory.hpp" + +class TestJttyReceiveHistory final : public QObject +{ + Q_OBJECT +private slots: + void rotationsRetainExactSuffixAcrossPacketBoundaries () + { + Jtty::ReceiveHistory history {17}; + qint64 const origin = qint64 (1) << 35; + std::vector<short> received; + for (int packet = 0; packet < 200; ++packet) { + int const count = 1 + packet % 7; + std::vector<short> incoming (count); + for (int i = 0; i < count; ++i) incoming[i] = short (received.size () + i); + auto const first = origin + qint64 (received.size ()); + received.insert (received.end (), incoming.begin (), incoming.end ()); + QVERIFY (history.append (12, first, incoming.data (), count)); + auto const retained = std::min<qint64> (17, received.size ()); + auto const end = origin + qint64 (received.size ()); + QCOMPARE (history.size (), retained); + QCOMPARE (history.first (12), end - retained); + QCOMPARE (history.end (12), end); + std::vector<short> expected (received.end () - retained, received.end ()); + QVERIFY (history.snapshot (12, end - retained, end) == expected); + QVERIFY (history.snapshot (12, end - retained - 1, end).empty ()); + QVERIFY (history.snapshot (12, end - retained, end + 1).empty ()); + } + } + + void snapshotsNeverJoinReceptionsWithMatchingCoordinates () + { + Jtty::ReceiveHistory history {12}; + short const first[] = {1, 2, 3, 4}; + short const second[] = {5, 6, 7, 8}; + short const third[] = {9, 10, 11, 12}; + QVERIFY (history.append (1, 0, first, 4)); + QVERIFY (history.append (2, 4, second, 4)); + QVERIFY (history.snapshot (1, 0, 8).empty ()); + QVERIFY (history.snapshot (2, 0, 8).empty ()); + QVERIFY (history.append (3, 0, third, 4)); + QVERIFY (history.snapshot (1, 0, 4) == std::vector<short> ({1, 2, 3, 4})); + QVERIFY (history.snapshot (3, 0, 4) == std::vector<short> ({9, 10, 11, 12})); + QVERIFY (history.append (3, 4, third, 4)); + QCOMPARE (history.first (1), qint64 (-1)); + QCOMPARE (history.end (1), qint64 (-1)); + QCOMPARE (history.first (2), qint64 (4)); + QCOMPARE (history.first (3), qint64 (0)); + } + + void gapsAndDuplicatesFailWithoutChangingRetainedAudio () + { + Jtty::ReceiveHistory history {10}; + short const samples[] = {1, 2, 3, 4}; + QVERIFY (history.append (3, 7, samples, 4)); + QVERIFY (!history.append (3, 12, samples, 4)); + QVERIFY (!history.append (3, 7, samples, 4)); + QCOMPARE (history.size (), qint64 (4)); + QCOMPARE (history.end (3), qint64 (11)); + QVERIFY (history.snapshot (3, 7, 11) == std::vector<short> ({1, 2, 3, 4})); + QVERIFY (history.append (3, 11, samples, 4)); + QVERIFY (history.snapshot (3, 9, 13) == std::vector<short> ({3, 4, 1, 2})); + } + + void snapshotsOwnAudioBeyondInputReuseAndEviction () + { + Jtty::ReceiveHistory history {6}; + short samples[] = {1, 2, 3, 4}; + QVERIFY (history.append (4, 0, samples, 4)); + std::fill (std::begin (samples), std::end (samples), 9); + auto const saved = history.snapshot (4, 1, 4); + QVERIFY (saved == std::vector<short> ({2, 3, 4})); + QVERIFY (history.append (4, 4, samples, 4)); + QVERIFY (history.snapshot (4, 0, 4).empty ()); + history.clear (); + QCOMPARE (history.size (), qint64 (0)); + QVERIFY (history.snapshot (4, 1, 4).empty ()); + QVERIFY (saved == std::vector<short> ({2, 3, 4})); + } +}; + +QTEST_APPLESS_MAIN (TestJttyReceiveHistory) +#include "test_jtty_receive_history.moc" diff --git a/tests/unit/jtty/test_jtty_receive_line.cpp b/tests/unit/jtty/test_jtty_receive_line.cpp new file mode 100644 index 00000000..b25c7cfc --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_line.cpp @@ -0,0 +1,209 @@ +#include <QtTest> +#include <QTextDocument> +#include "JttyReceiveLine.hpp" + +class TestJttyReceiveLine final : public QObject +{ + Q_OBJECT + + static JttyReceiveLine::Presentation message (qint64 id, QString const& text, + double seconds = 0, quint64 group = 1) + { + return {group, id, QDateTime {QDate {2026, 9, 11}, QTime {12, 34, 56}, Qt::UTC}, + seconds, 1500, text}; + } + +private slots: + void growingWrappedLinePreservesOtherMessagesAndTransmitText () + { + QTextDocument document; + JttyReceiveLine first, second; + QFont const font {"Monospace", 10}; + QVERIFY (!first.render (document, message (11, "CQ TEST\nCONTINUATION"), {}, font).isNull ()); + QVERIFY (!second.render (document, message (12, "ANOTHER MESSAGE"), {}, font).isNull ()); + QTextCursor tx (&document); + tx.movePosition (QTextCursor::End); + tx.insertBlock (); + QTextBlockFormat txBlock; + txBlock.setBackground (Qt::yellow); + tx.setBlockFormat (txBlock); + QTextCharFormat txText; + txText.setForeground (Qt::red); + tx.insertText ("Tx: MY RESPONSE", txText); + QVERIFY (!first.render (document, message (11, "CQ TEST\nCONTINUATION COMPLETE"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 CQ TEST\nCONTINUATION COMPLETE\n1500 -10 ANOTHER MESSAGE\nTx: MY RESPONSE"}); + JttyReceiveLine::refresh (document, {true, true}, font); + QCOMPARE (document.toPlainText (), QString { + "123456 1500 -10 cq test\ncontinuation complete\n123456 1500 -10 another message\nTx: MY RESPONSE"}); + QCOMPARE (document.lastBlock ().blockFormat (), txBlock); + QTextCursor check (document.lastBlock ()); + check.movePosition (QTextCursor::NextCharacter, QTextCursor::KeepAnchor); + QCOMPARE (check.charFormat ().foreground (), txText.foreground ()); + QVERIFY (!second.render (document, message (12, "ANOTHER MESSAGE COMPLETE"), {true, true}, font).isNull ()); + QCOMPARE (document.lastBlock ().text (), QString {"Tx: MY RESPONSE"}); + QVERIFY (second.render (document, message (12, "ANOTHER MESSAGE COMPLETE"), {true, true}, font).isNull ()); + } + + void completedRecordsRefreshAndRestoreCanonicalCase () + { + QTextDocument document; + QFont const font {"Monospace", 10}; + { + JttyReceiveLine completed; + QVERIFY (!completed.render (document, message (1, "CQ MiXeD CASE"), {}, font).isNull ()); + } + QFont const larger {"Monospace", 14}; + JttyReceiveLine::refresh (document, {true, true}, larger); + QCOMPARE (document.toPlainText (), QString {"123456 1500 -10 cq mixed case"}); + QTextCursor check (document.begin ()); + check.movePosition (QTextCursor::NextCharacter, QTextCursor::KeepAnchor); + QCOMPARE (check.charFormat ().font ().pointSize (), 14); + JttyReceiveLine::refresh (document, {false, false}, font); + QCOMPARE (document.toPlainText (), QString {"1500 -10 CQ MiXeD CASE"}); + } + + void lateEarlierMessagesAndEqualTimeIdsAreOrdered () + { + QTextDocument document; + QFont const font; + { + JttyReceiveLine completed; + QVERIFY (!completed.render (document, message (30, "LATE", 30), {}, font, true).isNull ()); + } + JttyReceiveLine earlier, equal, middle; + QVERIFY (!earlier.render (document, message (20, "EARLIER", 10), {}, font, true).isNull ()); + QVERIFY (!equal.render (document, message (10, "EQUAL TIME LOWER ID", 10), {}, font, true).isNull ()); + QVERIFY (!middle.render (document, message (25, "MIDDLE", 20), {}, font, true).isNull ()); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 EQUAL TIME LOWER ID\n1500 -10 EARLIER\n1500 -10 MIDDLE\n1500 -10 LATE"}); + JttyReceiveLine::refresh (document, {true, false}, font); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 equal time lower id\n1500 -10 earlier\n1500 -10 middle\n1500 -10 late"}); + QVERIFY (!earlier.render (document, message (20, "EARLIER COMPLETE", 10), {true, false}, font, true).isNull ()); + QCOMPARE (document.findBlockByNumber (1).text (), QString {"1500 -10 earlier complete"}); + } + + void chronologyStaysWithinItsGroupAndQsoAppends () + { + QTextDocument document; + QFont const font; + JttyReceiveLine first, second, late, early, qso; + QVERIFY (!first.render (document, message (1, "GROUP ONE", 20, 1), {}, font, true).isNull ()); + QTextCursor heading (&document); + heading.movePosition (QTextCursor::End); + heading.insertBlock (); + QTextBlockFormat headingFormat; + headingFormat.setAlignment (Qt::AlignRight); + heading.setBlockFormat (headingFormat); + heading.insertText ("FILE HEADING"); + QVERIFY (!second.render (document, message (1, "GROUP TWO", 5, 2), {}, font, true).isNull ()); + QVERIFY (!late.render (document, message (2, "GROUP ONE LATER", 30, 1), {}, font, true).isNull ()); + QVERIFY (!early.render (document, message (0, "GROUP TWO EARLIER", 1, 2), {}, font, true).isNull ()); + QVERIFY (!qso.render (document, message (0, "QSO APPENDED", 0, 1), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString { + "1500 -10 GROUP ONE\n1500 -10 GROUP ONE LATER\nFILE HEADING\n1500 -10 GROUP TWO EARLIER\n1500 -10 GROUP TWO\n1500 -10 QSO APPENDED"}); + QCOMPARE (document.findBlockByNumber (2).blockFormat (), headingFormat); + } + + void eraseAndReplacementCannotReuseOldOwnership () + { + QTextDocument document; + JttyReceiveLine old, replacement; + QFont const font; + QVERIFY (!old.render (document, message (1, "OLD PARTIAL"), {}, font).isNull ()); + document.clear (); + QVERIFY (!replacement.render (document, message (2, "NEW MESSAGE"), {}, font).isNull ()); + QVERIFY (old.render (document, message (1, "OLD PARTIAL COMPLETED"), {}, font).isNull ()); + JttyReceiveLine::refresh (document, {true, false}, font); + QCOMPARE (document.toPlainText (), QString {"1500 -10 new message"}); + QVERIFY (!replacement.render (document, message (2, "NEW MESSAGE COMPLETED"), {}, font).isNull ()); + QVERIFY (old.render (document, message (1, "OLD PARTIAL COMPLETED"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 NEW MESSAGE COMPLETED"}); + } + + void prunedBlocksCannotEraseReusedBlocksOrReappear () + { + QTextDocument document; + document.setMaximumBlockCount (3); + JttyReceiveLine old; + QFont const font; + QVERIFY (!old.render (document, message (1, "OLD PARTIAL\nOLD CONTINUATION"), {}, font).isNull ()); + for (int i = 0; i < 20; ++i) { + JttyReceiveLine archived; + QVERIFY (!archived.render (document, message (i + 2, QString::number (i)), {}, font).isNull ()); + } + auto const retained = document.toPlainText (); + QVERIFY (old.render (document, message (1, "OLD PARTIAL COMPLETE"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), retained); + QCOMPARE (document.blockCount (), 3); + } + + void partiallyPrunedWrappedRecordIsNotRefreshed () + { + QTextDocument document; + document.setMaximumBlockCount (3); + QFont const font; + JttyReceiveLine wrapped; + QString const longMessage (90, QLatin1Char {'A'}); + QVERIFY (!wrapped.render (document, message (1, longMessage), {}, font).isNull ()); + QCOMPARE (document.blockCount (), 3); + { + JttyReceiveLine completed; + QVERIFY (!completed.render (document, message (2, "RETAINED"), {}, font).isNull ()); + } + auto const first = document.begin ().text (); + auto const second = document.begin ().next ().text (); + JttyReceiveLine::refresh (document, {true, true}, font); + QCOMPARE (document.begin ().text (), first); + QCOMPARE (document.begin ().next ().text (), second); + QCOMPARE (document.lastBlock ().text (), QString {"123456 1500 -10 retained"}); + QVERIFY (wrapped.render (document, message (1, longMessage + " COMPLETE"), {}, font).isNull ()); + document.clear (); + JttyReceiveLine::refresh (document, {}, font); + QVERIFY (document.toPlainText ().isEmpty ()); + } + + void earlierInsertAtHistoryLimitCannotTakeExistingOwnership () + { + QTextDocument document; + document.setMaximumBlockCount (1); + QFont const font; + JttyReceiveLine retained, earlier; + QVERIFY (!retained.render (document, message (2, "RETAINED", 20), {}, font, true).isNull ()); + QVERIFY (earlier.render (document, message (1, "EARLIER", 10), {}, font, true).isNull ()); + JttyReceiveLine::refresh (document, {true, false}, font); + QCOMPARE (document.toPlainText (), QString {"1500 -10 retained"}); + QVERIFY (!retained.render (document, message (2, "RETAINED COMPLETE", 20), {}, font, true).isNull ()); + QVERIFY (earlier.render (document, message (1, "EARLIER COMPLETE", 10), {}, font, true).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 RETAINED COMPLETE"}); + } + + void foreignTextInsideOwnedRangeIsNeverDeleted () + { + QTextDocument document; + JttyReceiveLine old; + QFont const font; + QVERIFY (!old.render (document, message (1, "PARTIAL"), {}, font).isNull ()); + QTextCursor external (&document); + external.movePosition (QTextCursor::End); + external.insertText (" UNRELATED TEXT"); + JttyReceiveLine::refresh (document, {true, true}, font); + QVERIFY (old.render (document, message (1, "PARTIAL COMPLETED"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 PARTIAL UNRELATED TEXT"}); + } + + void movedActiveHandleStillOwnsItsMessage () + { + QTextDocument document; + JttyReceiveLine line; + QFont const font; + QVERIFY (!line.render (document, message (9, "PARTIAL"), {}, font).isNull ()); + auto moved = std::move (line); + QVERIFY (!moved.render (document, message (9, "PARTIAL COMPLETE"), {}, font).isNull ()); + QCOMPARE (document.toPlainText (), QString {"1500 -10 PARTIAL COMPLETE"}); + } +}; + +QTEST_MAIN (TestJttyReceiveLine) +#include "test_jtty_receive_line.moc" diff --git a/tests/unit/jtty/test_jtty_receive_results.cpp b/tests/unit/jtty/test_jtty_receive_results.cpp new file mode 100644 index 00000000..af88d9e6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_results.cpp @@ -0,0 +1,396 @@ +#include <QtTest> +#include <QTextDocument> + +#include "JttyReceiveResultController.hpp" + +namespace { +using Controller = Jtty::ReceiveResultController; +using Source = Controller::Source; +using Pane = Controller::Pane; +using Terminal = Jtty::ReceiveTerminal; + +Jtty::ReceiveUpdate update (qint64 id, QString const& text, + Terminal terminal = Terminal::Growing, + float frequency = 1500, int snr = -7) +{ + return {id, frequency, text, 2.25, 4.5, terminal, snr}; +} + +struct Harness +{ + Controller controller; + QTextDocument all, qso; + QFont font {"Monospace", 10}; + Controller::Reception reception; + Controller::Selection selection {true, 1, 1500, 50}; + JttyReceiveLine::Options display; + Controller::EchoOptions echo {true, false}; + bool reporting {true}; + QStringList trace, echoes, logs; + QVector<DecodeOperatingContext> logContexts; + QVector<Controller::Spot> spots; + QVector<QPair<qint64, qint64>> intervals; + QVector<JttyReceiveLine::Presentation> presentations; + std::function<void(QString const&)> after; + Controller::Inputs inputs; + Controller::Effects effects; + + void event (QString const& name) + { + trace.append (name); + if (after) after (name); + } + + Harness () + { + reception.contextId = 1; + reception.displayGroup = 1; + reception.anchor = QDateTime {QDate {2026, 9, 11}, QTime {12, 34, 56}, Qt::UTC}; + reception.displayAnchor = reception.anchor; + reception.context.mode = "JTTY"; + reception.context.myCall = "N0ME"; + reception.context.periodFrequency = 14078000; + reception.context.band = "20m"; + inputs.display = [this] { event ("display"); return display; }; + inputs.selection = [this] { event ("selection"); return selection; }; + inputs.echo = [this] { event ("echo-options"); return echo; }; + inputs.reporting = [this] { event ("reporting"); return reporting; }; + effects.reviewHeading = [this] (Pane pane) { + auto& document = pane == Pane::All ? all : qso; + QTextCursor cursor {&document}; + cursor.movePosition (QTextCursor::End); + if (cursor.position ()) cursor.insertBlock (); + cursor.insertText ("REVIEW"); + event (pane == Pane::All ? "heading-all" : "heading-qso"); + }; + effects.render = [this] (Pane pane, JttyReceiveLine& line, + JttyReceiveLine::Presentation const& presentation, + JttyReceiveLine::Options const& options) { + line.render (pane == Pane::All ? all : qso, presentation, options, + font, pane == Pane::All); + presentations.append (presentation); + event (pane == Pane::All ? "all" : "qso"); + }; + effects.echo = [this] (QString const& text) { echoes.append (text); event ("echo"); }; + effects.noteDecoded = [this] (qint64 first, qint64 last) { + intervals.append (qMakePair (first, last)); event ("recording"); + }; + effects.log = [this] (QString const& text, DecodeOperatingContext const& context) { + logs.append (text); logContexts.append (context); event ("log"); + }; + effects.spot = [this] (Controller::Spot const& spot) { spots.append (spot); event ("spot"); }; + } + + void apply (QVector<Jtty::ReceiveUpdate> const& updates) + { + controller.apply (updates, reception, inputs, effects); + } +}; +} + +class TestJttyReceiveResults final : public QObject +{ + Q_OBJECT + +private slots: + void interleavedGrowthAndTerminalOnlyDelivery () + { + Harness h; + h.apply ({update (1, "CQ K1ABC"), update (2, "OTHER")}); + auto const firstBlock = h.all.begin (); + auto const firstQsoBlock = h.qso.begin (); + h.apply ({update (1, "CQ K1ABC FN42"), update (1, "CQ K1ABC FN42", Terminal::Complete), + update (3, "CQ K1ABC FN42", Terminal::Complete)}); + QCOMPARE (h.all.blockCount (), 3); + QCOMPARE (h.qso.blockCount (), 3); + QCOMPARE (h.all.begin (), firstBlock); + QCOMPARE (h.qso.begin (), firstQsoBlock); + QCOMPARE (h.all.toPlainText (), QString {"1500 -7 CQ K1ABC FN42\n1500 -7 OTHER\n1500 -7 CQ K1ABC FN42"}); + QCOMPARE (h.logs.size (), 2); + QCOMPARE (h.logs.front (), QString {"1500 -7 CQ K1ABC FN42"}); + QCOMPARE (h.spots.size (), 2); + QCOMPARE (h.intervals.size (), 5); + QCOMPARE (h.intervals.front (), qMakePair (qint64 {54000}, qint64 {76656})); + h.apply ({update (1, "CQ K1ABC FN42", Terminal::Complete)}); + QCOMPARE (h.logs.size (), 3); + QCOMPARE (h.spots.size (), 3); + QCOMPARE (h.all.blockCount (), 4); + } + + void sourceAndTerminalPolicy_data () + { + QTest::addColumn<int> ("source"); + QTest::addColumn<int> ("terminal"); + QTest::addColumn<bool> ("empty"); + for (int source = 0; source < 3; ++source) + for (int terminal = 0; terminal < 4; ++terminal) + for (bool empty : {false, true}) { + auto const name = QString {"source-%1-terminal-%2-empty-%3"}.arg (source).arg (terminal).arg (empty); + QTest::newRow (qPrintable (name)) << source << terminal << empty; + } + } + + void sourceAndTerminalPolicy () + { + QFETCH (int, source); + QFETCH (int, terminal); + QFETCH (bool, empty); + Harness h; + h.reception.source = static_cast<Source> (source); + auto const review = h.reception.source == Source::Review; + auto const live = h.reception.source == Source::Live; + h.apply ({update (1, empty ? QString {} : QString {"CQ K1ABC FN42"}, static_cast<Terminal> (terminal))}); + QCOMPARE (h.logs.size (), int (!empty && !review && terminal != 0)); + QCOMPARE (h.spots.size (), int (!empty && live && terminal == 1)); + QCOMPARE (h.intervals.size (), int (!empty && live)); + QCOMPARE (h.echoes.size (), int (!empty && !review)); + QCOMPARE (h.trace.count ("heading-all"), int (!empty && review)); + QCOMPARE (h.trace.count ("heading-qso"), int (!empty && review)); + QCOMPARE (h.presentations.size (), empty ? 0 : 2); + if (empty) QVERIFY (h.trace.isEmpty ()); + } + + void tuningAdmissionIsStickyAndUsesCurrentLiveContext () + { + Harness h; + h.selection.center = 1600; + h.apply ({update (1, "EXCLUDED")}); + QVERIFY (h.qso.isEmpty ()); + h.selection.center = 1500; + QVERIFY (h.qso.isEmpty ()); + h.apply ({update (1, "EXCLUDED")}); + QVERIFY (h.qso.toPlainText ().contains ("EXCLUDED")); + QCOMPARE (h.echoes, QStringList {"\r\nEXCLUDED"}); + h.selection.center = 1700; + h.apply ({update (1, "EXCLUDED NOW INCLUDED")}); + QVERIFY (h.qso.toPlainText ().contains ("EXCLUDED NOW INCLUDED")); + QCOMPARE (h.echoes.last (), QString {" NOW INCLUDED"}); + + for (Source source : {Source::Live, Source::Review, Source::Wav}) { + Harness captured; + captured.reception.source = source; + captured.selection.contextId = 2; + captured.selection.center = 1700; + captured.apply ({update (1, "CAPTURED")}); + QVERIFY (captured.qso.toPlainText ().contains ("CAPTURED")); + } + Harness inactive; + inactive.selection.jttyActive = false; + inactive.selection.center = 1700; + inactive.apply ({update (1, "INACTIVE")}); + QVERIFY (inactive.qso.toPlainText ().contains ("INACTIVE")); + } + + void retainedContextAndPresentationHaveSeparateAnchors () + { + Harness h; + auto const firstAnchor = h.reception.anchor; + h.reception.displayAnchor = firstAnchor.addDays (1); + h.display = {true, true}; + h.apply ({update (1, "CQ K1ABC")}); + auto const trace = h.trace; + h.apply ({update (1, {}, Terminal::Complete)}); + QCOMPARE (h.trace, trace); + h.reception.context.myCall = "K1ABC"; + h.reception.context.periodFrequency = 7000000; + h.reception.context.band = "40m"; + h.reception.anchor = firstAnchor.addDays (2); + h.reception.displayAnchor = firstAnchor.addDays (3); + auto complete = update (1, "CQ K1ABC FN42", Terminal::Complete, 1500.6f, -3); + complete.startSeconds = 9; + h.apply ({complete}); + QCOMPARE (h.logContexts.size (), 1); + QCOMPARE (h.logContexts.front ().sequenceStart, firstAnchor.addMSecs (2250)); + QCOMPARE (h.logContexts.front ().band, QString {"20m"}); + QCOMPARE (h.logContexts.front ().myCall, QString {"N0ME"}); + QCOMPARE (h.logs.front (), QString {"1501 -3 CQ K1ABC FN42"}); + QCOMPARE (h.presentations.last ().startUtc, h.reception.displayAnchor.addSecs (9)); + QCOMPARE (h.spots.size (), 1); + auto const& spot = h.spots.front (); + QCOMPARE (spot.sender, QString {"K1ABC"}); + QCOMPARE (spot.grid, QString {"FN42"}); + QCOMPARE (spot.frequency, Radio::Frequency {14079501}); + QCOMPARE (spot.mode, QString {"JTTY"}); + QCOMPARE (spot.snr, -3); + QCOMPARE (spot.time, firstAnchor.addMSecs (2250)); + QCOMPARE (spot.time.timeSpec (), Qt::UTC); + QVERIFY (h.all.toPlainText ().contains ("cq k1abc fn42")); + } + + void reportSyntax_data () + { + QTest::addColumn<QString> ("text"); + QTest::addColumn<bool> ("eligible"); + QTest::addColumn<QString> ("grid"); + QTest::newRow ("cq") << QString {"cq k1abc fn42ab"} << true << QString {"fn42ab"}; + QTest::newRow ("de") << QString {"De K1ABC"} << true << QString {}; + QTest::newRow ("call pair") << QString {"W9XYZ K1ABC FN42"} << true << QString {"FN42"}; + QTest::newRow ("portable") << QString {"CQ K1ABC/P FN42"} << true << QString {"FN42"}; + QTest::newRow ("invalid grid") << QString {"CQ K1ABC ZZ99"} << true << QString {}; + QTest::newRow ("rr73") << QString {"CQ K1ABC RR73"} << true << QString {}; + QTest::newRow ("free text") << QString {"HELLO K1ABC FN42"} << false << QString {}; + QTest::newRow ("invalid sender") << QString {"CQ EA8/K1ABC FN42"} << false << QString {}; + QTest::newRow ("self") << QString {"CQ n0me FN42"} << false << QString {}; + QTest::newRow ("missing sender") << QString {"CQ"} << false << QString {}; + } + + void reportSyntax () + { + QFETCH (QString, text); + QFETCH (bool, eligible); + QFETCH (QString, grid); + Harness h; + h.apply ({update (1, text, Terminal::Complete)}); + QCOMPARE (h.spots.size (), int (eligible)); + if (eligible) QCOMPARE (h.spots.front ().grid, grid); + h.reporting = false; + h.apply ({update (2, text, Terminal::Complete)}); + QCOMPARE (h.spots.size (), int (eligible)); + h.reporting = true; + h.reception.anchor = {}; + h.apply ({update (3, text, Terminal::Complete)}); + QCOMPARE (h.spots.size (), int (eligible)); + } + + void snapshotsAndEffectsFollowSynchronousPhases () + { + Harness h; + h.selection.center = 1700; + h.reporting = false; + h.after = [&h] (QString const& event) { + if (event == "all") { h.selection.center = 1500; h.display.lowerCase = true; } + if (event == "qso") h.echo.lowerCase = true; + if (event == "log") h.reporting = true; + if (event == "spot") + QCOMPARE (h.controller.snrForSelectedWord ("K1ABC", Pane::All), -10); + }; + h.apply ({update (1, "CQ K1ABC FN42", Terminal::Complete)}); + QCOMPARE (h.trace, QStringList ({"display", "all", "selection", "qso", "echo-options", + "echo", "recording", "log", "reporting", "spot"})); + QVERIFY (h.qso.toPlainText ().contains ("CQ K1ABC FN42")); + QCOMPARE (h.echoes, QStringList {"\r\ncq k1abc fn42"}); + QCOMPARE (h.spots.size (), 1); + QCOMPARE (h.controller.snrForSelectedWord ("K1ABC", Pane::All), -7); + } + + void echoDeltaPolicy () + { + Harness h; + h.apply ({update (1, "FIRST"), update (1, "FIRST LONGER"), update (1, "FIRST LONGER"), + update (1, "REPLACED")}); + QCOMPARE (h.echoes, QStringList ({"\r\nFIRST", " LONGER", "\r\nREPLACED"})); + h.echo.enabled = false; + h.apply ({update (1, "REPLACED SILENT")}); + QCOMPARE (h.echoes.size (), 3); + h.echo = {true, true}; + h.apply ({update (1, "REPLACED SILENT END", Terminal::Complete)}); + QCOMPARE (h.echoes.last (), QString {" end"}); + } + + void replayResetAndRefreshPreserveLiveHistory () + { + Harness h; + h.apply ({update (1, "LIVE")}); + h.reception.source = Source::Review; + h.reception.displayGroup = 2; + h.apply ({update (2, {})}); + QCOMPARE (h.trace.count ("heading-all"), 0); + h.apply ({update (2, "REVIEW MESSAGE", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 1); + QVERIFY (h.trace.indexOf ("heading-all") < h.trace.indexOf ("heading-qso")); + h.reception.displayGroup = 3; + h.apply ({update (3, "LATER REVIEW", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 1); + h.controller.resetReplay (); + h.reception.displayGroup = 4; + h.apply ({update (4, "RESET REVIEW", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 2); + h.reception.source = Source::Wav; + h.reception.displayGroup = 5; + h.apply ({update (5, "WAV", Terminal::Complete)}); + QCOMPARE (h.trace.count ("heading-all"), 2); + h.reception.source = Source::Live; + h.reception.displayGroup = 1; + h.apply ({update (1, "LIVE COMPLETE", Terminal::Complete)}); + QCOMPARE (h.all.toPlainText ().count ("LIVE"), 1); + QCOMPARE (h.logs.size (), 2); + QCOMPARE (h.intervals.size (), 2); + auto const trace = h.trace; + auto const original = h.all.toPlainText (); + JttyReceiveLine::refresh (h.all, {true, true}, h.font); + JttyReceiveLine::refresh (h.qso, {true, true}, h.font); + QVERIFY (h.all.toPlainText ().contains ("live complete")); + JttyReceiveLine::refresh (h.all, {}, h.font); + QCOMPARE (h.all.toPlainText (), original); + QCOMPARE (h.trace, trace); + QCOMPARE (h.controller.snrForSelectedWord ("MESSAGE", Pane::All), -7); + } + + void clearedActiveHandlesDoNotResurrectMessages () + { + Harness h; + h.apply ({update (1, "REMOVED")}); + h.all.clear (); + h.qso.clear (); + h.apply ({update (2, "RETAINED"), update (1, "REMOVED COMPLETE", Terminal::Complete)}); + QCOMPARE (h.all.toPlainText (), QString {"1500 -7 RETAINED"}); + QCOMPARE (h.qso.toPlainText (), h.all.toPlainText ()); + QCOMPARE (h.logs.size (), 1); + QVERIFY (h.logs.front ().contains ("REMOVED COMPLETE")); + } + + void replayResetRetiresOnlyReplayActiveRecords () + { + Harness h; + h.apply ({update (1, "LIVE")}); + h.reception.source = Source::Review; + h.reception.displayGroup = 2; + h.apply ({update (1, "REPLAY")}); + QCOMPARE (h.all.toPlainText ().count ("LIVE"), 1); + QCOMPARE (h.all.toPlainText ().count ("REPLAY"), 1); + h.controller.resetReplay (); + h.reception.source = Source::Wav; + h.reception.displayGroup = 3; + h.reception.context.band = "40m"; + h.apply ({update (1, "WAV", Terminal::Complete)}); + QCOMPARE (h.logContexts.front ().band, QString {"40m"}); + QVERIFY (h.all.toPlainText ().contains ("REPLAY")); + QVERIFY (h.all.toPlainText ().contains ("WAV")); + h.reception.source = Source::Live; + h.reception.displayGroup = 1; + h.apply ({update (1, "LIVE COMPLETE", Terminal::Complete)}); + QCOMPARE (h.logContexts.last ().band, QString {"20m"}); + QCOMPARE (h.all.toPlainText ().count ("LIVE"), 1); + QVERIFY (h.all.toPlainText ().contains ("LIVE COMPLETE")); + } + + void snrLookupTracksEveryUpdateAndEvictsOldEntries () + { + Harness h; + h.apply ({update (1, "CQ TOKEN", Terminal::Growing, 1500, -2)}); + h.apply ({update (1, "CQ TOKEN", Terminal::Complete, 1500, -3)}); + h.selection.center = 1700; + h.apply ({update (2, "CQ TOKEN", Terminal::Complete, 1500, -4)}); + QCOMPARE (h.controller.snrForSelectedWord ("TOKEN", Pane::All), -4); + QCOMPARE (h.controller.snrForSelectedWord ("TOKEN", Pane::Qso), -3); + QCOMPARE (h.controller.snrForSelectedWord ("token", Pane::All), -10); + QCOMPARE (h.controller.snrForSelectedWord ("TOK", Pane::All), -10); + h.reception.source = Source::Review; + h.apply ({update (3, "REVIEWTOKEN", Terminal::Complete, 1500, -5)}); + h.controller.resetReplay (); + h.reception.source = Source::Wav; + h.apply ({update (4, "WAVTOKEN", Terminal::Complete, 1500, -6)}); + QCOMPARE (h.controller.snrForSelectedWord ("REVIEWTOKEN", Pane::Qso), -5); + QCOMPARE (h.controller.snrForSelectedWord ("WAVTOKEN", Pane::All), -6); + h.apply ({update (5, "EVICT", Terminal::Complete, 1500, -8)}); + for (int i = 0; i < 499; ++i) + h.apply ({update (6, "FILLER", Terminal::Growing, 1500, i)}); + QCOMPARE (h.controller.snrForSelectedWord ("EVICT", Pane::All), -8); + h.apply ({update (6, "FILLER", Terminal::Complete, 1500, 499)}); + QCOMPARE (h.controller.snrForSelectedWord ("EVICT", Pane::All), -10); + QCOMPARE (h.controller.snrForSelectedWord ("FILLER", Pane::All), 499); + } +}; + +QTEST_MAIN (TestJttyReceiveResults) +#include "test_jtty_receive_results.moc" diff --git a/tests/unit/jtty/test_jtty_recording.cpp b/tests/unit/jtty/test_jtty_recording.cpp new file mode 100644 index 00000000..0e903e3a --- /dev/null +++ b/tests/unit/jtty/test_jtty_recording.cpp @@ -0,0 +1,274 @@ +#include <QtTest> +#include <QTemporaryDir> +#include <QAudioFormat> +#include <QFileInfo> +#include <algorithm> + +#include "Audio/BWFFile.hpp" +#include "JttyRecording.hpp" + +namespace +{ +using Recording = JttyRecording; + +Recording::Settings settings (Recording::SavePolicy policy) +{ + Recording::Settings result; + result.policy = policy; + result.directory = QStringLiteral ("/unused-recording-test-path"); + result.myCall = QStringLiteral ("K1ABC"); + result.myGrid = QStringLiteral ("FN42"); + result.frequency = 14074000; + return result; +} + +QDateTime origin () +{ + return QDateTime {QDate {2026, 9, 11}, QTime {23, 58, 42, 123}, Qt::UTC}; +} + +std::vector<short> audio (qint64 count) +{ + std::vector<short> result (std::size_t (count), 0); + for (qint64 i = 0; i < count; ++i) result[std::size_t (i)] = short (i % 30001); + return result; +} +} + +class TestJttyRecording final : public QObject +{ + Q_OBJECT +private slots: + void overlappingSegmentsRetainExactAudioAndOrigin () + { + std::vector<Recording::Snapshot> saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (17, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (Recording::segmentSamples + 123); + recorder.feed (0, pcm.data (), int (pcm.size ())); + QCOMPARE (saved.size (), std::size_t {1}); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {2}); + QCOMPARE (saved[0]->firstSample, qint64 {0}); + QCOMPARE (saved[0]->endSample (), Recording::segmentSamples); + QCOMPARE (saved[1]->firstSample, Recording::hopSamples); + QCOMPARE (saved[1]->endSample (), qint64 (pcm.size ())); + QVERIFY (saved[0]->id != saved[1]->id); + QVERIFY (saved[0]->fileName != saved[1]->fileName); + for (auto const& segment : saved) { + QCOMPARE (segment->reception, quint64 {17}); + QCOMPARE (segment->firstSampleUtc, origin ().addMSecs (segment->firstSample / 12)); + QVERIFY (std::equal (segment->samples.begin (), segment->samples.end (), + pcm.begin () + segment->firstSample)); + } + QCOMPARE (saved[1]->firstSampleUtc.date (), QDate (2026, 9, 12)); + } + + void partialDecodeQualifiesBothOverlappingSegmentsAfterClosure () + { + std::vector<Recording::Snapshot> saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::Decoded)); + auto const pcm = audio (Recording::segmentSamples + 100); + recorder.feed (0, pcm.data (), int (pcm.size ())); + QVERIFY (saved.empty ()); + recorder.noteDecoded (Recording::segmentSamples - 1000, Recording::segmentSamples + 10); + recorder.advanceDecoderWatermark (Recording::segmentSamples - 1); + QVERIFY (saved.empty ()); + recorder.advanceDecoderWatermark (Recording::segmentSamples); + QCOMPARE (saved.size (), std::size_t {1}); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {2}); + QVERIFY (saved[0]->decoded); + QVERIFY (saved[1]->decoded); + } + + void noiseAndNonoverlappingEvidenceDoNotQualify () + { + int writes = 0; + Recording recorder {nullptr, [&writes] (Recording::Snapshot, Recording::Completion done) { + ++writes; + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::Decoded)); + auto const pcm = audio (1000); + recorder.feed (0, pcm.data (), int (pcm.size ())); + recorder.noteDecoded (1000, 2000); + recorder.noteDecoded (20, 20); + recorder.endReception (); + QCOMPARE (writes, 0); + } + + void savePolicyIsFrozenAndOffIntervalsAreNotJoined () + { + std::vector<Recording::Snapshot> saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (8000); + recorder.feed (0, pcm.data (), 1000); + recorder.updateSavePolicy (Recording::SavePolicy::Off); + QCOMPARE (saved.size (), std::size_t {1}); + QCOMPARE (saved[0]->settings.policy, Recording::SavePolicy::All); + recorder.feed (1000, pcm.data (), 1000); + recorder.updateSavePolicy (Recording::SavePolicy::Decoded); + recorder.feed (2000, pcm.data () + 2000, 6000); + recorder.noteDecoded (5700, 5800); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {2}); + QCOMPARE (QFileInfo {saved[0]->fileName}.fileName (), QStringLiteral ("260911_235842_123.wav")); + QCOMPARE (QFileInfo {saved[1]->fileName}.fileName (), QStringLiteral ("260911_235842_595.wav")); + QCOMPARE (saved[1]->firstSample, Recording::searchStepSamples); + QCOMPARE (saved[1]->samples.size (), std::size_t (8000 - Recording::searchStepSamples)); + QVERIFY (std::equal (saved[1]->samples.begin (), saved[1]->samples.end (), + pcm.begin () + Recording::searchStepSamples)); + QCOMPARE (saved[1]->settings.policy, Recording::SavePolicy::Decoded); + } + + void metadataUpdatesApplyOnlyToNewSegments () + { + std::vector<Recording::Snapshot> saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + auto initial = settings (Recording::SavePolicy::All); + initial.hisCall = QStringLiteral ("K1OLD"); + recorder.beginReception (1, origin (), initial); + auto const pcm = audio (Recording::segmentSamples + 1); + recorder.feed (0, pcm.data (), int (Recording::hopSamples)); + + auto updated = initial; + updated.directory = QStringLiteral ("/updated-recording-test-path"); + updated.hisCall = QStringLiteral ("K1NEW"); + updated.policy = Recording::SavePolicy::Off; + recorder.updateMetadata (updated); + recorder.feed (Recording::hopSamples, pcm.data () + Recording::hopSamples, + int (pcm.size () - Recording::hopSamples)); + recorder.endReception (); + + QCOMPARE (saved.size (), std::size_t {2}); + QCOMPARE (saved[0]->settings.hisCall, QStringLiteral ("K1OLD")); + QCOMPARE (saved[0]->settings.directory, initial.directory); + QCOMPARE (saved[1]->settings.hisCall, QStringLiteral ("K1NEW")); + QCOMPARE (saved[1]->settings.directory, updated.directory); + QCOMPARE (saved[1]->settings.policy, Recording::SavePolicy::All); + } + + void delayedFailureStopsSavingUntilExplicitRearm () + { + std::vector<Recording::Completion> completions; + int errors = 0; + Recording recorder {nullptr, [&completions] (Recording::Snapshot, Recording::Completion done) { + completions.push_back (done); + }}; + recorder.setErrorHandler ([&errors] (QString const&) {++errors;}); + auto const pcm = audio (7000); + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + recorder.feed (0, pcm.data (), 1000); + recorder.endReception (); + QCOMPARE (recorder.snapshotsInFlight (), 1); + completions[0] (QStringLiteral ("disk full")); + QVERIFY (recorder.suspendedAfterError ()); + QCOMPARE (errors, 1); + recorder.beginReception (2, origin (), settings (Recording::SavePolicy::All)); + recorder.feed (0, pcm.data (), 1000); + QCOMPARE (completions.size (), std::size_t {1}); + recorder.updateSavePolicy (Recording::SavePolicy::All); + recorder.feed (1000, pcm.data () + 1000, 6000); + recorder.endReception (); + QCOMPARE (completions.size (), std::size_t {2}); + completions[1] ({}); + QVERIFY (!recorder.suspendedAfterError ()); + } + + void delayedStartPreservesSearchPhaseAcrossInputBlocks () + { + std::vector<Recording::Snapshot> saved; + Recording recorder {nullptr, [&saved] (Recording::Snapshot segment, Recording::Completion done) { + saved.push_back (segment); + done ({}); + }}; + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (8000); + recorder.feed (3456, pcm.data () + 3456, 1000); + recorder.feed (4456, pcm.data () + 4456, 1000); + recorder.feed (5456, pcm.data () + 5456, 2544); + recorder.endReception (); + QCOMPARE (saved.size (), std::size_t {1}); + QCOMPARE (saved[0]->firstSample, Recording::searchStepSamples); + QCOMPARE (saved[0]->endSample (), qint64 {8000}); + QCOMPARE (saved[0]->firstSampleUtc, origin ().addMSecs (Recording::searchStepSamples / 12)); + QVERIFY (std::equal (saved[0]->samples.begin (), saved[0]->samples.end (), + pcm.begin () + Recording::searchStepSamples)); + } + + void slowWriterCannotRetainUnboundedAudio () + { + std::vector<Recording::Completion> completions; + int errors = 0; + Recording recorder {nullptr, [&completions] (Recording::Snapshot, Recording::Completion done) { + completions.push_back (done); + }}; + recorder.setErrorHandler ([&errors] (QString const&) {++errors;}); + auto const pcm = audio (1000); + for (quint64 reception = 1; reception <= 3; ++reception) { + recorder.beginReception (reception, origin (), settings (Recording::SavePolicy::All)); + recorder.feed (0, pcm.data (), 1000); + recorder.endReception (); + } + QCOMPARE (completions.size (), std::size_t {Recording::maximumSnapshots}); + QCOMPARE (recorder.snapshotsInFlight (), Recording::maximumSnapshots); + QVERIFY (recorder.suspendedAfterError ()); + QCOMPARE (errors, 1); + for (auto const& done : completions) done ({}); + QCOMPARE (recorder.snapshotsInFlight (), 0); + } + + void discontinuityRequiresANewReception () + { + int errors = 0; + Recording recorder {nullptr, [] (Recording::Snapshot, Recording::Completion done) {done ({});}}; + recorder.setErrorHandler ([&errors] (QString const&) {++errors;}); + recorder.beginReception (1, origin (), settings (Recording::SavePolicy::All)); + auto const pcm = audio (1000); + recorder.feed (0, pcm.data (), 1000); + recorder.feed (1001, pcm.data (), 1000); + QVERIFY (recorder.suspendedAfterError ()); + QCOMPARE (errors, 1); + } + + void writerPreservesCaptureTimeAndNeverOverwrites () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + Recording::Segment segment; + segment.settings = settings (Recording::SavePolicy::All); + segment.fileName = directory.filePath (QStringLiteral ("260911_235842_test.wav")); + segment.firstSampleUtc = origin (); + segment.samplesSinceMidnight = quint64 (origin ().time ().msecsSinceStartOfDay ()) * 12 + 7; + segment.samples = audio (1000); + QVERIFY2 (Recording::writeSegment (segment).isEmpty (), "initial write failed"); + BWFFile wav {QAudioFormat {}, segment.fileName}; + QVERIFY (wav.open (QIODevice::ReadOnly)); + QCOMPARE (wav.bext_time_reference (), segment.samplesSinceMidnight); + QCOMPARE (wav.bext_origination_date_time (), origin ().addMSecs (-origin ().time ().msec ())); + QCOMPARE (wav.size (), qint64 {2000}); + wav.close (); + segment.samples.resize (10); + QVERIFY (!Recording::writeSegment (segment).isEmpty ()); + QVERIFY (wav.open (QIODevice::ReadOnly)); + QCOMPARE (wav.size (), qint64 {2000}); + } +}; + +QTEST_GUILESS_MAIN (TestJttyRecording) +#include "test_jtty_recording.moc" diff --git a/tests/unit/jtty/test_jtty_source_codec.f90 b/tests/unit/jtty/test_jtty_source_codec.f90 index dead01d8..3d1ee9b0 100644 --- a/tests/unit/jtty/test_jtty_source_codec.f90 +++ b/tests/unit/jtty/test_jtty_source_codec.f90 @@ -1,5 +1,6 @@ program test_jtty_source_codec use jtty_mod + use packjt77_grammar, only: pack77_arrl_section_index implicit none type(jtty_source_atom) :: atom,decoded,atoms(2) character(len=34) :: frame,frames(MAX_FRAMES) @@ -30,6 +31,24 @@ program test_jtty_source_codec '0000000111000000000000000001001001','0000000111100000000000000001001001', & '0000001000000000000000000001001001','0000001000100000000000000001001001'] + ! Section IDs are transmitted on the wire; preserve their assigned names. + character(len=3), parameter :: SECTION_NAMES(86)=[character(len=3) :: & + 'AB','AK','AL','AR','AZ','BC','CO','CT','DE','EB', & + 'EMA','ENY','EPA','EWA','GA','GH','IA','ID','IL','IN', & + 'KS','KY','LA','LAX','NS','MB','MDC','ME','MI','MN', & + 'MO','MS','MT','NC','ND','NE','NFL','NH','NL','NLI', & + 'NM','NNJ','NNY','TER','NTX','NV','OH','OK','ONE','ONN', & + 'ONS','OR','ORG','PAC','PR','QC','RI','SB','SC','SCV', & + 'SD','SDG','SF','SFL','SJV','SK','SNJ','STX','SV','TN', & + 'UT','VA','VI','VT','WCF','WI','WMA','WNY','WPA','WTX', & + 'WV','WWA','WY','DX','PE','NB'] + + if(PACK77_NSEC.ne.size(SECTION_NAMES)) error stop 'Section registry size changed' + do i=1,size(SECTION_NAMES) + if(pack77_arrl_section_index(SECTION_NAMES(i)).ne.i) error stop 'Section wire ID changed' + call expect_render(jtty_class_section_atom(1,'A',i),'1A '//trim(SECTION_NAMES(i))) + enddo + do i=0,5 call expect_vector(jtty_call_atom(i,'K1ABC'),CALL_VECTORS(i)) enddo diff --git a/tests/unit/jtty/test_jtty_spectrum.cpp b/tests/unit/jtty/test_jtty_spectrum.cpp new file mode 100644 index 00000000..e1d1556e --- /dev/null +++ b/tests/unit/jtty/test_jtty_spectrum.cpp @@ -0,0 +1,192 @@ +#include <QtTest> +#include <QCryptographicHash> +#include <cmath> +#include <memory> +#include <vector> + +#include "commons.h" +#include "widgets/JttySpectrum.hpp" + +extern "C" { + void symspec_ (struct dec_data *, int *, int *, int *, bool *, int *, + float *, float *, float *, int *, int *, float *, int *); +} + +namespace { +std::vector<qint16> fixture (int count) +{ + std::vector<qint16> result (count); + quint32 random = 17; + for (int i = 0; i < count; ++i) { + random = 1664525u * random + 1013904223u; + result[i] = 1000 * std::sin (2 * 3.141592653589793 * 1234 * i / 12000) + + int (random >> 24) - 128; + } + return result; +} + +QByteArray fingerprint (JttySpectrumFrame const& frame) +{ + QCryptographicHash hash {QCryptographicHash::Sha256}; + for (auto const * values : {&frame.bins, &frame.cumulative, &frame.linearAverage}) { + hash.addData (reinterpret_cast<char const *> (values->data ()), sizeof (*values)); + } + return hash.result (); +} + +constexpr float spectrumToleranceScale = 5.e-4f; + +float spectrumTolerance (float actual, float expected) +{ + auto const magnitude = std::max ({1.f, std::abs (actual), std::abs (expected)}); + return spectrumToleranceScale * magnitude; +} + +bool spectrumNearlyEqual (float actual, float expected) +{ + return std::abs (actual - expected) <= spectrumTolerance (actual, expected); +} + +QString spectrumMismatch (char const * series, int bin, float actual, float expected) +{ + return QStringLiteral ("%1[%2]: actual=%3 expected=%4 difference=%5 tolerance=%6") + .arg (QString::fromLatin1 (series)).arg (bin) + .arg (actual, 0, 'g', 9).arg (expected, 0, 'g', 9) + .arg (std::abs (actual - expected), 0, 'g', 9) + .arg (spectrumTolerance (actual, expected), 0, 'g', 9); +} +} + +class TestJttySpectrum final : public QObject +{ + Q_OBJECT +private slots: + void agreesWithTimedSpectrumMath_data () + { + QTest::addColumn<bool> ("windowed"); + QTest::newRow ("rectangular") << false; + QTest::newRow ("low-sidelobes") << true; + } + + void agreesWithTimedSpectrumMath () + { + QFETCH (bool, windowed); + auto shared = std::make_unique<dec_data_t> (); + auto const pcm = fixture (24 * JttySpectrum::Hop); + std::copy (pcm.begin (), pcm.end (), shared->d2); + JttySpectrum spectrum; + spectrum.begin (1, 0, 0); + int nsps = 6912; + int gain = 3; + int smoothing = 2; + int symbols = 0; + int eighths = 0; + int percentile = 0; + for (int end = JttySpectrum::Hop; end <= int (pcm.size ()); end += JttySpectrum::Hop) { + std::array<float, NSMAX> bins {}; + float db = 0, peak = 0, width = 0; + symspec_ (shared.get (), &end, &nsps, &gain, &windowed, &smoothing, + &db, bins.data (), &width, &symbols, &eighths, &peak, &percentile); + bool emitted = false; + QVERIFY (spectrum.process (end - JttySpectrum::Hop, pcm.data () + end - JttySpectrum::Hop, + JttySpectrum::Hop, gain, windowed, smoothing, [&] (JttySpectrumFrame const& frame) { + emitted = true; + QCOMPARE (frame.row.endSample, qint64 (end)); + QCOMPARE (frame.row.utcEndMs, qint64 (end / 12)); + QVERIFY (std::abs (frame.powerDb - db) < 0.002f); + QVERIFY (std::abs (frame.maxPowerDb - peak) < 0.002f); + for (int i = 0; i < NSMAX; ++i) { + QVERIFY2 (spectrumNearlyEqual (frame.bins[i], bins[i]), + qPrintable (spectrumMismatch ("bins", i, frame.bins[i], bins[i]))); + QVERIFY2 (spectrumNearlyEqual (frame.cumulative[i], shared->savg[i]), + qPrintable (spectrumMismatch ("cumulative", i, frame.cumulative[i], + shared->savg[i]))); + } + })); + QVERIFY (emitted); + } + } + + void packetizationAndLargeCoordinatesPreserveSpectrum () + { + auto const pcm = fixture (181 * 12000); + qint64 const origin = (qint64 (1) << 33) + 117; + qint64 const utc = 179000; + JttySpectrum whole; + JttySpectrum packets; + whole.begin (7, origin, utc); + packets.begin (7, origin, utc); + QVector<QByteArray> expected; + QVERIFY (whole.process (origin, pcm.data (), int (pcm.size ()), 0, true, 1, + [&] (JttySpectrumFrame const& frame) { expected.append (fingerprint (frame)); })); + int frameIndex = 0; + int offset = 0; + while (offset < int (pcm.size ())) { + int const size = std::min (1 + (offset * 17LL % 4001), qint64 (pcm.size () - offset)); + QVERIFY (packets.process (origin + offset, pcm.data () + offset, size, 0, true, 1, + [&] (JttySpectrumFrame const& frame) { + QCOMPARE (fingerprint (frame), expected.at (frameIndex)); + QCOMPARE (frame.row.reception, quint64 (7)); + QCOMPARE (frame.row.beginSample, origin + qint64 (frameIndex) * JttySpectrum::Hop); + QCOMPARE (frame.row.utcEndMs, utc + qint64 (frameIndex + 1) * JttySpectrum::Hop / 12); + ++frameIndex; + })); + offset += size; + } + QCOMPARE (frameIndex, expected.size ()); + QVERIFY (!packets.process (origin, pcm.data (), 100, 0, true, 1, [] (JttySpectrumFrame const&) {})); + } + + void explicitReceptionResetsTailAndAverage () + { + auto const pcm = fixture (12 * JttySpectrum::Hop); + JttySpectrum reused; + reused.begin (1, 0, 0); + QVERIFY (reused.process (0, pcm.data (), int (pcm.size ()) - 13, 0, true, 1, + [] (JttySpectrumFrame const&) {})); + reused.begin (2, 999, 15000); + JttySpectrum fresh; + fresh.begin (2, 999, 15000); + QVector<QByteArray> expected; + QVERIFY (fresh.process (999, pcm.data (), int (pcm.size ()), 0, true, 1, + [&] (JttySpectrumFrame const& frame) { expected.append (fingerprint (frame)); })); + int index = 0; + QVERIFY (reused.process (999, pcm.data (), int (pcm.size ()), 0, true, 1, + [&] (JttySpectrumFrame const& frame) { QCOMPARE (fingerprint (frame), expected.at (index++)); })); + QCOMPARE (index, expected.size ()); + } + + void averagesFollowNewSignalsAfterLongReception () + { + JttySpectrum spectrum; + spectrum.begin (3, 0, 0); + std::array<qint16, JttySpectrum::Hop> pcm; + JttySpectrumFrame latest; + qint64 nextSample = 0; + auto receiveTone = [&] (int frequency, int frames) { + for (int i = 0; i < int (pcm.size ()); ++i) { + pcm[i] = 1000 * std::sin (2 * 3.141592653589793 * frequency * i / 12000); + } + for (int i = 0; i < frames; ++i) { + QVERIFY (spectrum.process (nextSample, pcm.data (), int (pcm.size ()), 0, true, 0, + [&] (JttySpectrumFrame const& frame) { latest = frame; })); + nextSample += pcm.size (); + } + }; + int const oldBin = int (1500 / JttySpectrumFrame::BinWidth); + int const newBin = int (2250 / JttySpectrumFrame::BinWidth); + receiveTone (1500, 720 * 12000 / JttySpectrum::Hop); + float const oldPower = latest.cumulative[oldBin]; + QVERIFY (oldPower > 0); + receiveTone (2250, 180 * 12000 / JttySpectrum::Hop); + QVERIFY (latest.cumulative[oldBin] < 0.5f * oldPower); + QVERIFY (latest.cumulative[newBin] > 1.5f * latest.cumulative[oldBin]); + QVERIFY (latest.linearAverage[newBin] > latest.linearAverage[oldBin]); + QCOMPARE (latest.row.reception, quint64 (3)); + QCOMPARE (latest.row.endSample, nextSample); + QCOMPARE (latest.row.utcEndMs, nextSample / 12); + } +}; + +QTEST_APPLESS_MAIN (TestJttySpectrum) +#include "test_jtty_spectrum.moc" diff --git a/tests/unit/jtty/test_jtty_structured_decode.f90 b/tests/unit/jtty/test_jtty_structured_decode.f90 index e74b9c2a..6a55a816 100644 --- a/tests/unit/jtty/test_jtty_structured_decode.f90 +++ b/tests/unit/jtty/test_jtty_structured_decode.f90 @@ -1,9 +1,10 @@ program test_jtty_structured_decode use iso_c_binding, only: c_int,c_char,c_null_char,c_sizeof - use iso_fortran_env, only: int16,int32 + use iso_fortran_env, only: int16,int32,real32 use jtty_fec, only: is13,PAYLOAD_BITS,TOTAL_K,tbcc_encode use jtty_tbcc_code_profiles + use jtty_tbcc_decoder, only: jtty_tbcc_decode use jtty_mdec, only: npending,pending_updates,nactive,discard_pending_updates,display_message_text use jtty_mod, only: jtty_source_atom,jtty_source_atom_c,jtty_call_atom, & jtty_exch_num_atom,unpack_jtty,MAX_FRAMES,JTTY_CALL_CALL,JTTY_ROLE_FULL, & @@ -25,11 +26,10 @@ program test_jtty_structured_decode integer(c_int), intent(out) :: tones(*),nsym integer(c_int) :: status end function jtty_cpp_n1mm_smoke - function jtty_cpp_cq_smoke(tones,nsym,text,chained) result(status) bind(C) + function jtty_cpp_cq_smoke(tones,nsym,text) result(status) bind(C) import :: c_int,c_char integer(c_int), intent(out) :: tones(*),nsym character(kind=c_char), intent(out) :: text(*) - integer(c_int), value :: chained integer(c_int) :: status end function jtty_cpp_cq_smoke function jtty_cpp_rtty_smoke(tones,nsym) result(status) bind(C) @@ -59,6 +59,7 @@ program test_jtty_structured_decode call decode_native_call_and_serial(failures) call decode_c_adapter_atoms(failures) call reject_invalid_c_descriptors(failures) + call reject_invalid_c_batch(failures) call decode_cpp_compiled_n1mm(failures) call decode_compact_text(failures) call decode_profile_text(failures) @@ -79,13 +80,7 @@ contains call expect(status.eq.JTTY_ENCODE_OK .and. nsymbols.eq.frame_symbols, & 'C++ RTTY profile text matches native F8 while unknown text uses two frames',count) if(status.ne.JTTY_ENCODE_OK .or. nsymbols.ne.frame_symbols) return - call decode_waveform(tones,int(nsymbols)) - call expect(npending.eq.1,'RTTY serial text produces one update',count) - if(npending.eq.1) then - call expect(trim(normalized(pending_updates(1)%decoded)).eq.'599 123' .and. & - pending_updates(1)%complete .and. nactive.eq.0, & - 'RTTY serial text uses canonical rendering and completes',count) - endif + call expect_noiseless_message(tones,int(nsymbols),'599 123','RTTY serial text',count) end subroutine decode_profile_text subroutine decode_compact_text(count) @@ -93,29 +88,21 @@ contains integer(c_int) :: native_tones(MAX_FRAMES*frame_symbols),native_nsymbols,status character(kind=c_char) :: c_text(80) character(len=80) :: text - integer :: tones(MAX_FRAMES*frame_symbols),nsymbols,chained,i - - do chained=0,1 - status=jtty_cpp_cq_smoke(native_tones,native_nsymbols,c_text,int(chained,c_int)) - call expect(status.eq.JTTY_ENCODE_OK .and. native_nsymbols.eq.frame_symbols, & - 'native F1 generates one frame',count) - if(status.ne.JTTY_ENCODE_OK .or. native_nsymbols.ne.frame_symbols) return - do i=1,len(text) - text(i:i)=c_text(i) - enddo - call genjtty(text,tones,nsymbols) - call expect(nsymbols.eq.native_nsymbols,'GUI CQ text generates one frame',count) - if(nsymbols.ne.native_nsymbols) return - call expect(all(tones(1:nsymbols).eq.native_tones(1:nsymbols)), & - 'GUI CQ text and native F1 generate identical channel symbols',count) + integer :: tones(MAX_FRAMES*frame_symbols),nsymbols,i + + status=jtty_cpp_cq_smoke(native_tones,native_nsymbols,c_text) + call expect(status.eq.JTTY_ENCODE_OK .and. native_nsymbols.eq.frame_symbols, & + 'native F1 generates one frame',count) + if(status.ne.JTTY_ENCODE_OK .or. native_nsymbols.ne.frame_symbols) return + do i=1,len(text) + text(i:i)=c_text(i) enddo - call decode_waveform(tones,nsymbols) - call expect(npending.eq.1,'compact CQ produces one update',count) - if(npending.eq.1) then - call expect(trim(normalized(pending_updates(1)%decoded)).eq.'CQ K1ABC CQ' .and. & - pending_updates(1)%complete .and. nactive.eq.0, & - 'compact CQ preserves text and completes',count) - endif + call genjtty(text,tones,nsymbols) + call expect(nsymbols.eq.native_nsymbols,'GUI CQ text generates one frame',count) + if(nsymbols.ne.native_nsymbols) return + call expect(all(tones(1:nsymbols).eq.native_tones(1:nsymbols)), & + 'GUI CQ text and native F1 generate identical channel symbols',count) + call expect_noiseless_message(native_tones,int(native_nsymbols),'CQ K1ABC CQ','compact CQ',count) text='TEST WB9XYZ 599 123 QSL TU' call genjtty(text,tones,nsymbols) @@ -159,20 +146,12 @@ contains 'native call plus serial generates two frames',count) if(nsymbols.le.0) return - call decode_waveform(tones,nsymbols) - - call expect(npending.eq.1, & - 'native call plus serial produces one update',count) - if(npending.ne.1) return - call expect(trim(normalized(pending_updates(1)%decoded)).eq.'WB9XYZ 599 1234', & - 'merged native atoms use canonical call and serial rendering',count) - call expect(pending_updates(1)%complete .and. nactive.eq.0, & - 'final native atom completes and releases the message',count) + call expect_noiseless_message(tones,nsymbols,'WB9XYZ 599 1234','native call plus serial',count) end subroutine decode_native_call_and_serial subroutine decode_c_adapter_atoms(count) integer, intent(inout) :: count - type(jtty_source_atom_c) :: atoms(6) + type(jtty_source_atom_c) :: atoms(7) integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols,status call expect(c_sizeof(atoms(1)).eq.20,'C atom descriptor remains 20 bytes',count) @@ -183,27 +162,25 @@ contains JTTY_ROLE_FULL,0,'CA') call initialize_c_atom(atoms(4),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION, & 3,1,'EMA') - call initialize_c_atom(atoms(5),JTTY_ATOM_GRID4,0,JTTY_ROLE_FIELD_ONLY,0,'FN42') - call initialize_c_atom(atoms(6),JTTY_ATOM_CONTROL,JTTY_CONTROL_QSL_TU,0,0,'') + call initialize_c_atom(atoms(5),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,10,'CT') + atoms(5)%text(3)=' ' + call initialize_c_atom(atoms(6),JTTY_ATOM_GRID4,0,JTTY_ROLE_FIELD_ONLY,0,'FN42') + call initialize_c_atom(atoms(7),JTTY_ATOM_CONTROL,JTTY_CONTROL_QSL_TU,0,0,'') call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) call expect(nsymbols.eq.size(atoms)*frame_symbols, & 'C adapter generates serial/state/FD/grid/control frames',count) call expect(status.eq.JTTY_ENCODE_OK,'C adapter reports successful encoding',count) if(nsymbols.le.0) return - call decode_waveform(tones,int(nsymbols)) - call expect(npending.eq.1,'C adapter atoms produce one update',count) - if(npending.ne.1) return - call expect(trim(normalized(pending_updates(1)%decoded)).eq. & - 'K1ABC 599 012 599 CA 1D EMA FN42 QSL TU', & - 'C adapter atoms retain canonical structured rendering',count) - call expect(pending_updates(1)%complete .and. nactive.eq.0, & - 'final C adapter atom completes and releases the message',count) + call expect_noiseless_message(tones,int(nsymbols), & + 'K1ABC 599 012 599 CA 1D EMA 10A CT FN42 QSL TU','C adapter atoms',count) end subroutine decode_c_adapter_atoms subroutine reject_invalid_c_descriptors(count) integer, intent(inout) :: count type(jtty_source_atom_c) :: atom(1) + character(len=4), parameter :: invalid_sections(*)=['ZZZ ','EMAX','CT X'] + integer :: i integer(c_int) :: tones(frame_symbols),nsymbols,status call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_LOC,JTTY_LOC_STATE_PROVINCE,1,0,'CA') @@ -218,11 +195,13 @@ contains call genjtty_atoms_c(atom,1,tones,nsymbols,status) call expect(nsymbols.eq.0,'C adapter rejects unterminated text',count) - call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,'ZZZ') - call genjtty_atoms_c(atom,1,tones,nsymbols,status) - call expect(nsymbols.eq.0,'C adapter rejects unknown Field Day section',count) - call expect(status.eq.JTTY_ENCODE_UNKNOWN_SECTION, & - 'C adapter identifies unknown Field Day section',count) + do i=1,size(invalid_sections) + call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,invalid_sections(i)) + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects unknown Field Day section '//trim(invalid_sections(i)),count) + call expect(status.eq.JTTY_ENCODE_UNKNOWN_SECTION, & + 'C adapter identifies unknown Field Day section '//trim(invalid_sections(i)),count) + enddo call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,0,0,1,'EMA') call genjtty_atoms_c(atom,1,tones,nsymbols,status) @@ -237,6 +216,29 @@ contains call expect(nsymbols.eq.0,'C adapter rejects unassigned control phrase',count) end subroutine reject_invalid_c_descriptors + subroutine reject_invalid_c_batch(count) + integer, intent(inout) :: count + type(jtty_source_atom_c) :: atoms(3) + integer(c_int) :: tones(3*frame_symbols),nsymbols,status + + call initialize_c_atom(atoms(1),JTTY_ATOM_CALL,JTTY_CALL_CALL,0,0,'K1ABC') + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,'EMAX') + call initialize_c_atom(atoms(3),JTTY_ATOM_CONTROL,JTTY_CONTROL_QSL_TU,0,0,'') + call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) + call expect(nsymbols.eq.0 .and. status.eq.JTTY_ENCODE_UNKNOWN_SECTION, & + 'invalid section rejects the whole descriptor batch',count) + + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_NUM,JTTY_NUM_SERIAL,JTTY_ROLE_FULL,131072,'') + call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) + call expect(nsymbols.eq.0 .and. status.eq.JTTY_ENCODE_INVALID_DESCRIPTOR, & + 'invalid source atom rejects the whole descriptor batch',count) + + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,'EMA') + call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) + call expect(nsymbols.eq.size(atoms)*frame_symbols .and. status.eq.JTTY_ENCODE_OK, & + 'valid descriptor batch encodes after a rejected batch',count) + end subroutine reject_invalid_c_batch + subroutine initialize_c_atom(atom,kind,subtype,role,value,text) type(jtty_source_atom_c), intent(out) :: atom integer, intent(in) :: kind,subtype,role,value @@ -280,6 +282,45 @@ contains 'CRC/FEC-valid source-invalid frame creates no message or update',count) end subroutine reject_reserved_struct_family + subroutine expect_noiseless_message(tones,nsymbols,expected,description,count) + integer, intent(in) :: tones(:),nsymbols + character(len=*), intent(in) :: expected,description + integer, intent(inout) :: count + complex(real32) :: correlations(0:3,TOTAL_K),halves(0:3,TOTAL_K) + integer(int32) :: payload(PAYLOAD_BITS) + character(len=34) :: frames(MAX_FRAMES) + character(len=80) :: decoded + integer :: iframe,nframes,offset,symbol + logical :: success,source_valid,is_last_frame + + nframes=nsymbols/frame_symbols + call expect(nframes.ge.1 .and. nframes.le.MAX_FRAMES .and. & + nsymbols.eq.nframes*frame_symbols,description//': complete channel frames',count) + if(nframes.lt.1 .or. nframes.gt.MAX_FRAMES .or. nsymbols.ne.nframes*frame_symbols) return + frames='' + halves=cmplx(0.0_real32,0.0_real32,real32) + do iframe=1,nframes + offset=(iframe-1)*frame_symbols + call expect(all(tones(offset+1:offset+size(is13)).eq.is13),description//': sync symbols',count) + offset=offset+size(is13) + call expect(all(tones(offset+1:offset+TOTAL_K).ge.0) .and. & + all(tones(offset+1:offset+TOTAL_K).le.3),description//': payload tones',count) + if(any(tones(offset+1:offset+TOTAL_K).lt.0) .or. any(tones(offset+1:offset+TOTAL_K).gt.3)) return + correlations=cmplx(0.0_real32,0.0_real32,real32) + do symbol=1,TOTAL_K + correlations(tones(offset+symbol),symbol)=cmplx(100.0_real32,0.0_real32,real32) + enddo + call jtty_tbcc_decode(correlations,halves,payload,success) + call expect(success,description//': TBCC payload recovery',count) + if(.not.success) return + write(frames(iframe),'(34i1)') payload + call unpack_jtty(frames,iframe,decoded,is_last_frame=is_last_frame,source_valid=source_valid) + call expect(source_valid,description//': source-valid prefix',count) + call expect(is_last_frame.eqv.(iframe.eq.nframes),description//': final-frame marker',count) + enddo + call expect(trim(normalized(decoded)).eq.expected,description//': canonical text and ordering',count) + end subroutine expect_noiseless_message + subroutine decode_waveform(tones,nsymbols,channel_width) integer, intent(in) :: tones(:),nsymbols real, intent(in), optional :: channel_width diff --git a/tests/unit/jtty/test_jtty_tbcc_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 index 50fb6f63..09d5f032 100644 --- a/tests/unit/jtty/test_jtty_tbcc_decoder.f90 +++ b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 @@ -32,6 +32,7 @@ program test_jtty_tbcc_decoder 'rank-one payload unexpectedly evaluated half-symbol fallback') call require(result%exported_candidate_count <= 4_int32, & 'coherence ladder exposed more than four hypotheses per rung') + call expect_decode_symmetry() payload(33) = 1_int32 call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) @@ -41,6 +42,7 @@ program test_jtty_tbcc_decoder call require(.not.success, 'coherence ladder accepted reserved bit one') call require(all(decoded == 0_int32), & 'reserved-bit rejection left a stale payload') + call expect_failure_result() halves = correlations correlations = cmplx(0.0_real32, 0.0_real32, real32) @@ -49,6 +51,7 @@ program test_jtty_tbcc_decoder call require(.not.success, 'half-symbol fallback accepted reserved bit one') call require(all(decoded == 0_int32), & 'half-symbol reserved-bit rejection left a stale payload') + call expect_failure_result() payload(33) = 0_int32 call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) @@ -68,16 +71,14 @@ program test_jtty_tbcc_decoder call jtty_tbcc_decode(correlations, halves, decoded, success, result) call require(.not.success, 'coherence ladder accepted the all-zero payload') call require(all(decoded == 0_int32), 'failed ladder decode left stale payload') - call require(result%evaluated_rung_count == 4_int32, & - 'failed decode did not report all evaluated rungs') + call expect_failure_result() correlations = cmplx(0.0_real32, 0.0_real32, real32) decoded = huge(0_int32) call jtty_tbcc_decode(correlations, halves, decoded, success, result) call require(.not.success, 'coherence ladder accepted flat correlations') call require(all(decoded == 0_int32), 'flat-correlation decode left stale payload') - call require(result%evaluated_rung_count == 4_int32, & - 'flat-correlation decode did not report all evaluated rungs') + call expect_failure_result() call expect_coherent_decodes() @@ -85,6 +86,54 @@ program test_jtty_tbcc_decoder contains + subroutine expect_decode_symmetry() + complex(real32) :: transformed(0:3, TOTAL_K) + integer(int32) :: transformed_payload(PAYLOAD_BITS) + type(jtty_tbcc_decode_result) :: baseline, transformed_result + logical :: transformed_success + + baseline = result + transformed = -correlations + call jtty_tbcc_decode(transformed, halves, transformed_payload, transformed_success, transformed_result) + call require(transformed_success .and. all(transformed_payload == payload), & + 'negated correlations changed the decode outcome') + call require(transformed_result%accepted_hypothesis_rank == baseline%accepted_hypothesis_rank .and. & + transformed_result%accepted_identity == baseline%accepted_identity .and. & + transformed_result%exported_candidate_count == baseline%exported_candidate_count .and. & + transformed_result%circular_candidate_count == baseline%circular_candidate_count .and. & + transformed_result%coherent_block_length == baseline%coherent_block_length .and. & + transformed_result%evaluated_rung_count == baseline%evaluated_rung_count, & + 'negated correlations changed the accepted hypothesis') + + transformed = 2.0_real32*correlations + call jtty_tbcc_decode(transformed, halves, transformed_payload, transformed_success, transformed_result) + call require(transformed_success .and. all(transformed_payload == payload), & + 'doubled correlations changed the decode outcome') + call require(transformed_result%accepted_hypothesis_rank == baseline%accepted_hypothesis_rank .and. & + transformed_result%accepted_identity == baseline%accepted_identity .and. & + transformed_result%exported_candidate_count == baseline%exported_candidate_count .and. & + transformed_result%circular_candidate_count == baseline%circular_candidate_count .and. & + transformed_result%coherent_block_length == baseline%coherent_block_length .and. & + transformed_result%evaluated_rung_count == baseline%evaluated_rung_count, & + 'doubled correlations changed the accepted hypothesis') + end subroutine expect_decode_symmetry + + subroutine expect_failure_result() + type(jtty_tbcc_decode_result) :: empty + + empty = jtty_tbcc_decode_result() + call require(result%accepted_hypothesis_rank == empty%accepted_hypothesis_rank .and. & + result%exported_candidate_count == empty%exported_candidate_count .and. & + result%circular_candidate_count == empty%circular_candidate_count .and. & + result%coherent_block_length == empty%coherent_block_length .and. & + result%accepted_identity == empty%accepted_identity .and. & + result%accepted_metric == empty%accepted_metric .and. & + (result%used_half_symbol_observation .eqv. empty%used_half_symbol_observation), & + 'failed decode left stale result metadata') + call require(result%evaluated_rung_count == 4_int32, & + 'failed decode did not report all evaluated rungs') + end subroutine expect_failure_result + subroutine expect_coherent_decodes() ! Seed 6 verifies that reserved-bit pruning retains the valid L1 path. integer(int32), parameter :: seeds(2) = [2,6], lengths(2) = [2,1], & diff --git a/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 index d8b4eed7..545e0221 100644 --- a/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 +++ b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 @@ -9,7 +9,10 @@ program test_jtty_tbcc_list_decoder call expect_optimized_reference_parity() call expect_noiseless_tailbiting_decode() call expect_reserved_bit_pruning() + call expect_candidate_contract() + call expect_workspace_isolation() call expect_deterministic_hypothesis_budget() + call expect_score_symmetry() call expect_coherent_normalization() print *, 'test_jtty_tbcc_list_decoder: all checks passed' @@ -24,14 +27,7 @@ contains complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) integer(int32) :: coherent_index, width_index, symbol, tone, wraps - do symbol = 1, JTTY_TBCC_INFORMATION_BITS - do tone = 0, 3 - correlations(tone, symbol) = cmplx( & - real(modulo(17*tone + 11*symbol, 29) - 14, real32)/8.0_real32, & - real(modulo(7*tone + 19*symbol, 31) - 15, real32)/9.0_real32, & - real32) - end do - end do + call make_pattern_correlations(correlations) do wraps = 1, 2 do coherent_index = 1, size(coherent_lengths) @@ -189,6 +185,80 @@ contains end if end subroutine expect_reserved_bit_pruning + subroutine expect_candidate_contract() + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bits(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states(JTTY_TBCC_MAX_HYPOTHESES), count, pool, rank, earlier + integer(int32) :: encoded(2, JTTY_TBCC_INFORMATION_BITS) + integer(int64) :: ids(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean(JTTY_TBCC_MAX_HYPOTHESES), paths(JTTY_TBCC_MAX_HYPOTHESES), rescored + logical :: crc(JTTY_TBCC_MAX_HYPOTHESES), closed, expected_crc + + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits, ids, clean, paths, states, crc, count, pool, prune_reserved_zero=.true.) + if (count /= JTTY_TBCC_MAX_HYPOTHESES .or. pool < count) & + error stop 'TBCC candidate contract fixture did not export four candidates' + + do rank = 1, count + if (any(bits(:, rank) < 0_int32) .or. any(bits(:, rank) > 1_int32)) & + error stop 'TBCC candidate contains a nonbinary bit' + if (bits(JTTY_TBCC_RESERVED_BIT, rank) /= 0_int32) & + error stop 'TBCC candidate retained a reserved bit' + if (ids(rank) /= jtty_tbcc_candidate_identity(bits(:, rank))) & + error stop 'TBCC candidate identity disagrees with its bits' + if (states(rank) /= jtty_tbcc_tailbiting_state(JTTY_TBCC_PROFILE_1167_1545_80F, bits(:, rank))) & + error stop 'TBCC candidate start state disagrees with its bits' + call encode_crc12(bits(1:34, rank), encoded, JTTY_TBCC_PROFILE_1167_1545_80F) + expected_crc = all(encoded(1, :) == bits(:, rank)) + if (crc(rank) .neqv. expected_crc) error stop 'TBCC candidate CRC status disagrees with encoding' + call jtty_tbcc_score_candidate(JTTY_TBCC_PROFILE_1167_1545_80F, correlations, & + 2_int32, bits(:, rank), rescored, closed) + if (.not.closed .or. .not.real_arrays_agree([rescored], [clean(rank)])) & + error stop 'TBCC candidate clean score or closure disagrees with rescore' + do earlier = 1, rank - 1 + if (ids(rank) == ids(earlier)) error stop 'TBCC candidate identity is duplicated' + end do + if (rank == 1) cycle + if (clean(rank) > clean(rank - 1)) error stop 'TBCC candidate clean scores are not descending' + if (clean(rank) == clean(rank - 1) .and. ids(rank) < ids(rank - 1)) & + error stop 'TBCC tied candidate identities are not ascending' + end do + end subroutine expect_candidate_contract + + subroutine expect_workspace_isolation() + type(jtty_tbcc_decoder_plan) :: plan + type(jtty_tbcc_decoder_workspace) :: workspace + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bits_a(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: bits_b(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states_a(JTTY_TBCC_MAX_HYPOTHESES), states_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: count_a, count_b, pool_a, pool_b + integer(int64) :: ids_a(JTTY_TBCC_MAX_HYPOTHESES), ids_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean_a(JTTY_TBCC_MAX_HYPOTHESES), clean_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: paths_a(JTTY_TBCC_MAX_HYPOTHESES), paths_b(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_a(JTTY_TBCC_MAX_HYPOTHESES), crc_b(JTTY_TBCC_MAX_HYPOTHESES) + + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + bits_a, ids_a, clean_a, paths_a, states_a, crc_a, count_a, pool_a, prune_reserved_zero=.true.) + correlations = cmplx(0.0_real32, 0.0_real32, real32) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.false.) + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.true.) + if (count_a /= count_b .or. pool_a /= pool_b .or. any(bits_a /= bits_b) .or. & + any(ids_a /= ids_b) .or. any(states_a /= states_b) .or. & + .not.real_arrays_agree(clean_a, clean_b) .or. & + .not.real_arrays_agree(paths_a, paths_b) .or. any(crc_a .neqv. crc_b)) & + error stop 'TBCC workspace retained state across A-B-A decodes' + end subroutine expect_workspace_isolation + subroutine expect_deterministic_hypothesis_budget() type(jtty_tbcc_code_profile) :: code complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) @@ -233,8 +303,61 @@ contains one_count, one_pool, prune_reserved_zero=.true.) if (one_count /= 1_int32 .or. one_id(1) /= ids_a(1) .or. one_pool /= pool_a) & error stop 'TBCC list decoder did not enforce the H1 budget' + + ! The nonzero pool must exceed H4 so this checks the admission boundary. + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava(correlations, code, 2_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, bits_a, ids_a, clean_a, path_a, states_a, & + crc_a, count_a, pool_a, prune_reserved_zero=.true.) + call jtty_tbcc_list_wava(correlations, code, 2_int32, 4_int32, 2_int32, & + 1_int32, one_bit, one_id, one_clean, one_path, one_state, one_crc, & + one_count, one_pool, prune_reserved_zero=.true.) + if (count_a /= JTTY_TBCC_MAX_HYPOTHESES .or. pool_a <= count_a .or. & + one_count /= 1_int32 .or. one_pool /= pool_a) & + error stop 'TBCC nonzero H1/H4 fixture did not cross the hypothesis boundary' + if (any(one_bit(:, 1) /= bits_a(:, 1)) .or. one_id(1) /= ids_a(1) .or. & + one_state(1) /= states_a(1) .or. one_crc(1) .neqv. crc_a(1) .or. & + .not.real_arrays_agree(one_clean, clean_a(1:1)) .or. & + .not.real_arrays_agree(one_path, path_a(1:1))) & + error stop 'TBCC nonzero H1 differs from the first H4 candidate' end subroutine expect_deterministic_hypothesis_budget + subroutine expect_score_symmetry() + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bits_a(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: bits_b(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states_a(JTTY_TBCC_MAX_HYPOTHESES), states_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: count_a, count_b, pool_a, pool_b + integer(int64) :: ids_a(JTTY_TBCC_MAX_HYPOTHESES), ids_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean_a(JTTY_TBCC_MAX_HYPOTHESES), clean_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: paths_a(JTTY_TBCC_MAX_HYPOTHESES), paths_b(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_a(JTTY_TBCC_MAX_HYPOTHESES), crc_b(JTTY_TBCC_MAX_HYPOTHESES) + + call make_pattern_correlations(correlations) + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits_a, ids_a, clean_a, paths_a, states_a, crc_a, count_a, pool_a, prune_reserved_zero=.true.) + if (count_a /= JTTY_TBCC_MAX_HYPOTHESES) error stop 'TBCC symmetry fixture lacks four candidates' + if (any(clean_a(1:count_a-1) - clean_a(2:count_a) <= 1.0e-6_real64)) & + error stop 'TBCC symmetry fixture has near-tied clean scores' + correlations = -correlations + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.true.) + if (count_b /= count_a .or. pool_b /= pool_a .or. any(bits_b /= bits_a) .or. & + any(ids_b /= ids_a) .or. any(states_b /= states_a) .or. any(crc_b .neqv. crc_a) .or. & + .not.real_arrays_agree(clean_b, clean_a)) & + error stop 'TBCC candidate order or score changed under negation' + correlations = 2.0_real32*correlations + call jtty_tbcc_list_wava(correlations, JTTY_TBCC_PROFILE_1167_1545_80F, & + 2_int32, 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES, & + bits_b, ids_b, clean_b, paths_b, states_b, crc_b, count_b, pool_b, prune_reserved_zero=.true.) + if (count_b /= count_a .or. pool_b /= pool_a .or. any(bits_b /= bits_a) .or. & + any(ids_b /= ids_a) .or. any(states_b /= states_a) .or. any(crc_b .neqv. crc_a) .or. & + .not.real_arrays_agree(clean_b, 4.0_real64*clean_a)) & + error stop 'TBCC candidate order or score changed under amplitude doubling' + end subroutine expect_score_symmetry + subroutine expect_coherent_normalization() complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) integer(int32) :: tones4(4), tones2(2) @@ -282,6 +405,19 @@ contains end do end subroutine make_noiseless_correlations + subroutine make_pattern_correlations(correlations) + complex(real32), intent(out) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: symbol, tone + + do symbol = 1, JTTY_TBCC_INFORMATION_BITS + do tone = 0, 3 + correlations(tone, symbol) = cmplx( & + real(modulo(17*tone + 11*symbol, 29) - 14, real32)/8.0_real32, & + real(modulo(7*tone + 19*symbol, 31) - 15, real32)/9.0_real32, real32) + end do + end do + end subroutine make_pattern_correlations + pure logical function real_arrays_agree(left, right) result(agree) real(real64), intent(in) :: left(:), right(:) integer(int32) :: element diff --git a/tests/unit/jtty/test_jtty_transmit_queue.cpp b/tests/unit/jtty/test_jtty_transmit_queue.cpp new file mode 100644 index 00000000..d9b734a6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_transmit_queue.cpp @@ -0,0 +1,107 @@ +#include <QtTest> + +#include "widgets/JttyTransmitQueue.hpp" + +class TestJttyTransmitQueue final + : public QObject +{ + Q_OBJECT + + static Jtty::TransmitSegment segment (QString const& text, int toneCount = 2) + { + return {text, QVector<int> (toneCount, 1), 0}; + } + +private slots: + void fifoPreservesFullSegmentsAndLaterRequests () + { + Jtty::TransmitQueue queue; + auto const full = QString (79, 'A') + 'Z'; + queue.append (11, {segment (full), segment ("TAIL")}); + QCOMPARE (queue.nextRequestId (), qint64 {11}); + QCOMPARE (queue.nextSegment ()->text, full); + QVERIFY (queue.commitNext (3072)); + + queue.append (12, {segment ("NEW MESSAGE")}); + QCOMPARE (queue.nextRequestId (), qint64 {11}); + QCOMPARE (queue.nextSegment ()->text, QString {"TAIL"}); + QVERIFY (!queue.commitNext (6144)); + QCOMPARE (queue.nextRequestId (), qint64 {12}); + QCOMPARE (queue.nextSegment ()->text, QString {"NEW MESSAGE"}); + QVERIFY (queue.commitNext (9216)); + QVERIFY (!queue.hasUncommitted ()); + QVERIFY (!queue.nextSegment ()); + QCOMPARE (queue.nextRequestId (), qint64 {0}); + QCOMPARE (queue.requests ().at (0).segments.at (0).text, full); + } + + void progressDoesNotCompleteRequests () + { + Jtty::TransmitQueue queue; + queue.append (21, {segment ("FIRST"), segment ("LAST", 3)}); + QCOMPARE (queue.segmentCount (), 2); + QCOMPARE (queue.nextSegment ()->sampleCount (), qint64 {3072}); + QCOMPARE (queue.remainingSegments (0), 2); + QCOMPARE (queue.pendingText (0), QString {"FIRST\nLAST"}); + queue.commitNext (3072); + QCOMPARE (queue.remainingSegments (3071), 2); + QCOMPARE (queue.remainingSegments (3072), 1); + QCOMPARE (queue.pendingText (3072), QString {"LAST"}); + QVERIFY (queue.complete (3072).isEmpty ()); + QCOMPARE (queue.nextSegment ()->sampleCount (), qint64 {4608}); + queue.commitNext (7680); + QCOMPARE (queue.remainingSegments (7680), 0); + QVERIFY (queue.pendingText (7680).isEmpty ()); + QVERIFY (!queue.empty ()); + QCOMPARE (queue.segmentCount (), 2); + QVERIFY (queue.complete (7679).isEmpty ()); + QCOMPARE (queue.complete (7680), QVector<qint64> {21}); + QVERIFY (queue.empty ()); + QVERIFY (queue.complete (7680).isEmpty ()); + } + + void drainCompletesOnlyCommittedPrefix () + { + Jtty::TransmitQueue queue; + queue.append (31, {segment ("FIRST")}); + queue.append (32, {segment ("SECOND"), segment ("THIRD")}); + queue.append (33, {segment ("FOURTH")}); + queue.commitNext (3072); + queue.commitNext (6144); + QCOMPARE (queue.complete (6144), QVector<qint64> {31}); + QCOMPARE (queue.requests ().size (), 2); + QCOMPARE (queue.nextSegment ()->text, QString {"THIRD"}); + queue.commitNext (9216); + queue.commitNext (12288); + QCOMPARE (queue.complete (9216), QVector<qint64> {32}); + QCOMPARE (queue.complete (12288), QVector<qint64> {33}); + QVERIFY (queue.empty ()); + } + + void cancellationReportsAcceptedAndUnsubmittedOnce () + { + Jtty::TransmitQueue queue; + queue.append (41, {segment ("ACCEPTED")}); + queue.append (42, {segment ("PENDING"), segment ("UNSUBMITTED")}); + queue.append (43, {segment ("LATER")}); + queue.commitNext (3072); + queue.commitNext (6144); + auto const cancelled = queue.cancel (); + QCOMPARE (cancelled, (QVector<qint64> {41, 42, 43})); + QVERIFY (queue.empty ()); + QVERIFY (!queue.hasUncommitted ()); + QCOMPARE (queue.segmentCount (), 0); + QCOMPARE (queue.remainingSegments (0), 0); + QVERIFY (queue.pendingText (0).isEmpty ()); + QVERIFY (queue.cancel ().isEmpty ()); + QVERIFY (queue.complete (6144).isEmpty ()); + queue.append (44, {segment ("FRESH")}); + QCOMPARE (queue.nextSegment ()->text, QString {"FRESH"}); + QVERIFY (queue.commitNext (3072)); + QCOMPARE (queue.complete (3072), QVector<qint64> {44}); + } +}; + +QTEST_GUILESS_MAIN (TestJttyTransmitQueue) + +#include "test_jtty_transmit_queue.moc" diff --git a/tests/unit/jtty/test_jtty_tx_lifecycle.cpp b/tests/unit/jtty/test_jtty_tx_lifecycle.cpp new file mode 100644 index 00000000..d133f9f6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tx_lifecycle.cpp @@ -0,0 +1,186 @@ +#include <chrono> + +#include <QtTest> + +#include "widgets/JttyTxLifecycle.hpp" + +class TestJttyTxLifecycle final : public QObject +{ + Q_OBJECT + +private slots: + void pendingSessionRetainsBackendIdentity () + { + JttyTxLifecycle lifecycle; + auto const epoch = TxAudioQueueEpoch {7}; + + QVERIFY (lifecycle.begin (JttyTxLifecycle::Backend::Tci, epoch)); + QVERIFY (lifecycle.addPending (101, 201)); + + QCOMPARE (lifecycle.phase (), JttyTxLifecycle::Phase::AwaitingEnqueue); + QCOMPARE (lifecycle.backend (), JttyTxLifecycle::Backend::Tci); + QCOMPARE (lifecycle.epoch (), epoch); + QCOMPARE (lifecycle.pending ().size (), std::size_t {1}); + QCOMPARE (lifecycle.pending ().front ().request_id, 201); + } + + void stopSnapshotIsImmutable () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Local); + QVERIFY (epoch.isValid ()); + QVERIFY (lifecycle.addPending (1, 2)); + TxAudioQueueProgress progress; + progress.epoch = epoch; + progress.queued_samples = 3600; + progress.served_samples = 1200; + progress.total_samples = 4800; + auto const accepted = lifecycle.accept (epoch, 1, progress); + QVERIFY (accepted.pending.has_value ()); + QVERIFY (lifecycle.markTransmitting ()); + + auto const first = lifecycle.beginStop (); + QVERIFY (first.has_value ()); + QCOMPARE (first->backend, JttyTxLifecycle::Backend::Local); + QCOMPARE (first->epoch, epoch); + QCOMPARE (first->progress.queued_samples, 3600); + QCOMPARE (first->progress.served_samples, 1200); + QCOMPARE (first->progress.total_samples, 4800); + + QVERIFY (!lifecycle.begin (JttyTxLifecycle::Backend::Tci, + TxAudioQueueEpoch {99})); + QVERIFY (!lifecycle.addPending (3, 4)); + QVERIFY (!lifecycle.accept (epoch, 3, 9600).pending.has_value ()); + + auto const repeated = lifecycle.beginStop (); + QVERIFY (repeated.has_value ()); + QCOMPARE (repeated->backend, first->backend); + QCOMPARE (repeated->epoch, first->epoch); + QCOMPARE (repeated->progress.total_samples, first->progress.total_samples); + } + + void acceptanceAdvancingTotalDiscardsDeferredDrain () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 10)); + + QVERIFY (!lifecycle.observeDrain (epoch, 0).has_value ()); + QVERIFY (lifecycle.deferredDrain ().has_value ()); + + auto const accepted = lifecycle.accept (epoch, 1, 2400); + QVERIFY (accepted.pending.has_value ()); + QVERIFY (!accepted.drain.has_value ()); + QVERIFY (!lifecycle.deferredDrain ().has_value ()); + QCOMPARE (lifecycle.committedTotal (), 2400); + } + + void finalFailureReleasesMatchingDeferredDrain () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 10)); + QVERIFY (lifecycle.addPending (2, 20)); + + QVERIFY (!lifecycle.observeDrain (epoch, 0).has_value ()); + auto const first = lifecycle.fail (epoch, 1); + QVERIFY (first.pending.has_value ()); + QVERIFY (!first.drain.has_value ()); + + auto const last = lifecycle.fail (epoch, 2); + QVERIFY (last.pending.has_value ()); + QVERIFY (last.drain.has_value ()); + QCOMPARE (last.drain->epoch, epoch); + QCOMPARE (last.drain->total, 0); + } + + void rigCloseCanRejectEveryPendingRequestBeforeAcceptance () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 11)); + QVERIFY (lifecycle.addPending (2, 22)); + + auto const failed = lifecycle.failAll (); + QCOMPARE (failed.pending.size (), std::size_t {2}); + QCOMPARE (failed.pending.at (0).request_id, 11); + QCOMPARE (failed.pending.at (1).request_id, 22); + QVERIFY (!lifecycle.hasPending ()); + + auto const stop = lifecycle.beginStop (); + QVERIFY (stop.has_value ()); + QCOMPARE (stop->backend, JttyTxLifecycle::Backend::Tci); + QVERIFY (!lifecycle.accept (epoch, 1, 100).pending.has_value ()); + } + + void localStopCanRejectPendingAfterSnapshot () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QVERIFY (lifecycle.addPending (1, 11)); + + auto const stop = lifecycle.beginStop (); + QVERIFY (stop.has_value ()); + QVERIFY (!lifecycle.fail (epoch, 1).pending.has_value ()); + + auto const failed = lifecycle.failAll (); + QCOMPARE (failed.pending.size (), std::size_t {1}); + QCOMPARE (failed.pending.front ().request_id, 11); + QVERIFY (!failed.drain.has_value ()); + } + + void preacceptanceTimeoutIsConfigurableAndStartsWithFirstPending () + { + using namespace std::chrono_literals; + + JttyTxLifecycle lifecycle {25ms}; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Local); + auto const start = JttyTxLifecycle::TimePoint {1s}; + + QVERIFY (!lifecycle.preacceptanceDeadline ().has_value ()); + QVERIFY (lifecycle.addPending (1, 1, start)); + QCOMPARE (lifecycle.preacceptanceTimeout (), 25ms); + QCOMPARE (*lifecycle.preacceptanceDeadline (), start + 25ms); + QVERIFY (!lifecycle.preacceptanceTimedOut (start + 24ms)); + QVERIFY (lifecycle.preacceptanceTimedOut (start + 25ms)); + + QVERIFY (lifecycle.addPending (2, 2, start + 20ms)); + QCOMPARE (*lifecycle.preacceptanceDeadline (), start + 25ms); + QVERIFY (lifecycle.accept (epoch, 1, 10).pending.has_value ()); + QVERIFY (lifecycle.preacceptanceDeadline ().has_value ()); + QVERIFY (lifecycle.fail (epoch, 2).pending.has_value ()); + QVERIFY (!lifecycle.preacceptanceDeadline ().has_value ()); + } + + void resetRequiresBackendStopRouting () + { + JttyTxLifecycle lifecycle; + auto const epoch = lifecycle.begin (JttyTxLifecycle::Backend::Local); + QVERIFY (lifecycle.addPending (1, 1)); + QVERIFY (lifecycle.accept (epoch, 1, 10).pending.has_value ()); + + auto const stop = lifecycle.beginStop (); + QVERIFY (stop.has_value ()); + QVERIFY (!lifecycle.reset ()); + QCOMPARE (lifecycle.phase (), JttyTxLifecycle::Phase::Stopping); + QCOMPARE (lifecycle.backend (), JttyTxLifecycle::Backend::Local); + + auto wrong = *stop; + wrong.backend = JttyTxLifecycle::Backend::Tci; + QVERIFY (!lifecycle.markBackendStopRouted (wrong)); + QVERIFY (!lifecycle.reset ()); + + QVERIFY (lifecycle.markBackendStopRouted (*stop)); + QVERIFY (lifecycle.reset ()); + QCOMPARE (lifecycle.phase (), JttyTxLifecycle::Phase::Idle); + QCOMPARE (lifecycle.backend (), JttyTxLifecycle::Backend::None); + QVERIFY (!lifecycle.accept (epoch, 1, 10).pending.has_value ()); + + auto const next = lifecycle.begin (JttyTxLifecycle::Backend::Tci); + QCOMPARE (next.value (), epoch.value () + 1); + } +}; + +QTEST_GUILESS_MAIN (TestJttyTxLifecycle) + +#include "test_jtty_tx_lifecycle.moc" diff --git a/tests/unit/jtty/test_jtty_txstream.cpp b/tests/unit/jtty/test_jtty_txstream.cpp index d71be2a6..0ad89db5 100644 --- a/tests/unit/jtty/test_jtty_txstream.cpp +++ b/tests/unit/jtty/test_jtty_txstream.cpp @@ -1,9 +1,13 @@ #include <QtTest/QtTest> +#include <QElapsedTimer> #include <QSignalSpy> #include <QPointer> #include <QThread> #include <QVector> +#include <atomic> +#include <thread> + #include "Audio/AudioDevice.hpp" #include "Audio/TxAudioQueue.hpp" #include "Audio/TxIdentity.hpp" @@ -26,10 +30,12 @@ private slots: void gaplessConcatAndSilencePad (); void clearResetsCounters (); void clearThenEnqueueSkipsOldSamples (); + void resetMustBeAppliedBeforeReusingCapacity (); void clearDuringPartialPlaybackSkipsRemainder (); void pendingResetProgressExcludesAbortedAudio (); void fifoOverflowRejectsWithoutTruncating (); void fifoWrappedEnqueuePreservesOrder (); + void concurrentChainedEnqueueAndPullPreservesOrder (); void enqueueFitPredicate (); void fifoDrainStateCarriesEpochAndTotal (); void fifoDrainAfterResetUsesNewEpochAndTotal (); @@ -37,10 +43,18 @@ private slots: void drainedPredicate (); void readDoesNotEmitDrainedDirectly (); void timerEmitsDrainedEdge (); + void progressTracksConsumptionAppendAndReset (); + void progressPrecedesDrainAfterRefill (); + void stopAppliesPendingResetAndAcknowledges (); + void stopPreservesNewEpochSamples (); void drainedEmittedFromWorkerThread (); void sourceCommitUsesCurrentRealExtent (); void staleQueueEpochDoesNotStart (); void sourceCommitIsEmittedOncePerStart (); + void queuedClearAndEnqueueAcknowledgeReplacement (); + void queuedEnqueueReportsTypedFailures (); + void pendingPayloadBudgetSurvivesAbort (); + void pendingRequestBudgetRecoversAfterDelivery (); }; namespace @@ -77,11 +91,20 @@ namespace for (int i = 0; i < n; ++i) out.append (p[i]); return out; } + + QByteArray pcmBytes (QVector<qint16> const& samples) + { + return QByteArray {reinterpret_cast<char const *> (samples.constData ()), + samples.size () * int (sizeof (qint16))}; + } } void TestJttyTxStream::initTestCase () { qRegisterMetaType<TxAudioQueueDrainState> ("TxAudioQueueDrainState"); + qRegisterMetaType<TxAudioQueueEnqueueFailure> ( + "TxAudioQueueEnqueueFailure"); + qRegisterMetaType<TxAudioQueueProgress> ("TxAudioQueueProgress"); } void TestJttyTxStream::gaplessConcatAndSilencePad () @@ -146,6 +169,25 @@ void TestJttyTxStream::clearThenEnqueueSkipsOldSamples () QCOMPARE (fifo.servedReal (), qint64 (2)); } +void TestJttyTxStream::resetMustBeAppliedBeforeReusingCapacity () +{ + JttyPcmFifo fifo {8}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3, 4, 5, 6, 7}, 1)); + fifo.clear (2); + QVERIFY (!fifo.enqueue (QVector<qint16> {8, 9}, 2)); + + fifo.applyPendingReset (); + QVERIFY (fifo.enqueue (QVector<qint16> {8, 9}, 2)); + + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.queuedReal (), qint64 (2)); + + QCOMPARE (fifo.pullSample (2), qint16 (8)); + QCOMPARE (fifo.pullSample (2), qint16 (9)); + QCOMPARE (fifo.pullSample (2), qint16 (0)); + QCOMPARE (fifo.servedReal (), qint64 (2)); +} + void TestJttyTxStream::clearDuringPartialPlaybackSkipsRemainder () { JttyPcmFifo fifo {16}; @@ -213,6 +255,48 @@ void TestJttyTxStream::fifoWrappedEnqueuePreservesOrder () QCOMPARE (fifo.servedReal (), qint64 (7)); } +void TestJttyTxStream::concurrentChainedEnqueueAndPullPreservesOrder () +{ + constexpr int sampleCount = 5000; + constexpr int chunkSize = 17; + JttyPcmFifo fifo {64}; + QVector<qint16> received; + received.reserve (sampleCount); + std::atomic<bool> producerDone {false}; + + std::thread producer {[&fifo, &producerDone] { + for (int first = 1; first <= sampleCount; first += chunkSize) + { + QVector<qint16> chunk; + int const last = qMin (first + chunkSize, sampleCount + 1); + chunk.reserve (last - first); + for (int sample = first; sample < last; ++sample) + { + chunk.append (qint16 (sample)); + } + while (!fifo.enqueue (chunk, 1)) + { + std::this_thread::yield (); + } + } + producerDone.store (true, std::memory_order_release); + }}; + + while (!producerDone.load (std::memory_order_acquire) + || received.size () < sampleCount) + { + qint16 const sample = fifo.pullSample (64); + if (sample != 0) received.append (sample); + } + producer.join (); + + QCOMPARE (received.size (), sampleCount); + for (int i = 0; i < received.size (); ++i) + { + QCOMPARE (received.at (i), qint16 (i + 1)); + } +} + void TestJttyTxStream::enqueueFitPredicate () { QVERIFY (jttyPcmEnqueueFits (4, 0, 4)); @@ -308,10 +392,146 @@ void TestJttyTxStream::readDoesNotEmitDrainedDirectly () JttyTxStream s {queue}; QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); QSignalSpy spy (&s, &JttyTxStream::drained); + QSignalSpy progressSpy (&s, &JttyTxStream::progress); QVERIFY (queue.enqueue (QVector<qint16> {7, 7, 7}, epoch).accepted); (void) readFrames (s, 3 + DEFAULT_GUARD); QCOMPARE (spy.count (), 0); + QCOMPARE (progressSpy.count (), 0); +} + +void TestJttyTxStream::progressTracksConsumptionAppendAndReset () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (35); + queue.clear (epoch); + JttyTxStream stream {queue}; + QSignalSpy spy (&stream, &JttyTxStream::progress); + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3}, epoch).accepted); + stream.start (jttyRequest (35, 1), nullptr); + + QTRY_COMPARE (spy.count (), 1); + auto current = qvariant_cast<TxAudioQueueProgress> (spy.last ().at (0)); + QCOMPARE (current.epoch, epoch); + QCOMPARE (current.served_samples, qint64 (0)); + QCOMPARE (current.total_samples, qint64 (3)); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 1); + + QCOMPARE (readFrames (stream, 2), (QVector<qint16> {1, 2})); + QCOMPARE (spy.count (), 1); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 2); + current = qvariant_cast<TxAudioQueueProgress> (spy.last ().at (0)); + QCOMPARE (current.served_samples, qint64 (2)); + QCOMPARE (current.queued_samples, qint64 (1)); + + QVERIFY (queue.enqueue (QVector<qint16> {4, 5}, epoch).accepted); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 3); + current = qvariant_cast<TxAudioQueueProgress> (spy.last ().at (0)); + QCOMPARE (current.epoch, epoch); + QCOMPARE (current.served_samples, qint64 (2)); + QCOMPARE (current.total_samples, qint64 (5)); + + auto const nextEpoch = queueEpoch (36); + queue.clear (nextEpoch); + QVERIFY (queue.enqueue (QVector<qint16> {6}, nextEpoch).accepted); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 4); + current = qvariant_cast<TxAudioQueueProgress> (spy.last ().at (0)); + QCOMPARE (current.epoch, nextEpoch); + QCOMPARE (current.served_samples, qint64 (0)); + QCOMPARE (current.total_samples, qint64 (1)); + QCOMPARE (current.queued_samples, qint64 (1)); + + queue.clear (TxAudioQueueEpoch::invalid ()); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 4); + stream.stop (); + queue.clear (queueEpoch (37)); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (spy.count (), 4); +} + +void TestJttyTxStream::progressPrecedesDrainAfterRefill () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (38); + queue.clear (epoch); + JttyTxStream stream {queue}; + QSignalSpy drainedSpy (&stream, &JttyTxStream::drained); + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3}, epoch).accepted); + stream.start (jttyRequest (38, 1), nullptr); + bool appended {false}; + bool progressPrecededDrain {false}; + connect (&stream, &JttyTxStream::drained, &stream, + [&appended, &progressPrecededDrain] (TxAudioQueueDrainState) { + progressPrecededDrain = appended; + }); + connect (&stream, &JttyTxStream::progress, &stream, + [&queue, epoch, &appended] (TxAudioQueueProgress current) { + if (!appended && current.served_samples == current.total_samples) + { + appended = queue.enqueue (QVector<qint16> {4, 5}, epoch).accepted; + } + }); + + (void) readFrames (stream, 3 + DEFAULT_GUARD); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QVERIFY (appended); + QVERIFY (progressPrecededDrain); + QCOMPARE (drainedSpy.count (), 1); + QCOMPARE (qvariant_cast<TxAudioQueueDrainState> ( + drainedSpy.first ().at (0)).total_at_drain, qint64 (3)); + QCOMPARE (readFrames (stream, 2), (QVector<qint16> {4, 5})); + (void) readFrames (stream, DEFAULT_GUARD); + QVERIFY (QMetaObject::invokeMethod (&stream, "pollDrain")); + QCOMPARE (drainedSpy.count (), 2); + QCOMPARE (qvariant_cast<TxAudioQueueDrainState> ( + drainedSpy.last ().at (0)).total_at_drain, qint64 (5)); + stream.stop (); +} + +void TestJttyTxStream::stopAppliesPendingResetAndAcknowledges () +{ + TxAudioQueue queue {8}; + auto const epoch = queueEpoch (39); + auto const nextEpoch = queueEpoch (40); + queue.clear (epoch); + JttyTxStream stream {queue}; + QSignalSpy stoppedSpy (&stream, &JttyTxStream::stopped); + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3, 4, 5, 6}, epoch).accepted); + + // Stop during PTT lead: no audio pull has applied either reset yet. + queue.clear (nextEpoch); + stream.stop (); + QCOMPARE (stoppedSpy.count (), 1); + QVERIFY (queue.enqueue (QVector<qint16> {7, 8, 9, 10, 11, 12}, nextEpoch).accepted); + stream.start (jttyRequest (40, 1), nullptr); + QCOMPARE (readFrames (stream, 6), (QVector<qint16> {7, 8, 9, 10, 11, 12})); + stream.stop (); + stream.stop (); + QCOMPARE (stoppedSpy.count (), 3); +} + +void TestJttyTxStream::stopPreservesNewEpochSamples () +{ + TxAudioQueue queue {8}; + auto const epoch = queueEpoch (42); + auto const nextEpoch = queueEpoch (43); + queue.clear (epoch); + JttyTxStream stream {queue}; + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3, 4, 5, 6}, epoch).accepted); + stream.start (jttyRequest (42, 1), nullptr); + queue.clear (nextEpoch); + QVERIFY (queue.enqueue (QVector<qint16> {7, 8}, nextEpoch).accepted); + + stream.stop (); + QCOMPARE (queue.progress ().queued_samples, qint64 (2)); + stream.start (jttyRequest (43, 2), nullptr); + QCOMPARE (readFrames (stream, 3), (QVector<qint16> {7, 8, 0})); + stream.stop (); } void TestJttyTxStream::timerEmitsDrainedEdge () @@ -483,5 +703,161 @@ void TestJttyTxStream::sourceCommitIsEmittedOncePerStart () stream.stop (); } +void TestJttyTxStream::queuedClearAndEnqueueAcknowledgeReplacement () +{ + TxAudioQueue queue {8}; + auto const first = queueEpoch (91); + auto const replacement = queueEpoch (92); + queue.clear (first); + queue.applyPendingReset (); + QVector<qint16> const aborted {1, 2, 3, 4, 5, 6, 7, 8}; + QVector<qint16> const replacementSamples {11, 12, 13, 14, 15, 16, 17, 18}; + QVERIFY (queue.enqueue (aborted, first).accepted); + QCOMPARE (queue.enqueue (QVector<qint16> {9}, first).failure, + TxAudioQueueEnqueueFailure::Capacity); + + auto * stream = new JttyTxStream {queue}; + QPointer<JttyTxStream> streamWitness {stream}; + QObject receiver; + int acceptedCount {0}; + int failedCount {0}; + qint64 acceptedId {-1}; + qint64 acceptedSamples {-1}; + TxAudioQueueProgress signaledProgress; + TxAudioQueueProgress callbackProgress; + connect (stream, &JttyTxStream::enqueueAccepted, &receiver, + [&] (qint64 enqueueId, qint64 sampleCount, + TxAudioQueueProgress progress) { + ++acceptedCount; + acceptedId = enqueueId; + acceptedSamples = sampleCount; + signaledProgress = progress; + callbackProgress = queue.progress (); + }, Qt::QueuedConnection); + connect (stream, &JttyTxStream::enqueueFailed, &receiver, + [&] {++failedCount;}, Qt::QueuedConnection); + + QThread audioThread; + stream->moveToThread (&audioThread); + connect (&audioThread, &QThread::finished, stream, &QObject::deleteLater); + + QMetaObject::invokeMethod (stream, [stream, replacement] { + stream->clearQueue (replacement); + }, Qt::QueuedConnection); + QMetaObject::invokeMethod ( + stream, [stream, replacement, replacementSamples] { + stream->enqueuePcm (pcmBytes (replacementSamples), replacement, 101); + }, Qt::QueuedConnection); + audioThread.start (); + + QElapsedTimer callbackWait; + callbackWait.start (); + while (!acceptedCount && !failedCount && callbackWait.elapsed () < 2000) + { + QCoreApplication::processEvents (QEventLoop::AllEvents, 10); + QThread::msleep (1); + } + + bool const stopped = QMetaObject::invokeMethod ( + stream, "stop", Qt::BlockingQueuedConnection); + audioThread.quit (); + bool const threadStopped = audioThread.wait (2000); + + QVERIFY (stopped); + QVERIFY (threadStopped); + QVERIFY (streamWitness.isNull ()); + QCOMPARE (failedCount, 0); + QCOMPARE (acceptedCount, 1); + QCOMPARE (acceptedId, qint64 (101)); + QCOMPARE (acceptedSamples, qint64 (replacementSamples.size ())); + QCOMPARE (signaledProgress.epoch, replacement); + QCOMPARE (signaledProgress.queued_samples, + qint64 (replacementSamples.size ())); + QCOMPARE (signaledProgress.total_samples, + qint64 (replacementSamples.size ())); + QCOMPARE (callbackProgress.epoch, replacement); + QCOMPARE (callbackProgress.total_samples, + qint64 (replacementSamples.size ())); + for (auto sample : replacementSamples) + { + QCOMPARE (queue.pullSample (0), sample); + } + QCOMPARE (queue.pullSample (0), qint16 (0)); +} + +void TestJttyTxStream::queuedEnqueueReportsTypedFailures () +{ + TxAudioQueue queue {2}; + auto const current = queueEpoch (101); + queue.clear (current); + queue.applyPendingReset (); + JttyTxStream stream {queue}; + QSignalSpy accepted (&stream, &JttyTxStream::enqueueAccepted); + QSignalSpy failed (&stream, &JttyTxStream::enqueueFailed); + + stream.enqueuePcm (pcmBytes (QVector<qint16> {1, 2}), current, 201); + stream.enqueuePcm (pcmBytes (QVector<qint16> {3}), current, 202); + stream.enqueuePcm (pcmBytes (QVector<qint16> {4}), queueEpoch (102), 203); + + QCOMPARE (accepted.count (), 1); + QCOMPARE (failed.count (), 2); + QCOMPARE (failed.at (0).at (0).value<TxAudioQueueEpoch> (), current); + QCOMPARE (failed.at (0).at (1).toLongLong (), qint64 (202)); + QCOMPARE (failed.at (0).at (2).value<TxAudioQueueEnqueueFailure> (), + TxAudioQueueEnqueueFailure::Capacity); + QCOMPARE (failed.at (1).at (1).toLongLong (), qint64 (203)); + QCOMPARE (failed.at (1).at (2).value<TxAudioQueueEnqueueFailure> (), + TxAudioQueueEnqueueFailure::StaleEpoch); +} + +void TestJttyTxStream::pendingPayloadBudgetSurvivesAbort () +{ + TxAudioQueue queue; + JttyTxStream stream {queue}; + auto const first = queueEpoch (1); + auto const replacement = queueEpoch (2); + stream.clearQueue (first); + QSignalSpy accepted (&stream, &JttyTxStream::enqueueAccepted); + QSignalSpy failed (&stream, &JttyTxStream::enqueueFailed); + QByteArray const full (int (TxAudioQueue::defaultCapacity () * sizeof (qint16)), '\0'); + + stream.queuePcm (full, first, 1); + stream.clearQueue (replacement); + stream.queuePcm (pcmBytes ({7}), replacement, 2); + QCOMPARE (failed.count (), 1); + QCOMPARE (failed.at (0).at (2).value<TxAudioQueueEnqueueFailure> (), + TxAudioQueueEnqueueFailure::Capacity); + + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 0); + QCOMPARE (failed.count (), 2); + QCOMPARE (failed.at (1).at (2).value<TxAudioQueueEnqueueFailure> (), + TxAudioQueueEnqueueFailure::StaleEpoch); + + stream.queuePcm (full, replacement, 3); + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 1); +} + +void TestJttyTxStream::pendingRequestBudgetRecoversAfterDelivery () +{ + TxAudioQueue queue; + JttyTxStream stream {queue}; + auto const epoch = queueEpoch (1); + stream.clearQueue (epoch); + QSignalSpy accepted (&stream, &JttyTxStream::enqueueAccepted); + QSignalSpy failed (&stream, &JttyTxStream::enqueueFailed); + for (int id = 1; id <= 65; ++id) stream.queuePcm (pcmBytes ({7}), epoch, id); + QCOMPARE (failed.count (), 1); + QCOMPARE (failed.at (0).at (1).toLongLong (), qint64 (65)); + + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 64); + stream.queuePcm (pcmBytes ({8}), epoch, 66); + QCoreApplication::sendPostedEvents (&stream, QEvent::MetaCall); + QCOMPARE (accepted.count (), 65); + QCOMPARE (failed.count (), 1); +} + QTEST_MAIN (TestJttyTxStream) #include "test_jtty_txstream.moc" diff --git a/tests/unit/jtty/test_jtty_waterfall.cpp b/tests/unit/jtty/test_jtty_waterfall.cpp new file mode 100644 index 00000000..0611a2f8 --- /dev/null +++ b/tests/unit/jtty/test_jtty_waterfall.cpp @@ -0,0 +1,104 @@ +#include <QtTest> +#include <QMouseEvent> +#include <QSignalSpy> + +#include "commons.h" +#include "widgets/plotter.h" + +namespace { +dec_data_t storage; +} +dec_data_t& dec_data = storage; +QVector<QColor> g_ColorTbl (256, Qt::black); + +class TestablePlotter final : public CPlotter +{ +public: + using CPlotter::mouseDoubleClickEvent; + + TestablePlotter () + { + setMode ("JTTY"); + setNsps (0, 6912); + setCurrent (false); + setPlot2dGain (0); + setPlot2dZero (0); + setCumulative (true); + setLinearAvg (false); + setReference (false); + setQ65_Sync (false); + setVHF (false); + setSingleDecode (false); + setFlatten (false, false); + setWaterfallAvg (2); + setBars (false); + setTimestamp (1); + setDiskUTC (-1); + setDataFromDisk (false); + setTol (100); + resize (700, 350); + show (); + QCoreApplication::processEvents (); + } + + void push (JttyWaterfallRow const& row) + { + std::array<float, 2048> values {}; + if (row.gap) values.fill (1.e30f); + setJttyRow (row); + draw (values.data (), true, false); + } + + void clickRow (int row) + { + QMouseEvent event {QEvent::MouseButtonDblClick, QPointF (100, 30 + row), + Qt::LeftButton, Qt::LeftButton, Qt::NoModifier}; + mouseDoubleClickEvent (&event); + } +}; + +class TestJttyWaterfall final : public QObject +{ + Q_OBJECT +private slots: + void rowIdentitySurvivesAverageResizeAndReplot () + { + TestablePlotter plotter; + QSignalSpy selected (&plotter, &CPlotter::jttyDecodeAgainAtSample); + qint64 const start = qint64 (1) << 34; + plotter.push ({12, start, start + 6912, 180000, false}); + plotter.setWaterfallAvg (11); + plotter.push ({12, start + 6912, start + 6912 + 38016, 183168, false}); + plotter.resize (1000, 450); + QCoreApplication::processEvents (); + plotter.replot (); + plotter.clickRow (1); + QCOMPARE (selected.size (), 1); + QCOMPARE (selected[0][0].toULongLong (), quint64 (12)); + QCOMPARE (selected[0][1].toLongLong (), start + 6912); + plotter.clickRow (0); + QCOMPARE (selected.size (), 2); + QCOMPARE (selected[1][1].toLongLong (), start + 6912 + 38016); + } + + void gapsAndUnpopulatedRowsDoNotSelectUnrelatedAudio () + { + TestablePlotter plotter; + QSignalSpy selected (&plotter, &CPlotter::jttyDecodeAgainAtSample); + plotter.push ({4, 0, 3456, 288, false}); + plotter.push ({4, 3456, 3456, 288, true}); + plotter.push ({5, 0, 3456, 190000, false}); + plotter.clickRow (1); + plotter.clickRow (10); + QCOMPARE (selected.size (), 0); + plotter.clickRow (2); + QCOMPARE (selected.size (), 1); + QCOMPARE (selected[0][0].toULongLong (), quint64 (4)); + plotter.clickRow (0); + QCOMPARE (selected.size (), 2); + QCOMPARE (selected[1][0].toULongLong (), quint64 (5)); + } +}; + +QTEST_MAIN (TestJttyWaterfall) +#include "test_jtty_waterfall.moc" |
