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 /lib | |
| parent | 059831534c7e884f0a607ed86b582fd00d821731 (diff) | |
New upstream version 3.3.0~beta1+dfsgupstream/3.3.0_beta1+dfsg
Diffstat (limited to 'lib')
135 files changed, 9511 insertions, 3435 deletions
diff --git a/lib/77bit/decoder_codec_context.f90 b/lib/77bit/decoder_codec_context.f90 new file mode 100644 index 00000000..2f8c0daa --- /dev/null +++ b/lib/77bit/decoder_codec_context.f90 @@ -0,0 +1,16 @@ +module decoder_codec_context + use packjt77, only: pack77_state,initialize_pack77_state + implicit none + private + public :: get_decoder_codec_state + + type(pack77_state), save, target :: gui_codec_state + +contains + + function get_decoder_codec_state() result(state) + type(pack77_state), pointer :: state + call initialize_pack77_state(gui_codec_state) + state => gui_codec_state + end function +end module decoder_codec_context diff --git a/lib/77bit/packjt77.f90 b/lib/77bit/packjt77.f90 index 9fba9f92..6efd2b15 100644 --- a/lib/77bit/packjt77.f90 +++ b/lib/77bit/packjt77.f90 @@ -9,33 +9,31 @@ module packjt77 ! decode, and configured/var decode stage calls at their boundaries, then ! commit them through save_hash_call instead of maintaining separate TX/RX ! hash stores. - character (len=13), dimension(0:1023) :: calls10='' - character (len=13), dimension(0:4095) :: calls12='' - character (len=13), dimension(1:MAXHASH) :: calls22='' - character (len=13), dimension(1:MAXRECENT) :: recent_calls='' - character (len=13) :: mycall13='' - character (len=13) :: dxcall13='' - integer, dimension(1:MAXHASH) :: ihash22=-1 - integer :: nzhash=0 + character (len=13), dimension(0:1023), target :: calls10='' + character (len=13), dimension(0:4095), target :: calls12='' + character (len=13), dimension(1:MAXHASH), target :: calls22='' + character (len=13), dimension(1:MAXRECENT), target :: recent_calls='' + character (len=13), target :: mycall13='' + character (len=13), target :: dxcall13='' + integer, dimension(1:MAXHASH), target :: ihash22=-1 + integer, target :: nzhash=0 ! Configured/var decodes queue per-thread facts until fillhashvar folds them ! into the shared hash and recent-call state. - character (len=13), dimension(1:840) :: queued_calls_by_thread='' - character (len=13), dimension(1:840) :: queued_recent_calls_by_thread='' - character (len=13) :: mycall13_configured='' - character (len=13) :: dxcall13_configured='' - character (len=13) :: mycall13_configured_prev='' - character (len=13) :: dxcall13_configured_prev='' - integer hashmy10_configured,hashmy12_configured,hashmy22_configured,hashdx10_configured - logical :: dxcall13_configured_set=.false. - logical :: mycall13_configured_set=.false. - integer, dimension(1:24) :: nqueued_calls_by_thread=0 - integer, dimension(1:24) :: nqueued_recent_calls_by_thread=0 + character (len=13), dimension(1:840), target :: queued_calls_by_thread='' + character (len=13), dimension(1:840), target :: queued_recent_calls_by_thread='' + character (len=13), target :: mycall13_configured='' + character (len=13), target :: dxcall13_configured='' + character (len=13), target :: mycall13_configured_prev='' + character (len=13), target :: dxcall13_configured_prev='' + integer, target :: hashmy10_configured,hashmy12_configured,hashmy22_configured,hashdx10_configured + logical, target :: dxcall13_configured_set=.false. + logical, target :: mycall13_configured_set=.false. + integer, dimension(1:24), target :: nqueued_calls_by_thread=0 + integer, dimension(1:24), target :: nqueued_recent_calls_by_thread=0 ! Per-thread slice boundaries of queued_*_by_thread; earlier (busier) ! decode threads get larger slots. - integer, dimension(1:25) :: thread_call_index=(/0,200,300,370,420,460,500,530,560,590,610,630,650,670,690,710, & + integer, dimension(1:25), target :: thread_call_index=(/0,200,300,370,420,460,500,530,560,590,610,630,650,670,690,710, & 730,750,770,790,800,810,820,830,840/) - integer n28a_configured,n28b_configured -!$omp threadprivate(n28a_configured,n28b_configured) ! Everything is private unless exported here; imported grammar/schema ! symbols therefore never re-export through "use packjt77". private @@ -62,6 +60,51 @@ module packjt77 public :: hashmy10_configured,hashmy12_configured,hashmy22_configured public :: hashdx10_configured public :: thread_call_index + public :: pack77_state,pack77_for_state,pack77_legacy_truncating_fallback_for_state + public :: unpack77_for_state,unpack77_configured_for_state + public :: pack28_for_state,unpack28_for_state + public :: hash10_for_state,hash12_for_state,hash22_for_state,save_hash_call_for_state + public :: queue_hash_call_for_thread_for_state,fold_queued_recent_calls_for_state + public :: sync_configured_calls_for_decode_start_for_state + public :: prepare_configured_decode_for_state,fold_queued_calls_for_state + public :: initialize_pack77_state,reset_pack77_state + + type pack77_state + character(len=13), allocatable :: calls10(:),calls12(:),calls22(:),recent_calls(:) + character(len=13) :: mycall13='',dxcall13='' + integer, allocatable :: ihash22(:) + integer :: nzhash=0 + character(len=13), allocatable :: queued_calls_by_thread(:),queued_recent_calls_by_thread(:) + integer :: nqueued_calls_by_thread(24)=0 + integer :: nqueued_recent_calls_by_thread(24)=0 + integer :: thread_call_index(25)=(/0,200,300,370,420,460,500,530,560,590,610,630,650,670,690,710, & + 730,750,770,790,800,810,820,830,840/) + character(len=13) :: mycall13_configured='',dxcall13_configured='' + character(len=13) :: mycall13_configured_prev='',dxcall13_configured_prev='' + integer :: hashmy10_configured=-1,hashmy12_configured=-1 + integer :: hashmy22_configured=-1,hashdx10_configured=-1 + logical :: mycall13_configured_set=.false.,dxcall13_configured_set=.false. + character(len=13) :: mycall13_0='',dxcall13_0=' ' + integer :: hashmy10=-1,hashmy12=-1,hashmy22=-1 + integer :: hashdx10=-1,hashdx12=-1,hashdx22=-1 + logical :: mycall13_set=.false.,dxcall13_set=.false. + end type pack77_state + + type pack77_state_view + character(len=13), pointer :: calls10(:)=>null(),calls12(:)=>null(),calls22(:)=>null() + character(len=13), pointer :: recent_calls(:)=>null() + character(len=13), pointer :: mycall13=>null(),dxcall13=>null() + integer, pointer :: ihash22(:)=>null(),nzhash=>null() + character(len=13), pointer :: queued_calls_by_thread(:)=>null() + character(len=13), pointer :: queued_recent_calls_by_thread(:)=>null() + integer, pointer :: nqueued_calls_by_thread(:)=>null(),nqueued_recent_calls_by_thread(:)=>null() + integer, pointer :: thread_call_index(:)=>null() + character(len=13), pointer :: mycall13_configured=>null(),dxcall13_configured=>null() + character(len=13), pointer :: mycall13_configured_prev=>null(),dxcall13_configured_prev=>null() + integer, pointer :: hashmy10_configured=>null(),hashmy12_configured=>null() + integer, pointer :: hashmy22_configured=>null(),hashdx10_configured=>null() + logical, pointer :: mycall13_configured_set=>null(),dxcall13_configured_set=>null() + end type pack77_state_view integer, parameter :: PACK77_STATUS_NOT_ENCODED=0 integer, parameter :: PACK77_STATUS_ENCODED=1 @@ -118,6 +161,7 @@ module packjt77 integer :: hashmy12=-1 integer :: hashmy22=-1 integer :: hashdx10=-1 + type(pack77_state_view) :: store end type unpack77_context type configured_decode_state @@ -164,6 +208,114 @@ module packjt77 contains +subroutine initialize_pack77_state(state) + type(pack77_state), intent(inout) :: state + + if(.not.allocated(state%calls10)) allocate(state%calls10(0:1023),source=repeat(' ',13)) + if(.not.allocated(state%calls12)) allocate(state%calls12(0:4095),source=repeat(' ',13)) + if(.not.allocated(state%calls22)) allocate(state%calls22(MAXHASH),source=repeat(' ',13)) + if(.not.allocated(state%recent_calls)) allocate(state%recent_calls(MAXRECENT),source=repeat(' ',13)) + if(.not.allocated(state%ihash22)) allocate(state%ihash22(MAXHASH),source=-1) + if(.not.allocated(state%queued_calls_by_thread)) & + allocate(state%queued_calls_by_thread(840),source=repeat(' ',13)) + if(.not.allocated(state%queued_recent_calls_by_thread)) & + allocate(state%queued_recent_calls_by_thread(840),source=repeat(' ',13)) +end subroutine initialize_pack77_state + +subroutine reset_pack77_state(state) + type(pack77_state), intent(inout) :: state + + call initialize_pack77_state(state) + state%calls10(:)='' + state%calls12(:)='' + state%calls22(:)='' + state%recent_calls(:)='' + state%ihash22(:)=-1 + state%queued_calls_by_thread(:)='' + state%queued_recent_calls_by_thread(:)='' + state%nzhash=0 + state%mycall13='' + state%dxcall13='' + state%nqueued_calls_by_thread=0 + state%nqueued_recent_calls_by_thread=0 + state%thread_call_index=(/0,200,300,370,420,460,500,530,560,590,610,630,650,670,690,710, & + 730,750,770,790,800,810,820,830,840/) + state%mycall13_configured='' + state%dxcall13_configured='' + state%mycall13_configured_prev='' + state%dxcall13_configured_prev='' + state%hashmy10_configured=-1 + state%hashmy12_configured=-1 + state%hashmy22_configured=-1 + state%hashdx10_configured=-1 + state%mycall13_configured_set=.false. + state%dxcall13_configured_set=.false. + state%mycall13_0='' + state%dxcall13_0=' ' + state%hashmy10=-1 + state%hashmy12=-1 + state%hashmy22=-1 + state%hashdx10=-1 + state%hashdx12=-1 + state%hashdx22=-1 + state%mycall13_set=.false. + state%dxcall13_set=.false. +end subroutine reset_pack77_state + +type(pack77_state_view) function legacy_state_view() result(view) + view%calls10=>calls10 + view%calls12=>calls12 + view%calls22=>calls22 + view%recent_calls=>recent_calls + view%mycall13=>mycall13 + view%dxcall13=>dxcall13 + view%ihash22=>ihash22 + view%nzhash=>nzhash + view%queued_calls_by_thread=>queued_calls_by_thread + view%queued_recent_calls_by_thread=>queued_recent_calls_by_thread + view%nqueued_calls_by_thread=>nqueued_calls_by_thread + view%nqueued_recent_calls_by_thread=>nqueued_recent_calls_by_thread + view%thread_call_index=>thread_call_index + view%mycall13_configured=>mycall13_configured + view%dxcall13_configured=>dxcall13_configured + view%mycall13_configured_prev=>mycall13_configured_prev + view%dxcall13_configured_prev=>dxcall13_configured_prev + view%hashmy10_configured=>hashmy10_configured + view%hashmy12_configured=>hashmy12_configured + view%hashmy22_configured=>hashmy22_configured + view%hashdx10_configured=>hashdx10_configured + view%mycall13_configured_set=>mycall13_configured_set + view%dxcall13_configured_set=>dxcall13_configured_set +end function legacy_state_view + +type(pack77_state_view) function owned_state_view(state) result(view) + type(pack77_state), target, intent(inout) :: state + call initialize_pack77_state(state) + view%calls10=>state%calls10 + view%calls12=>state%calls12 + view%calls22=>state%calls22 + view%recent_calls=>state%recent_calls + view%mycall13=>state%mycall13 + view%dxcall13=>state%dxcall13 + view%ihash22=>state%ihash22 + view%nzhash=>state%nzhash + view%queued_calls_by_thread=>state%queued_calls_by_thread + view%queued_recent_calls_by_thread=>state%queued_recent_calls_by_thread + view%nqueued_calls_by_thread=>state%nqueued_calls_by_thread + view%nqueued_recent_calls_by_thread=>state%nqueued_recent_calls_by_thread + view%thread_call_index=>state%thread_call_index + view%mycall13_configured=>state%mycall13_configured + view%dxcall13_configured=>state%dxcall13_configured + view%mycall13_configured_prev=>state%mycall13_configured_prev + view%dxcall13_configured_prev=>state%dxcall13_configured_prev + view%hashmy10_configured=>state%hashmy10_configured + view%hashmy12_configured=>state%hashmy12_configured + view%hashmy22_configured=>state%hashmy22_configured + view%hashdx10_configured=>state%hashdx10_configured + view%mycall13_configured_set=>state%mycall13_configured_set + view%dxcall13_configured_set=>state%dxcall13_configured_set +end function owned_state_view + type(pack77_result) function pack77_no_match() result(encoded) encoded=pack77_result() end function pack77_no_match @@ -197,7 +349,8 @@ subroutine pack77_accept_candidate_encoded(candidate,i3,n3,c77,ok) if(ok) candidate%result=pack77_accept(i3,n3,c77) end subroutine pack77_accept_candidate_encoded -logical function take_candidate(candidate,msg,encoded) result(won) +logical function take_candidate(store,candidate,msg,encoded) result(won) + type(pack77_state_view), intent(in) :: store type(pack77_candidate), intent(in) :: candidate character(len=*), intent(in) :: msg type(pack77_encode_core_result), intent(inout) :: encoded @@ -209,7 +362,7 @@ logical function take_candidate(candidate,msg,encoded) result(won) ! fallback callers can report what kind of exact encoding was rejected. won=candidate%result%encoded if(won) then - decoded=pack77_decode_neutral(candidate%result%c77) + decoded=pack77_decode_neutral(store,candidate%result%c77) call pack77_gate_message_checks(msg,decoded%msg,candidate%hash_facts%calls, & candidate%hash_facts%ncalls,messages_match,resolved_render_fits) if(.not.(decoded%success .and. decoded%i3.eq.candidate%result%i3 .and. & @@ -224,77 +377,115 @@ logical function take_candidate(candidate,msg,encoded) result(won) encoded%hash_facts=candidate%hash_facts end function take_candidate -type(unpack77_core_result) function pack77_decode_neutral(c77) result(decoded) +type(unpack77_core_result) function pack77_decode_neutral(store,c77) result(decoded) + type(pack77_state_view), intent(in) :: store character(len=77), intent(in) :: c77 type(unpack77_context) :: context context=unpack77_context() + context%store=store decoded=unpack77_core(c77,context) end function pack77_decode_neutral -integer function pack77_wspr_payload_type(c77) result(wspr_type) - character(len=77), intent(in) :: c77 - -! Bit columns 49/50 are the j49/j50 subtype selector fields fixed by the -! WSPR schemas in packjt77_schema; keep in sync with those field offsets. - wspr_type=0 - if(c77(50:50).eq.'1') then - wspr_type=2 - else if(c77(49:49).eq.'0') then - wspr_type=1 - else if(c77(49:49).eq.'1') then - ! Invalid selector 110 reaches Type 3; the schema decoder rejects it. - wspr_type=3 - endif -end function pack77_wspr_payload_type subroutine hash10(n10,c13) + integer, intent(in) :: n10 + character*13 c13 + + call hash10_core(legacy_state_view(),n10,c13) +end subroutine hash10 + +subroutine hash10_for_state(state,n10,c13) + type(pack77_state), target, intent(inout) :: state + integer, intent(in) :: n10 + character*13 c13 + + call hash10_core(owned_state_view(state),n10,c13) +end subroutine hash10_for_state + +subroutine hash10_core(store,n10,c13) + type(pack77_state_view), intent(in) :: store + integer, intent(in) :: n10 character*13 c13 c13='<...>' if(n10.lt.0 .or. n10.gt.1023) return - if(len(trim(calls10(n10))).gt.0) then - c13=calls10(n10) + if(len(trim(store%calls10(n10))).gt.0) then + c13=store%calls10(n10) c13='<'//trim(c13)//'>' endif return -end subroutine hash10 +end subroutine hash10_core subroutine hash12(n12,c13) + integer, intent(in) :: n12 + character*13 c13 + + call hash12_core(legacy_state_view(),n12,c13) +end subroutine hash12 + +subroutine hash12_for_state(state,n12,c13) + type(pack77_state), target, intent(inout) :: state + integer, intent(in) :: n12 + character*13 c13 + + call hash12_core(owned_state_view(state),n12,c13) +end subroutine hash12_for_state + +subroutine hash12_core(store,n12,c13) + type(pack77_state_view), intent(in) :: store + integer, intent(in) :: n12 character*13 c13 c13='<...>' if(n12.lt.0 .or. n12.gt.4095) return - if(len(trim(calls12(n12))).gt.0) then - c13=calls12(n12) + if(len(trim(store%calls12(n12))).gt.0) then + c13=store%calls12(n12) c13='<'//trim(c13)//'>' endif return -end subroutine hash12 +end subroutine hash12_core subroutine hash22(n22,c13) + integer, intent(in) :: n22 + character*13 c13 + + call hash22_core(legacy_state_view(),n22,c13) +end subroutine hash22 + +subroutine hash22_for_state(state,n22,c13) + type(pack77_state), target, intent(inout) :: state + integer, intent(in) :: n22 + character*13 c13 + + call hash22_core(owned_state_view(state),n22,c13) +end subroutine hash22_for_state + +subroutine hash22_core(store,n22,c13) + type(pack77_state_view), intent(in) :: store + integer, intent(in) :: n22 character*13 c13 c13='<...>' - do i=1,nzhash - if(ihash22(i).eq.n22) then - c13=calls22(i) + do i=1,store%nzhash + if(store%ihash22(i).eq.n22) then + c13=store%calls22(i) c13='<'//trim(c13)//'>' go to 900 endif enddo 900 return -end subroutine hash22 +end subroutine hash22_core integer function ihashcall(c0,m) @@ -354,8 +545,25 @@ integer function ihashcall_from_n8(n8,m) end function ihashcall_from_n8 subroutine save_hash_call(c13,n10,n12,n22) + character*13 c13 + integer :: n10,n12,n22 + + call save_hash_call_core(legacy_state_view(),c13,n10,n12,n22) +end subroutine save_hash_call + +subroutine save_hash_call_for_state(state,c13,n10,n12,n22) + type(pack77_state), target, intent(inout) :: state + character*13 c13 + integer :: n10,n12,n22 + + call save_hash_call_core(owned_state_view(state),c13,n10,n12,n22) +end subroutine save_hash_call_for_state + +subroutine save_hash_call_core(store,c13,n10,n12,n22) + type(pack77_state_view), intent(in) :: store character*13 c13,cw + integer :: n10,n12,n22 cw=c13 if(cw(1:1).eq.' ' .or. cw(1:5).eq.'<...>') return @@ -366,28 +574,28 @@ subroutine save_hash_call(c13,n10,n12,n22) if(len(trim(cw)) .lt. 3) return n10=ihashcall(cw,10) - if(n10.ge.0 .and. n10 .le. 1023 .and. cw.ne.mycall13) calls10(n10)=cw + if(n10.ge.0 .and. n10 .le. 1023 .and. cw.ne.store%mycall13) store%calls10(n10)=cw n12=ihashcall(cw,12) - if(n12.ge.0 .and. n12 .le. 4095 .and. cw.ne.mycall13) calls12(n12)=cw + if(n12.ge.0 .and. n12 .le. 4095 .and. cw.ne.store%mycall13) store%calls12(n12)=cw n22=ihashcall(cw,22) - if(any(ihash22.eq.n22)) then ! If entry exists, make sure callsign is the most recently received one - where(ihash22.eq.n22) calls22=cw + if(any(store%ihash22.eq.n22)) then ! If entry exists, make sure callsign is the most recently received one + where(store%ihash22.eq.n22) store%calls22=cw go to 900 endif ! New entry: move table down, making room for new one at the top - ihash22(MAXHASH:2:-1)=ihash22(MAXHASH-1:1:-1) + store%ihash22(MAXHASH:2:-1)=store%ihash22(MAXHASH-1:1:-1) ! Add the new entry - calls22(MAXHASH:2:-1)=calls22(MAXHASH-1:1:-1) - ihash22(1)=n22 - calls22(1)=cw - if(nzhash.lt.MAXHASH) nzhash=nzhash+1 + store%calls22(MAXHASH:2:-1)=store%calls22(MAXHASH-1:1:-1) + store%ihash22(1)=n22 + store%calls22(1)=cw + if(store%nzhash.lt.MAXHASH) store%nzhash=store%nzhash+1 900 continue return -end subroutine save_hash_call +end subroutine save_hash_call_core subroutine normalize_hash_call(c13,cw,ok) @@ -445,14 +653,15 @@ subroutine pack77_hash_index(hash_facts,token,nbits,n,ok) return end subroutine pack77_hash_index -subroutine commit_hash_facts(hash_facts) +subroutine commit_hash_facts(store,hash_facts) + type(pack77_state_view), intent(in) :: store type(pack77_hash_facts), intent(in) :: hash_facts integer :: i,n10,n12,n22 ! All hash-producing encode paths feed the same shared tables here. do i=1,hash_facts%ncalls - call save_hash_call(hash_facts%calls(i),n10,n12,n22) + call save_hash_call_core(store,hash_facts%calls(i),n10,n12,n22) enddo return @@ -524,10 +733,12 @@ logical function pack77_failed_preferred_wspr_shape(msg0,options) result(reject) len_trim(source_tokens(2)).le.6 end function pack77_failed_preferred_wspr_shape -type(pack77_encode_core_result) function pack77_encode_core(msg0,options) & +type(pack77_encode_core_result) function pack77_encode_core(store,msg0,options) & result(encoded) + type(pack77_state_view), intent(in) :: store - character*37 msg,msg0 + character*37 msg + character(len=*), intent(in) :: msg0 character(len=13) :: source_tokens(19) type(pack77_options), intent(in), optional :: options type(pack77_candidate) :: candidate @@ -568,14 +779,14 @@ type(pack77_encode_core_result) function pack77_encode_core(msg0,options) & ! Check 0.1 (DXpedition mode) candidate=pack77_01_candidate(msg) - if(take_candidate(candidate,msg,encoded)) return + if(take_candidate(store,candidate,msg,encoded)) return ! Check 0.2 (EU VHF contest exchange) ! call pack77_02(nwords,w,i3,n3,c77) ! if(i3.ge.0) go to 900 ! Check 0.3 and 0.4 (ARRL Field Day exchange) candidate=pack77_03_candidate(msg) - if(take_candidate(candidate,msg,encoded)) return + if(take_candidate(store,candidate,msg,encoded)) return if(nwords.lt.2) then ! Check 0.5 (telemetry) @@ -585,31 +796,32 @@ type(pack77_encode_core_result) function pack77_encode_core(msg0,options) & endif candidate=pack77_06_candidate(msg,prefer_wspr_50bit) - if(take_candidate(candidate,msg,encoded)) return + if(take_candidate(store,candidate,msg,encoded)) return ! Check Type 1 (Standard 77-bit message) or Type 2, with optional "/P" candidate=pack77_1_candidate(msg) - if(take_candidate(candidate,msg,encoded)) return + if(take_candidate(store,candidate,msg,encoded)) return ! Check Type 3 (ARRL RTTY contest exchange) candidate=pack77_3_candidate(msg) - if(take_candidate(candidate,msg,encoded)) return + if(take_candidate(store,candidate,msg,encoded)) return ! Check Type 4 (One nonstandard call and one hashed call) candidate=pack77_4_candidate(msg) - if(take_candidate(candidate,msg,encoded)) return + if(take_candidate(store,candidate,msg,encoded)) return ! Check Type 5 (EU VHF Contest with 2 hashed calls, report, serial, and grid6) candidate=pack77_5_candidate(msg) - if(take_candidate(candidate,msg,encoded)) return + if(take_candidate(store,candidate,msg,encoded)) return ! It defaults to exactly representable free text. encoded%result=pack77_free_text_exact(msg) end function pack77_encode_core -type(pack77_result) function pack77_encode_result(msg0,options) result(encoded) +type(pack77_result) function pack77_encode_result(store,msg0,options) result(encoded) + type(pack77_state_view), intent(in) :: store - character*37 msg0 + character(len=*), intent(in) :: msg0 type(pack77_options), intent(in), optional :: options type(pack77_encode_core_result) :: core logical :: record_tx_hashes @@ -617,13 +829,13 @@ type(pack77_result) function pack77_encode_result(msg0,options) result(encoded) record_tx_hashes=.true. if(present(options)) record_tx_hashes=options%record_tx_hashes - core=pack77_encode_core(msg0,options) + core=pack77_encode_core(store,msg0,options) encoded=core%result if(.not.encoded%encoded .and. & encoded%status.ne.PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED .and. & pack77_failed_preferred_wspr_shape(pack77_normalized_message(msg0), & options)) encoded=pack77_reject(PACK77_STATUS_PREFERRED_FAMILY_REJECTED) - if(record_tx_hashes) call commit_hash_facts(core%hash_facts) + if(record_tx_hashes) call commit_hash_facts(store,core%hash_facts) end function pack77_encode_result subroutine pack77(msg0,i3,n3,c77,options,status) @@ -634,13 +846,29 @@ subroutine pack77(msg0,i3,n3,c77,options,status) integer, intent(out), optional :: status type(pack77_result) :: packed - packed=pack77_encode_result(msg0,options) + packed=pack77_encode_result(legacy_state_view(),msg0,options) i3=packed%i3 n3=packed%n3 c77=packed%c77 if(present(status)) status=packed%status end subroutine pack77 +subroutine pack77_for_state(state,msg0,i3,n3,c77,options,status) + type(pack77_state), target, intent(inout) :: state + character(len=*), intent(in) :: msg0 + integer, intent(out) :: i3,n3 + character(len=77), intent(out) :: c77 + type(pack77_options), intent(in), optional :: options + integer, intent(out), optional :: status + type(pack77_result) :: packed + + packed=pack77_encode_result(owned_state_view(state),msg0,options) + i3=packed%i3 + n3=packed%n3 + c77=packed%c77 + if(present(status)) status=packed%status +end subroutine pack77_for_state + subroutine pack77_legacy_truncating_fallback(msg0,i3,n3,c77,options,status) character(len=*), intent(in) :: msg0 integer, intent(out) :: i3,n3 @@ -649,22 +877,39 @@ subroutine pack77_legacy_truncating_fallback(msg0,i3,n3,c77,options,status) integer, intent(out), optional :: status type(pack77_result) :: packed - packed=pack77_legacy_truncating_result(msg0,options) + packed=pack77_legacy_truncating_result(legacy_state_view(),msg0,options) i3=packed%i3 n3=packed%n3 c77=packed%c77 if(present(status)) status=packed%status end subroutine pack77_legacy_truncating_fallback -type(pack77_result) function pack77_legacy_truncating_result(msg0,options) & +subroutine pack77_legacy_truncating_fallback_for_state(state,msg0,i3,n3,c77,options,status) + type(pack77_state), target, intent(inout) :: state + character(len=*), intent(in) :: msg0 + integer, intent(out) :: i3,n3 + character(len=77), intent(out) :: c77 + type(pack77_options), intent(in), optional :: options + integer, intent(out), optional :: status + type(pack77_result) :: packed + + packed=pack77_legacy_truncating_result(owned_state_view(state),msg0,options) + i3=packed%i3 + n3=packed%n3 + c77=packed%c77 + if(present(status)) status=packed%status +end subroutine pack77_legacy_truncating_fallback_for_state + +type(pack77_result) function pack77_legacy_truncating_result(store,msg0,options) & result(encoded) + type(pack77_state_view), intent(in) :: store character(len=*), intent(in) :: msg0 type(pack77_options), intent(in), optional :: options type(pack77_result) :: fallback character(len=37) :: msg character(len=13) :: payload - encoded=pack77_encode_result(msg0,options) + encoded=pack77_encode_result(store,msg0,options) if(encoded%encoded) return if(encoded%status.eq.PACK77_STATUS_PREFERRED_FAMILY_REJECTED) return if(encoded%status.eq.PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED) return @@ -759,25 +1004,7 @@ integer function pack77_free_text_reject_status(msg) result(status) endif end function pack77_free_text_reject_status -logical function pack77_exact_free_text_ok(msg) result(ok) - character(len=*), intent(in) :: msg - - ok=.false. - if(len_trim(msg).gt.13) return - ok=pack77_free_text_alphabet_ok(msg(1:len_trim(msg))) -end function pack77_exact_free_text_ok -logical function pack77_free_text_alphabet_ok(msg) result(ok) - character(len=*), intent(in) :: msg - character(len=42), parameter :: alphabet=' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?' - integer :: i - - ok=.false. - do i=1,len_trim(msg) - if(index(alphabet,msg(i:i)).eq.0) return - enddo - ok=.true. -end function pack77_free_text_alphabet_ok ! Must mirror the character canonicalization of pack77_split_source_tokens ! (NUL->space, uppercase fold, blank collapse) so free text and structured @@ -850,6 +1077,7 @@ subroutine unpack77(c77,nrx,msg,unpk77_success) context%nrx=nrx context%configured=.false. context%strict_var_guards=.false. + context%store=legacy_state_view() context%mycall_set=mycall13_set context%dxcall_set=dxcall13_set context%mycall=mycall13 @@ -865,6 +1093,52 @@ subroutine unpack77(c77,nrx,msg,unpk77_success) return end subroutine unpack77 +subroutine unpack77_for_state(state,c77,nrx,msg,unpk77_success) + type(pack77_state), target, intent(inout) :: state + character*77 c77 + character*37 msg + integer, intent(in) :: nrx + logical unpk77_success + type(unpack77_context) :: context + type(unpack77_effect_policy) :: policy + + context%store=owned_state_view(state) + if(state%mycall13.ne.state%mycall13_0) then + if(len(trim(state%mycall13)).gt.2) then + state%mycall13_set=.true. + state%mycall13_0=state%mycall13 + call save_hash_call_core(context%store,state%mycall13, & + state%hashmy10,state%hashmy12,state%hashmy22) + else + state%mycall13_set=.false. + endif + endif + if(state%dxcall13.ne.state%dxcall13_0) then + if(len(trim(state%dxcall13)).gt.2) then + state%dxcall13_set=.true. + state%dxcall13_0=state%dxcall13 + state%hashdx10=ihashcall(state%dxcall13,10) + state%hashdx12=ihashcall(state%dxcall13,12) + state%hashdx22=ihashcall(state%dxcall13,22) + else + state%dxcall13_set=.false. + endif + endif + context%nrx=nrx + context%configured=.false. + context%strict_var_guards=.false. + context%mycall_set=state%mycall13_set + context%dxcall_set=state%dxcall13_set + context%mycall=state%mycall13 + context%dxcall=state%dxcall13 + context%hashmy10=state%hashmy10 + context%hashmy12=state%hashmy12 + context%hashmy22=state%hashmy22 + context%hashdx10=state%hashdx10 + policy=unpack77_effect_policy() + call run_unpack77(c77,context,policy,msg,unpk77_success) +end subroutine unpack77_for_state + subroutine pack28(c13,n28) ! Callers must pass a well-formed callsign or special/hash token. Malformed ! tokens are encoded as 22-bit hashes, never coerced to standard calls, per the @@ -874,11 +1148,21 @@ subroutine pack28(c13,n28) type(pack77_hash_facts) :: hash_facts call pack28_core(c13,n28,hash_facts) - call commit_hash_facts(hash_facts) + call commit_hash_facts(legacy_state_view(),hash_facts) return end subroutine pack28 +subroutine pack28_for_state(state,c13,n28) + type(pack77_state), target, intent(inout) :: state + character*13 c13 + integer, intent(out) :: n28 + type(pack77_hash_facts) :: hash_facts + + call pack28_core(c13,n28,hash_facts) + call commit_hash_facts(owned_state_view(state),hash_facts) +end subroutine pack28_for_state + subroutine pack28_core(c13,n28,hash_facts) ! Pack a special token, a 22-bit hash code, or a valid base call into a 28-bit @@ -1005,12 +1289,22 @@ subroutine unpack28(n28_0,c13,success) character*13 c13 logical success - call unpack28_core(n28_0,c13,success,.false.) + call unpack28_core(legacy_state_view(),n28_0,c13,success,.false.) return end subroutine unpack28 -subroutine unpack28_core(n28_0,c13,success,reject_two_digit_prefix) +subroutine unpack28_for_state(state,n28_0,c13,success) + type(pack77_state), target, intent(inout) :: state + integer, intent(in) :: n28_0 + character*13 c13 + logical success + + call unpack28_core(owned_state_view(state),n28_0,c13,success,.false.) +end subroutine unpack28_for_state + +subroutine unpack28_core(store,n28_0,c13,success,reject_two_digit_prefix) + type(pack77_state_view), intent(in) :: store logical success,callok logical, intent(in) :: reject_two_digit_prefix character*13 c13 @@ -1055,7 +1349,7 @@ subroutine unpack28_core(n28_0,c13,success,reject_two_digit_prefix) if(n28.lt.PACK77_MAX22) then ! This is a 22-bit hash of a callsign n22=n28 - call hash22(n22,c13) !Retrieve callsign from hash table + call hash22_core(store,n22,c13) !Retrieve callsign from hash table go to 900 endif @@ -1246,6 +1540,13 @@ subroutine mp_short_init end subroutine mp_short_init subroutine add_call_to_recent_calls(callsign) + character*13 callsign + + call add_call_to_recent_calls_core(legacy_state_view(),callsign) +end subroutine add_call_to_recent_calls + +subroutine add_call_to_recent_calls_core(store,callsign) + type(pack77_state_view), intent(in) :: store character*13 callsign logical ladd @@ -1253,21 +1554,21 @@ subroutine add_call_to_recent_calls(callsign) ! only add if the callsign is not already on the list ladd=.true. do i=1,MAXRECENT-1 ! if callsign is at the end of the list add it again - if(recent_calls(i).eq.callsign) ladd=.false. + if(store%recent_calls(i).eq.callsign) ladd=.false. enddo if(ladd) then do i=MAXRECENT,2,-1 - recent_calls(i)=recent_calls(i-1) + store%recent_calls(i)=store%recent_calls(i-1) enddo - recent_calls(1)=callsign + store%recent_calls(1)=callsign endif ! Recent-call ordering is separate from hash storage; decode paths stage both ! effects explicitly when a call should become recent and hash-resolvable. return -end subroutine add_call_to_recent_calls +end subroutine add_call_to_recent_calls_core @@ -1277,23 +1578,48 @@ subroutine queue_hash_call_for_thread(c13,nthr) ! Configured/var decode workers queue hash facts; fillhashvar later folds them ! into the shared calls10/calls12/calls22 tables. - call queue_call_for_thread(c13,nthr,queued_calls_by_thread, & - nqueued_calls_by_thread) + call queue_hash_call_core(legacy_state_view(),c13,nthr) return end subroutine queue_hash_call_for_thread +subroutine queue_hash_call_for_thread_for_state(state,c13,nthr) + type(pack77_state), target, intent(inout) :: state + character*13 c13 + integer, intent(in) :: nthr + + call queue_hash_call_core(owned_state_view(state),c13,nthr) +end subroutine queue_hash_call_for_thread_for_state + +subroutine queue_hash_call_core(store,c13,nthr) + type(pack77_state_view), intent(in) :: store + character*13 c13 + integer, intent(in) :: nthr + + call queue_call_for_thread(store,c13,nthr,store%queued_calls_by_thread, & + store%nqueued_calls_by_thread) +end subroutine queue_hash_call_core + subroutine queue_recent_call_for_thread(c13,nthr) character*13 c13 integer, intent(in) :: nthr - call queue_call_for_thread(c13,nthr,queued_recent_calls_by_thread, & - nqueued_recent_calls_by_thread) + call queue_recent_call_core(legacy_state_view(),c13,nthr) return end subroutine queue_recent_call_for_thread -subroutine queue_call_for_thread(c13,nthr,queued_calls,nqueued_calls) +subroutine queue_recent_call_core(store,c13,nthr) + type(pack77_state_view), intent(in) :: store + character*13 c13 + integer, intent(in) :: nthr + + call queue_call_for_thread(store,c13,nthr,store%queued_recent_calls_by_thread, & + store%nqueued_recent_calls_by_thread) +end subroutine queue_recent_call_core + +subroutine queue_call_for_thread(store,c13,nthr,queued_calls,nqueued_calls) + type(pack77_state_view), intent(in) :: store character(len=*), intent(in) :: c13 integer, intent(in) :: nthr character(len=13), intent(inout) :: queued_calls(:) @@ -1308,8 +1634,8 @@ subroutine queue_call_for_thread(c13,nthr,queued_calls,nqueued_calls) if(i.gt.0) cw(i:)=' ' if(len(trim(cw)) .lt. 3) return - nposition=thread_call_index(nthr)+nqueued_calls(nthr) - if(nposition.lt.thread_call_index(nthr+1)) then + nposition=store%thread_call_index(nthr)+nqueued_calls(nthr) + if(nposition.lt.store%thread_call_index(nthr+1)) then nqueued_calls(nthr)=nqueued_calls(nthr)+1 queued_calls(nposition+1)=cw endif @@ -1318,129 +1644,190 @@ subroutine queue_call_for_thread(c13,nthr,queued_calls,nqueued_calls) end subroutine queue_call_for_thread subroutine fold_queued_recent_calls(numthreads) + integer, intent(in) :: numthreads + + call fold_queued_recent_calls_core(legacy_state_view(),numthreads) +end subroutine fold_queued_recent_calls + +subroutine fold_queued_recent_calls_for_state(state,numthreads) + type(pack77_state), target, intent(inout) :: state + integer, intent(in) :: numthreads + + call fold_queued_recent_calls_core(owned_state_view(state),numthreads) +end subroutine fold_queued_recent_calls_for_state + +subroutine fold_queued_recent_calls_core(store,numthreads) + type(pack77_state_view), intent(in) :: store integer, intent(in) :: numthreads character*13 cw do i=1,numthreads - do m=1,nqueued_recent_calls_by_thread(i) - nposition=thread_call_index(i)+m - cw=queued_recent_calls_by_thread(nposition) - call add_call_to_recent_calls(cw) + do m=1,store%nqueued_recent_calls_by_thread(i) + nposition=store%thread_call_index(i)+m + cw=store%queued_recent_calls_by_thread(nposition) + call add_call_to_recent_calls_core(store,cw) enddo enddo return -end subroutine fold_queued_recent_calls +end subroutine fold_queued_recent_calls_core subroutine sync_configured_calls_for_decode_start() + call sync_configured_calls_core(legacy_state_view()) +end subroutine sync_configured_calls_for_decode_start + +subroutine sync_configured_calls_for_decode_start_for_state(state) + type(pack77_state), target, intent(inout) :: state + + call sync_configured_calls_core(owned_state_view(state)) +end subroutine sync_configured_calls_for_decode_start_for_state + +subroutine prepare_configured_decode_for_state(state,mycall,hiscall) + type(pack77_state), target, intent(inout) :: state + character(len=*), intent(in) :: mycall,hiscall + + state%nqueued_calls_by_thread=0 + state%nqueued_recent_calls_by_thread=0 + state%mycall13=mycall + state%dxcall13=hiscall + call sync_configured_calls_core(owned_state_view(state)) +end subroutine prepare_configured_decode_for_state + +subroutine fold_queued_calls_for_state(state,numthreads) + type(pack77_state), target, intent(inout) :: state + integer, intent(in) :: numthreads + type(pack77_state_view) :: store + integer :: i,m,nposition,n10,n12,n22 + + store=owned_state_view(state) + do i=1,numthreads + do m=1,store%nqueued_calls_by_thread(i) + nposition=store%thread_call_index(i)+m + call save_hash_call_core(store,store%queued_calls_by_thread(nposition),n10,n12,n22) + enddo + enddo + call fold_queued_recent_calls_core(store,numthreads) +end subroutine fold_queued_calls_for_state + +subroutine sync_configured_calls_core(store) + type(pack77_state_view), intent(in) :: store ! Capture the operator-configured calls at decode-cycle boundaries. These ! hashes let configured decodes resolve hash-only messages without a separate ! var hash table. - if(mycall13.ne.mycall13_configured_prev) then - if(len(trim(mycall13)).gt.2) then - call set_configured_mycall_from_current() + if(store%mycall13.ne.store%mycall13_configured_prev) then + if(len(trim(store%mycall13)).gt.2) then + call set_configured_mycall_from_current(store) else - call clear_configured_mycall() + call clear_configured_mycall(store) endif endif - call sync_configured_mycall_value_from_current() + call sync_configured_mycall_value_from_current(store) - if(dxcall13.ne.dxcall13_configured_prev) then - if(len(trim(dxcall13)).gt.2) then - call set_configured_dxcall_from_current() + if(store%dxcall13.ne.store%dxcall13_configured_prev) then + if(len(trim(store%dxcall13)).gt.2) then + call set_configured_dxcall_from_current(store) else - call clear_configured_dxcall() + call clear_configured_dxcall(store) endif endif - call sync_configured_dxcall_value_from_current() + call sync_configured_dxcall_value_from_current(store) return -end subroutine sync_configured_calls_for_decode_start +end subroutine sync_configured_calls_core -subroutine set_configured_mycall_from_current() +subroutine set_configured_mycall_from_current(store) + type(pack77_state_view), intent(in) :: store - mycall13_configured_set=.true. - mycall13_configured=mycall13 - mycall13_configured_prev=mycall13 - hashmy10_configured=ihashcall(mycall13,10) - hashmy12_configured=ihashcall(mycall13,12) - hashmy22_configured=ihashcall(mycall13,22) - call save_hash_call(mycall13,ndum10,ndum12,ndum22) + store%mycall13_configured_set=.true. + store%mycall13_configured=store%mycall13 + store%mycall13_configured_prev=store%mycall13 + store%hashmy10_configured=ihashcall(store%mycall13,10) + store%hashmy12_configured=ihashcall(store%mycall13,12) + store%hashmy22_configured=ihashcall(store%mycall13,22) + call save_hash_call_core(store,store%mycall13,ndum10,ndum12,ndum22) return end subroutine set_configured_mycall_from_current -subroutine clear_configured_mycall() +subroutine clear_configured_mycall(store) + type(pack77_state_view), intent(in) :: store - mycall13_configured_set=.false. - mycall13_configured=' ' - mycall13_configured_prev=' ' - hashmy10_configured=-1 - hashmy12_configured=-1 - hashmy22_configured=-1 + store%mycall13_configured_set=.false. + store%mycall13_configured=' ' + store%mycall13_configured_prev=' ' + store%hashmy10_configured=-1 + store%hashmy12_configured=-1 + store%hashmy22_configured=-1 return end subroutine clear_configured_mycall -subroutine sync_configured_mycall_value_from_current() +subroutine sync_configured_mycall_value_from_current(store) + type(pack77_state_view), intent(in) :: store - if(mycall13_configured_set) mycall13_configured=mycall13 + if(store%mycall13_configured_set) store%mycall13_configured=store%mycall13 return end subroutine sync_configured_mycall_value_from_current -subroutine set_configured_dxcall_from_current() +subroutine set_configured_dxcall_from_current(store) + type(pack77_state_view), intent(in) :: store - dxcall13_configured_set=.true. - dxcall13_configured=dxcall13 - dxcall13_configured_prev=dxcall13 - hashdx10_configured=ihashcall(dxcall13,10) + store%dxcall13_configured_set=.true. + store%dxcall13_configured=store%dxcall13 + store%dxcall13_configured_prev=store%dxcall13 + store%hashdx10_configured=ihashcall(store%dxcall13,10) ! Seed the manual DX Call before decode so first-cycle hash references to it ! can resolve even if the call has not yet been decoded over the air. - call queue_hash_call_for_thread(dxcall13,1) + call queue_hash_call_core(store,store%dxcall13,1) return end subroutine set_configured_dxcall_from_current -subroutine clear_configured_dxcall() +subroutine clear_configured_dxcall(store) + type(pack77_state_view), intent(in) :: store - dxcall13_configured_set=.false. - dxcall13_configured=' ' - dxcall13_configured_prev=' ' - hashdx10_configured=-1 + store%dxcall13_configured_set=.false. + store%dxcall13_configured=' ' + store%dxcall13_configured_prev=' ' + store%hashdx10_configured=-1 return end subroutine clear_configured_dxcall -subroutine sync_configured_dxcall_value_from_current() +subroutine sync_configured_dxcall_value_from_current(store) + type(pack77_state_view), intent(in) :: store - if(dxcall13_configured_set) dxcall13_configured=dxcall13 + if(store%dxcall13_configured_set) store%dxcall13_configured=store%dxcall13 return end subroutine sync_configured_dxcall_value_from_current -type(configured_decode_state) function current_configured_decode_state() & +type(configured_decode_state) function current_configured_decode_state(store) & result(state) + type(pack77_state_view), intent(in) :: store - state%mycall_set=mycall13_configured_set - state%dxcall_set=dxcall13_configured_set - state%mycall=mycall13_configured - state%dxcall=dxcall13_configured - state%hashmy10=hashmy10_configured - state%hashmy12=hashmy12_configured - state%hashmy22=hashmy22_configured - state%hashdx10=hashdx10_configured + state%mycall_set=store%mycall13_configured_set + state%dxcall_set=store%dxcall13_configured_set + state%mycall=store%mycall13_configured + state%dxcall=store%dxcall13_configured + state%hashmy10=store%hashmy10_configured + state%hashmy12=store%hashmy12_configured + state%hashmy22=store%hashmy22_configured + state%hashdx10=store%hashdx10_configured return end function current_configured_decode_state -type(unpack77_context) function configured_unpack77_context(nrx) result(context) +type(unpack77_context) function configured_unpack77_context(store,nrx) result(context) + type(pack77_state_view), intent(in) :: store integer, intent(in) :: nrx type(configured_decode_state) :: state - state=current_configured_decode_state() + state=current_configured_decode_state(store) + context%store=store context%nrx=nrx context%configured=.true. context%strict_var_guards=.true. @@ -1473,13 +1860,28 @@ subroutine unpack77_configured(c77,nrx,msg,unpk77_successvar,options) type(unpack77_context) :: context type(unpack77_effect_policy) :: policy - context=configured_unpack77_context(nrx) + context=configured_unpack77_context(legacy_state_view(),nrx) policy=configured_unpack77_effect_policy(options) call run_unpack77(c77,context,policy,msg,unpk77_successvar) return end subroutine unpack77_configured +subroutine unpack77_configured_for_state(state,c77,nrx,msg,unpk77_successvar,options) + type(pack77_state), target, intent(inout) :: state + character*77 c77 + character*37 msg + integer, intent(in) :: nrx + logical unpk77_successvar + type(unpack77_options), intent(in) :: options + type(unpack77_context) :: context + type(unpack77_effect_policy) :: policy + + context=configured_unpack77_context(owned_state_view(state),nrx) + policy=configured_unpack77_effect_policy(options) + call run_unpack77(c77,context,policy,msg,unpk77_successvar) +end subroutine unpack77_configured_for_state + subroutine run_unpack77(c77,context,policy,msg,unpk77_success) character*77 c77 type(unpack77_context), intent(in) :: context @@ -1491,7 +1893,7 @@ subroutine run_unpack77(c77,context,policy,msg,unpk77_success) decoded=unpack77_core(c77,context) msg=decoded%msg unpk77_success=decoded%success - if(unpk77_success) call apply_unpack77_effects(decoded%effects,policy) + if(unpk77_success) call apply_unpack77_effects(context%store,decoded%effects,policy) return end subroutine run_unpack77 @@ -1573,14 +1975,13 @@ subroutine unpack77_decode_i3_0(c77,context,decoded) n28b=dxpedition_fields%n28b n10=dxpedition_fields%n10 n5=dxpedition_fields%n5 - call record_configured_n28_pair(context,n28a,n28b) irpt=2*n5 - 30 crpt=pack77_format_snr_report(irpt) call unpack28_for_context(context,n28a,call_1,unpk28_success) if(.not.unpk28_success .or. n28a.le.2) decoded%success=.false. call unpack28_for_context(context,n28b,call_2,unpk28_success) if(.not.unpk28_success .or. n28b.le.2) decoded%success=.false. - call hash10(n10,call_3) + call hash10_core(context%store,n10,call_3) if(context%nrx.eq.1) then if(context%dxcall_set .and. len(trim(context%dxcall)).ge.3 .and. & context%hashdx10.eq.n10) then @@ -1612,7 +2013,6 @@ subroutine unpack77_decode_i3_0(c77,context,decoded) intx=field_day_fields%intx nclass=field_day_fields%nclass isec=field_day_fields%isec - call record_configured_n28_pair(context,n28a,n28b) if(isec.gt.PACK77_NSEC .or. isec.lt.1) then decoded%success=.false. isec=1 @@ -1640,7 +2040,7 @@ subroutine unpack77_decode_i3_0(c77,context,decoded) 1007 format(3z6.6) else if(decoded%n3.eq.6) then - select case(pack77_wspr_payload_type(c77)) + select case(pack77_wspr_payload_type(c77,.true.)) case(2) call decode_pack77_wspr_type2(c77,wspr2_fields,ok,.true.) if(.not.ok) then @@ -1739,7 +2139,6 @@ subroutine unpack77_decode_type12(c77,context,decoded) ipb=type12_fields%ipb ir=type12_fields%ir igrid4=type12_fields%igrid4 - call record_configured_n28_pair(context,n28a,n28b) call unpack28_for_context(context,n28a,call_1,unpk28_success) if(context%nrx.eq.1 .and. context%mycall_set .and. & context%hashmy22.eq.(n28a-PACK77_NTOKENS)) then @@ -1773,7 +2172,7 @@ subroutine unpack77_decode_type12(c77,context,decoded) if(.not.unpkg4_success) decoded%success=.false. decoded%msg=pack77_format_exchange_message(call_1,call_2,ir,grid4,.true.) if(decoded%msg(1:3).eq.'CQ ' .and. ir.eq.1) decoded%success=.false. - if(context%strict_var_guards .and. .not.unpack77_type12_var_guard_ok( & + if(context%strict_var_guards .and. .not.pack77_configured_type12_ok( & call_1,call_2,grid4,ir)) decoded%success=.false. else irpt=igrid4-PACK77_MAXGRID4 @@ -1812,7 +2211,6 @@ subroutine unpack77_decode_type3(c77,context,decoded) ir=type3_fields%ir irpt=type3_fields%irpt nexch=type3_fields%nexch - call record_configured_n28_pair(context,n28a,n28b) crpt=pack77_format_rtty_report(irpt) call unpack28_for_context(context,n28a,call_1,unpk28_success) if(.not.unpk28_success) decoded%success=.false. @@ -1859,7 +2257,7 @@ subroutine unpack77_decode_type4(c77,context,decoded) iflip=type4_fields%iflip nrpt=type4_fields%nrpt icq=type4_fields%icq - call hash12(n12,call_3) + call hash12_core(context%store,n12,call_3) if(iflip.eq.0) then ! 12 bit hash for TO call call_1=call_3 call_2=adjustl(c11)//' ' @@ -1885,7 +2283,7 @@ subroutine unpack77_decode_type4(c77,context,decoded) else decoded%msg='CQ '//trim(call_2) endif - if(context%strict_var_guards .and. .not.unpack77_type4_var_guard_ok( & + if(context%strict_var_guards .and. .not.pack77_configured_type4_ok( & call_1,call_2,decoded%msg,iflip,icq,nrpt)) decoded%success=.false. return @@ -1912,9 +2310,9 @@ subroutine unpack77_decode_type5(c77,context,decoded) irpt=type5_fields%irpt iserial=type5_fields%iserial igrid6=type5_fields%igrid6 - call hash12(n12,call_1) + call hash12_core(context%store,n12,call_1) if(n12.eq.context%hashmy12) call_1='<'//trim(context%mycall)//'>' - call hash22(n22,call_2) + call hash22_core(context%store,n22,call_2) cexch=pack77_format_vhf_exchange(irpt,iserial) call to_grid6(igrid6,grid6,decoded%success) decoded%msg=pack77_format_exchange_message(call_1,call_2,ir,cexch//' '//grid6,.true.) @@ -1958,7 +2356,8 @@ subroutine stage_unpack_call(calls,ncalls,c13) return end subroutine stage_unpack_call -subroutine apply_unpack77_effects(effects,policy) +subroutine apply_unpack77_effects(store,effects,policy) + type(pack77_state_view), intent(in) :: store type(unpack77_effects), intent(in) :: effects type(unpack77_effect_policy), intent(in) :: policy integer :: i,n10,n12,n22 @@ -1968,19 +2367,19 @@ subroutine apply_unpack77_effects(effects,policy) if(policy%record_hashes) then do i=1,effects%nhash if(policy%queue_by_thread) then - call queue_hash_call_for_thread(effects%hash_calls(i),policy%nthr_hash) + call queue_hash_call_core(store,effects%hash_calls(i),policy%nthr_hash) else - call save_hash_call(effects%hash_calls(i),n10,n12,n22) + call save_hash_call_core(store,effects%hash_calls(i),n10,n12,n22) endif enddo endif if(policy%record_recent_calls) then do i=1,effects%nrecent if(policy%queue_by_thread) then - call queue_recent_call_for_thread(effects%recent_calls(i), & + call queue_recent_call_core(store,effects%recent_calls(i), & policy%nthr_recent) else - call add_call_to_recent_calls(effects%recent_calls(i)) + call add_call_to_recent_calls_core(store,effects%recent_calls(i)) endif enddo endif @@ -1994,101 +2393,14 @@ subroutine unpack28_for_context(context,n28,c13,success) character*13 c13 logical success - if(context%configured) then - call unpack28_configured(n28,c13,success) - else - call unpack28(n28,c13,success) - endif + call unpack28_core(context%store,n28,c13,success,context%configured) return end subroutine unpack28_for_context -subroutine record_configured_n28_pair(context,n28a,n28b) - type(unpack77_context), intent(in) :: context - integer, intent(in) :: n28a,n28b - - if(.not.context%configured) return - n28a_configured=n28a - n28b_configured=n28b - return -end subroutine record_configured_n28_pair -logical function unpack77_type12_var_guard_ok(call_1,call_2,grid4,ir) result(ok) -! Configured decode rejects a few hash-collision renders that parse as valid -! source messages but cannot round-trip through the configured var encoder. - character(len=*), intent(in) :: call_1,call_2,grid4 - integer, intent(in) :: ir - type(pack77_type12_call_source) :: source - logical :: source_ok - ok=.true. - if(ir.eq.0 .and. call_1(1:1).eq.'<' .and. grid4.ne.'RR73') then - call pack77_parse_type12_call(call_2,.false.,source,source_ok) - if(source_ok .and. source%suffix.eq.PACK77_TYPE12_SUFFIX_R) ok=.false. - endif - - return -end function unpack77_type12_var_guard_ok - -logical function unpack77_type4_var_guard_ok(call_1,call_2,msg,iflip,icq,nrpt) result(ok) -! Type 4 can decode arbitrary 58-bit text as plausible calls; configured var -! mode keeps only renders that also satisfy the source-side Type 4 grammar. - character(len=*), intent(in) :: call_1,call_2,msg - integer, intent(in) :: iflip,icq,nrpt - integer :: nmsglen,indxp,nlencall2,nindxspace - type(pack77_type4_source) :: source - logical :: source_ok - - ok=.true. - call pack77_parse_type4_source(msg,source,source_ok) - if(.not.source_ok) ok=.false. - if(.not.unpack77_type4_call_guard_ok(call_2)) ok=.false. - if(msg(1:3).ne.'CQ ' .and. .not.unpack77_type4_call_guard_ok(call_1)) & - ok=.false. - nmsglen=len_trim(msg) - if(ok .and. nmsglen.gt.0) then - indxp=index(msg,'/P ') - if((icq.eq.0 .and. nrpt.eq.0 .and. (indxp.lt.1 .or. indxp.gt.7)) .or. & - icq.eq.1) then - if(msg(nmsglen:nmsglen).eq.'>') ok=.false. - endif - endif - if(ok .and. iflip.eq.0 .and. icq.eq.0 .and. nrpt.eq.0) then - nlencall2=len_trim(call_2) - if(nlencall2.gt.9) then - if(call_2(1:1).eq.'/' .or. call_2(nlencall2:nlencall2).eq.'/') & - ok=.false. - nindxspace=index(call_2,' ') - if(nindxspace.gt.0 .and. nindxspace.lt.nlencall2) ok=.false. - endif - endif - - return -end function unpack77_type4_var_guard_ok - -logical function unpack77_type4_call_guard_ok(call_text) result(ok) - character(len=*), intent(in) :: call_text - integer :: ispace,islash - - ok=pack77_valid_hash_call_token(call_text) .or. & - pack77_valid_type4_c11(call_text) - if(.not.ok) return - if(pack77_valid_hash_call_token(call_text)) return - if(pack77_is_digit_char(call_text(1:1)) .and. & - pack77_is_digit_char(call_text(2:2))) ok=.false. - if(len_trim(call_text).eq.11) then - ispace=index(call_text,' ') - if(ispace.gt.0 .and. ispace.lt.12) ok=.false. - islash=index(call_text,'/') - if(islash.eq.1 .or. islash.eq.2 .or. islash.eq.11 .or. & - (islash.eq.10 .and. pack77_is_letter_char(call_text(11:11)) .and. & - call_text(11:11).ne.'P')) ok=.false. - if(islash.lt.6 .and. pack77_is_digit_char(call_text(11:11))) ok=.false. - endif - - return -end function unpack77_type4_call_guard_ok subroutine lower_c28_slot(token,allow_auto_hash,n28,hash_facts,ok) character(len=*), intent(in) :: token @@ -2178,16 +2490,6 @@ logical function pack77_field_day_render_fits(source) result(ok) end function pack77_field_day_render_fits -subroutine unpack28_configured(n28_0,c13,success) - integer, intent(in) :: n28_0 - character*13 c13 - logical success - - call unpack28_core(n28_0,c13,success,.true.) - - return -end subroutine unpack28_configured - type(pack77_candidate) function pack77_01_candidate(msg) result(candidate) ! Pack a Type 0.1 message: DXpedition mode diff --git a/lib/77bit/packjt77_grammar.f90 b/lib/77bit/packjt77_grammar.f90 index 7a2616b0..a31d0c46 100644 --- a/lib/77bit/packjt77_grammar.f90 +++ b/lib/77bit/packjt77_grammar.f90 @@ -2,7 +2,7 @@ module packjt77_grammar implicit none - private :: pack77_gate_staged_call_matches + private :: pack77_gate_staged_call_matches,pack77_configured_type4_call_ok integer, parameter :: PACK77_NSEC=86 integer, parameter :: PACK77_NUSCAN=171 @@ -98,6 +98,97 @@ module packjt77_grammar end type pack77_type5_source contains +logical function pack77_exact_free_text_ok(msg) result(ok) + character(len=*), intent(in) :: msg + + ok=.false. + if(len_trim(msg).gt.13) return + ok=pack77_free_text_alphabet_ok(msg(1:len_trim(msg))) +end function pack77_exact_free_text_ok + +logical function pack77_free_text_alphabet_ok(msg) result(ok) + character(len=*), intent(in) :: msg + character(len=42), parameter :: alphabet=' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?' + integer :: i + + ok=.false. + do i=1,len_trim(msg) + if(index(alphabet,msg(i:i)).eq.0) return + enddo + ok=.true. +end function pack77_free_text_alphabet_ok + +logical function pack77_configured_type12_ok(call_1,call_2,grid4,ir) result(ok) +! Reject hash-collision renders that cannot round-trip as configured messages. + character(len=*), intent(in) :: call_1,call_2,grid4 + integer, intent(in) :: ir + type(pack77_type12_call_source) :: source + logical :: source_ok + + ok=.true. + if(ir.eq.0 .and. call_1(1:1).eq.'<' .and. grid4.ne.'RR73') then + call pack77_parse_type12_call(call_2,.false.,source,source_ok) + if(source_ok .and. source%suffix.eq.PACK77_TYPE12_SUFFIX_R) ok=.false. + endif + +end function pack77_configured_type12_ok + +logical function pack77_configured_type4_ok(call_1,call_2,msg,iflip,icq,nrpt) result(ok) +! Configured Type 4 receive policy also requires source-side call grammar. + character(len=*), intent(in) :: call_1,call_2,msg + integer, intent(in) :: iflip,icq,nrpt + integer :: nmsglen,indxp,nlencall2,nindxspace + type(pack77_type4_source) :: source + logical :: source_ok + + ok=.true. + call pack77_parse_type4_source(msg,source,source_ok) + if(.not.source_ok) ok=.false. + if(.not.pack77_configured_type4_call_ok(call_2)) ok=.false. + if(msg(1:3).ne.'CQ ' .and. .not.pack77_configured_type4_call_ok(call_1)) & + ok=.false. + nmsglen=len_trim(msg) + if(ok .and. nmsglen.gt.0) then + indxp=index(msg,'/P ') + if((icq.eq.0 .and. nrpt.eq.0 .and. (indxp.lt.1 .or. indxp.gt.7)) .or. & + icq.eq.1) then + if(msg(nmsglen:nmsglen).eq.'>') ok=.false. + endif + endif + if(ok .and. iflip.eq.0 .and. icq.eq.0 .and. nrpt.eq.0) then + nlencall2=len_trim(call_2) + if(nlencall2.gt.9) then + if(call_2(1:1).eq.'/' .or. call_2(nlencall2:nlencall2).eq.'/') & + ok=.false. + nindxspace=index(call_2,' ') + if(nindxspace.gt.0 .and. nindxspace.lt.nlencall2) ok=.false. + endif + endif + +end function pack77_configured_type4_ok + +logical function pack77_configured_type4_call_ok(call_text) result(ok) + character(len=*), intent(in) :: call_text + integer :: ispace,islash + + ok=pack77_valid_hash_call_token(call_text) .or. & + pack77_valid_type4_c11(call_text) + if(.not.ok) return + if(pack77_valid_hash_call_token(call_text)) return + if(pack77_is_digit_char(call_text(1:1)) .and. & + pack77_is_digit_char(call_text(2:2))) ok=.false. + if(len_trim(call_text).eq.11) then + ispace=index(call_text,' ') + if(ispace.gt.0 .and. ispace.lt.12) ok=.false. + islash=index(call_text,'/') + if(islash.eq.1 .or. islash.eq.2 .or. islash.eq.11 .or. & + (islash.eq.10 .and. pack77_is_letter_char(call_text(11:11)) .and. & + call_text(11:11).ne.'P')) ok=.false. + if(islash.lt.6 .and. pack77_is_digit_char(call_text(11:11))) ok=.false. + endif + +end function pack77_configured_type4_call_ok + integer function pack77_arrl_section_index(section) result(isec) character(len=*), intent(in) :: section integer :: i diff --git a/lib/77bit/packjt77_schema.f90 b/lib/77bit/packjt77_schema.f90 index cfa43687..c61ce8f9 100644 --- a/lib/77bit/packjt77_schema.f90 +++ b/lib/77bit/packjt77_schema.f90 @@ -611,6 +611,36 @@ contains endif end subroutine decode_pack77_tag + integer function pack77_wspr_payload_type(c77,binary_checked) result(wspr_type) + character(len=77), intent(in) :: c77 + logical, intent(in), optional :: binary_checked + type(bit_field) :: selector + integer :: value + logical :: ok + + wspr_type=0 + ok=pack77_binary_precondition(c77,binary_checked) + selector=PACK77_SCHEMA_WSPR_TYPE2%fields(4) + selector%min_value=0_int64 + call get_int(ok,c77,selector,value) + if(.not.ok) return + if(value.eq.1) then + wspr_type=2 + return + endif + + selector=PACK77_SCHEMA_WSPR_TYPE1%fields(4) + selector%max_value=1_int64 + call get_int(ok,c77,selector,value) + if(.not.ok) return + if(value.eq.0) then + wspr_type=1 + else + ! Selector 110 belongs to this dispatch path but fails Type 3 decoding. + wspr_type=3 + endif + end function pack77_wspr_payload_type + subroutine decode_pack77_free_text(c77,fields,ok,binary_checked) character(len=77), intent(in) :: c77 type(pack77_free_text_fields), intent(out) :: fields diff --git a/lib/DecoderWorkerLock.cpp b/lib/DecoderWorkerLock.cpp new file mode 100644 index 00000000..617894af --- /dev/null +++ b/lib/DecoderWorkerLock.cpp @@ -0,0 +1,55 @@ +#include "DecoderWorkerLock.hpp" + +#include <cerrno> +#include <system_error> + +#ifndef _WIN32 +#include <fcntl.h> +#include <sys/file.h> +#include <unistd.h> +#endif + +DecoderWorkerLock::DecoderWorkerLock (char const * path) noexcept +{ +#ifndef _WIN32 + if (!path || !*path) { error_ = EINVAL; return; } + do + { + descriptor_ = open (path, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); + } + while (descriptor_ == -1 && errno == EINTR); + if (descriptor_ == -1) error_ = errno; +#else + (void) path; +#endif +} + +DecoderWorkerLock::~DecoderWorkerLock () +{ +#ifndef _WIN32 + // Keep the inode: unlinking it would let another worker lock a different file. + if (descriptor_ != -1) close (descriptor_); +#endif +} + +bool DecoderWorkerLock::tryLock () noexcept +{ +#ifndef _WIN32 + if (descriptor_ == -1) return false; + int result; + do { result = flock (descriptor_, LOCK_EX | LOCK_NB); } + while (result == -1 && errno == EINTR); + error_ = result == -1 ? errno : 0; +#endif + return error_ == 0; +} + +bool DecoderWorkerLock::busy () const noexcept +{ + return error_ == EWOULDBLOCK || error_ == EAGAIN; +} + +std::string DecoderWorkerLock::errorString () const +{ + return std::system_category ().message (error_); +} diff --git a/lib/DecoderWorkerLock.hpp b/lib/DecoderWorkerLock.hpp new file mode 100644 index 00000000..c5b4e0ab --- /dev/null +++ b/lib/DecoderWorkerLock.hpp @@ -0,0 +1,23 @@ +#ifndef WSJTX_DECODER_WORKER_LOCK_HPP +#define WSJTX_DECODER_WORKER_LOCK_HPP + +#include <string> + +class DecoderWorkerLock final +{ +public: + explicit DecoderWorkerLock (char const * path) noexcept; + ~DecoderWorkerLock (); + DecoderWorkerLock (DecoderWorkerLock const&) = delete; + DecoderWorkerLock& operator= (DecoderWorkerLock const&) = delete; + + bool tryLock () noexcept; + bool busy () const noexcept; + std::string errorString () const; + +private: + int descriptor_ {-1}; + int error_ {0}; +}; + +#endif diff --git a/lib/NativeSharedMemory.cpp b/lib/NativeSharedMemory.cpp new file mode 100644 index 00000000..67250e75 --- /dev/null +++ b/lib/NativeSharedMemory.cpp @@ -0,0 +1,253 @@ +#include "NativeSharedMemory.hpp" + +#include <cstdint> +#include <limits> +#include <system_error> + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#else +#include <cerrno> +#include <fcntl.h> +#include <sys/mman.h> +#include <sys/stat.h> +#include <unistd.h> +#endif + +namespace +{ + bool valid_name (std::string const& name) + { +#ifdef _WIN32 + std::string const prefix {"Local\\wsjt-"}; +#else + std::string const prefix {"/wsjt-"}; +#endif + if (name.size () != prefix.size () + 24 + || name.compare (0, prefix.size (), prefix) != 0) return false; + for (auto i = prefix.size (); i < name.size (); ++i) + if (!((name[i] >= '0' && name[i] <= '9') + || (name[i] >= 'a' && name[i] <= 'f'))) return false; + return true; + } + + std::string native_error (char const * operation, unsigned long code) + { + if (!operation) return {}; + return std::string {operation} + ": " + + std::system_category ().message (static_cast<int> (code)) + + " (" + std::to_string (code) + ")"; + } +} + +NativeSharedMemory::~NativeSharedMemory () +{ + detach (); +} + +bool NativeSharedMemory::fail (char const * operation, unsigned long code) noexcept +{ + operation_ = operation; + error_ = code; + return false; +} + +bool NativeSharedMemory::begin (std::string const& name) +{ +#ifdef _WIN32 + if (data_ || handle_) return fail ("shared memory already attached", ERROR_BUSY); + if (!valid_name (name)) return fail ("invalid shared memory name", ERROR_INVALID_NAME); +#else + if (data_ || descriptor_ != -1) return fail ("shared memory already attached", EBUSY); + if (!valid_name (name)) return fail ("invalid shared memory name", EINVAL); +#endif + name_ = name; + operation_ = nullptr; + error_ = 0; + return true; +} + +bool NativeSharedMemory::create (std::string const& name, std::size_t bytes) +{ + if (!begin (name)) return false; +#ifdef _WIN32 + if (!bytes) return fail ("invalid shared memory size", ERROR_INVALID_PARAMETER); + std::wstring const wide_name {name.begin (), name.end ()}; + auto const length = static_cast<std::uint64_t> (bytes); + handle_ = CreateFileMappingW (INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, + static_cast<DWORD> (length >> 32), + static_cast<DWORD> (length), wide_name.c_str ()); + auto const error = GetLastError (); + if (!handle_) return fail ("CreateFileMappingW", error); + if (error == ERROR_ALREADY_EXISTS) + { + CloseHandle (handle_); + handle_ = nullptr; + return fail ("CreateFileMappingW", error); + } + data_ = MapViewOfFile (handle_, FILE_MAP_ALL_ACCESS, 0, 0, bytes); + if (!data_) + { + auto const map_error = GetLastError (); + detach (); + return fail ("MapViewOfFile", map_error); + } +#else + if (!bytes || bytes > static_cast<std::uintmax_t> (std::numeric_limits<off_t>::max ())) + return fail ("invalid shared memory size", EINVAL); + descriptor_ = shm_open (name.c_str (), O_RDWR | O_CREAT | O_EXCL, 0600); + if (descriptor_ == -1) return fail ("shm_open (create)", errno); + owner_ = true; + if (ftruncate (descriptor_, static_cast<off_t> (bytes)) == -1) + { + auto const error = errno; + detach (); + return fail ("ftruncate", error); + } +#ifdef __linux__ + int allocation_error; + do { allocation_error = posix_fallocate (descriptor_, 0, static_cast<off_t> (bytes)); } + while (allocation_error == EINTR); + if (allocation_error) + { + detach (); + return fail ("posix_fallocate", allocation_error); + } +#endif + auto * address = mmap (nullptr, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, descriptor_, 0); + if (address == MAP_FAILED) + { + auto const error = errno; + detach (); + return fail ("mmap", error); + } + data_ = address; +#endif + size_ = bytes; + owner_ = true; + return true; +} + +bool NativeSharedMemory::attach (std::string const& name) +{ + if (!begin (name)) return false; +#ifdef _WIN32 + std::wstring const wide_name {name.begin (), name.end ()}; + handle_ = OpenFileMappingW (FILE_MAP_ALL_ACCESS, FALSE, wide_name.c_str ()); + if (!handle_) return fail ("OpenFileMappingW", GetLastError ()); + data_ = MapViewOfFile (handle_, FILE_MAP_ALL_ACCESS, 0, 0, 0); + if (!data_) + { + auto const error = GetLastError (); + detach (); + return fail ("MapViewOfFile", error); + } + MEMORY_BASIC_INFORMATION information {}; + if (!VirtualQuery (data_, &information, sizeof information)) + { + auto const error = GetLastError (); + detach (); + return fail ("VirtualQuery", error); + } + size_ = information.RegionSize; +#else + descriptor_ = shm_open (name.c_str (), O_RDWR, 0); + if (descriptor_ == -1) return fail ("shm_open (attach)", errno); + struct stat information {}; + if (fstat (descriptor_, &information) == -1) + { + auto const error = errno; + detach (); + return fail ("fstat", error); + } + if (information.st_size <= 0 + || static_cast<std::uintmax_t> (information.st_size) > std::numeric_limits<std::size_t>::max ()) + { + detach (); + return fail ("invalid shared memory size", EINVAL); + } + auto const bytes = static_cast<std::size_t> (information.st_size); + auto * address = mmap (nullptr, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, descriptor_, 0); + if (address == MAP_FAILED) + { + auto const error = errno; + detach (); + return fail ("mmap", error); + } + data_ = address; + size_ = bytes; +#endif + return true; +} + +bool NativeSharedMemory::detach () noexcept +{ + char const * operation {nullptr}; + unsigned long error {0}; + auto remember = [&] (char const * failed_operation, unsigned long code) + { + if (!operation) { operation = failed_operation; error = code; } + }; +#ifdef _WIN32 + if (data_ && !UnmapViewOfFile (data_)) remember ("UnmapViewOfFile", GetLastError ()); + if (handle_ && !CloseHandle (handle_)) remember ("CloseHandle", GetLastError ()); + handle_ = nullptr; +#else + // The GUI instance lock serializes owner cleanup and stale-name replacement. + if (owner_ && shm_unlink (name_.c_str ()) == -1 && errno != ENOENT) + remember ("shm_unlink", errno); + if (data_ && munmap (data_, size_) == -1) remember ("munmap", errno); + if (descriptor_ != -1 && close (descriptor_) == -1) remember ("close", errno); + descriptor_ = -1; +#endif + data_ = nullptr; + size_ = 0; + owner_ = false; + if (operation) return fail (operation, error); + return true; +} + +bool NativeSharedMemory::remove (std::string const& name, std::string * error) +{ + if (error) error->clear (); +#ifdef _WIN32 + (void) name; + if (error) *error = "Windows shared memory is retired when its last handle closes"; + return false; +#else + if (!valid_name (name)) + { + if (error) *error = native_error ("invalid shared memory name", EINVAL); + return false; + } + if (shm_unlink (name.c_str ()) == 0 || errno == ENOENT) return true; + if (error) *error = native_error ("shm_unlink", errno); + return false; +#endif +} + +bool NativeSharedMemory::alreadyExists () const noexcept +{ +#ifdef _WIN32 + return error_ == ERROR_ALREADY_EXISTS; +#else + return error_ == EEXIST; +#endif +} + +bool NativeSharedMemory::notFound () const noexcept +{ +#ifdef _WIN32 + return error_ == ERROR_FILE_NOT_FOUND; +#else + return error_ == ENOENT; +#endif +} + +std::string NativeSharedMemory::errorString () const +{ + return native_error (operation_, error_); +} diff --git a/lib/NativeSharedMemory.hpp b/lib/NativeSharedMemory.hpp new file mode 100644 index 00000000..7c8d25b5 --- /dev/null +++ b/lib/NativeSharedMemory.hpp @@ -0,0 +1,44 @@ +#ifndef WSJTX_NATIVE_SHARED_MEMORY_HPP +#define WSJTX_NATIVE_SHARED_MEMORY_HPP + +#include <cstddef> +#include <string> + +class NativeSharedMemory final +{ +public: + NativeSharedMemory () = default; + ~NativeSharedMemory (); + NativeSharedMemory (NativeSharedMemory const&) = delete; + NativeSharedMemory& operator= (NativeSharedMemory const&) = delete; + + bool create (std::string const& name, std::size_t bytes); + bool attach (std::string const& name); + bool detach () noexcept; + static bool remove (std::string const& name, std::string * error = nullptr); + + void * data () const noexcept { return data_; } + std::size_t size () const noexcept { return size_; } + bool isAttached () const noexcept { return data_ != nullptr; } + bool alreadyExists () const noexcept; + bool notFound () const noexcept; + std::string errorString () const; + +private: + bool begin (std::string const& name); + bool fail (char const * operation, unsigned long code) noexcept; + + std::string name_; + void * data_ {nullptr}; + std::size_t size_ {0}; + bool owner_ {false}; + char const * operation_ {nullptr}; + unsigned long error_ {0}; +#ifdef _WIN32 + void * handle_ {nullptr}; +#else + int descriptor_ {-1}; +#endif +}; + +#endif diff --git a/lib/afc65b.f90 b/lib/afc65b.f90 index 18bbb691..d006e222 100644 --- a/lib/afc65b.f90 +++ b/lib/afc65b.f90 @@ -2,9 +2,14 @@ subroutine afc65b(cx,npts,fsample,nflip,mode65,a,ccfbest,dtbest) ! Find delta f, f1, f2 ==> a(1:3) + use jt65_mod, only: jt65_work,ensure_jt65_workspace + complex cx(npts) real a(5),deltaa(5) + call ensure_jt65_workspace() + jt65_work%afc_valid=.false. + dtmax=0. a=0. a1=0. a2=0. @@ -57,7 +62,10 @@ subroutine afc65b(cx,npts,fsample,nflip,mode65,a,ccfbest,dtbest) delta=deltaa(j) 10 a(j)=a(j)+delta chisq2=fchisq65(cx,npts,fsample,nflip,a,ccfmax,dtmax) - if(chisq2.eq.chisq1) go to 10 + if(chisq2.eq.chisq1) then + a(j)=a(j)-delta + cycle + endif if(chisq2.gt.chisq1) then delta=-delta !Reverse direction a(j)=a(j)+delta @@ -75,13 +83,18 @@ subroutine afc65b(cx,npts,fsample,nflip,mode65,a,ccfbest,dtbest) endif ! Find minimum of parabola defined by last three points - delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) + if(chisq3.eq.chisq2) then + delta=0.5*delta + else + delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) + endif a(j)=a(j)-delta deltaa(j)=deltaa(j)*fn/3. ! write(*,4000) iter,j,a(1:2),-chisq2 !4000 format(2i2,4f9.4) enddo chisqr=fchisq65(cx,npts,fsample,nflip,a,ccfmax,dtmax) + if(chisqr0==0.) exit fdiff=chisqr/chisqr0-1.0 ! write(*,4000) 0,0,a(1:2),-chisqr,fdiff if(abs(fdiff).lt.0.0001) exit diff --git a/lib/astro.f90 b/lib/astro.f90 index cb44433d..62b6337f 100644 --- a/lib/astro.f90 +++ b/lib/astro.f90 @@ -1,7 +1,8 @@ subroutine astro(nyear,month,nday,uth,freq8,Mygrid, & NStation,MoonDX,AzSun,ElSun,AzMoon0,ElMoon0, & ntsky,doppler00,doppler,dbMoon,RAMoon,DecMoon,HA,Dgrd,sd, & - poloffset,xnr,day,lon,lat,LST,techo,ephemeris_result) + poloffset,xnr,day,lon,lat,LST,techo,ephemeris_result, & + use_home_coordinates,home_latitude,home_longitude) use jpl_ephemeris_status, only: EPHEMERIS_INVALID_INPUT, & EPHEMERIS_UNAVAILABLE @@ -9,7 +10,8 @@ subroutine astro(nyear,month,nday,uth,freq8,Mygrid, & ! NB: may want to smooth the Tsky map to 10 degrees or so. character*6 MyGrid,HisGrid - real*8 freq8 + real*8 freq8,home_longitude,home_latitude + logical use_home_coordinates real LST real lat,lon integer ephemeris_result @@ -42,6 +44,10 @@ subroutine astro(nyear,month,nday,uth,freq8,Mygrid, & call grid2deg(MyGrid,elon,lat) lon=-elon + if (use_home_coordinates) then + lon=home_longitude + lat=home_latitude + endif call sun(nyear,month,nday,uth,lon,lat,RASun,DecSun,LST, & AzSun,ElSun,mjd,day) diff --git a/lib/astro0.f90 b/lib/astro0.f90 index 207aa6a4..9e26bf5b 100644 --- a/lib/astro0.f90 +++ b/lib/astro0.f90 @@ -1,4 +1,5 @@ subroutine astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, & + use_home_coordinates,home_latitude,home_longitude, & AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & width1,width2,xlst8,techo8,ephemeris_result) @@ -12,7 +13,8 @@ subroutine astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, & real*8 AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8 real*8 dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,xnr8,dfdt,dfdt0,dt real*8 sd8,poloffset8,width1,width2,xlst8 - real*8 uth8,techo8,freq8 + real*8 uth8,techo8,freq8,home_latitude,home_longitude + logical use_home_coordinates real*8 xl,b integer ephemeris_result,result_dx,result_self,last_result integer last_reader_generation @@ -33,7 +35,7 @@ subroutine astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, & call astro(nyear,month,nday,uth,freq8,hisgrid_calc,2,1, & AzSun,ElSun,AzMoon,ElMoon,ntsky,doppler00,doppler, & dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, & - day,xlon2,xlat2,xlst,techo,result_dx) + day,xlon2,xlat2,xlst,techo,result_dx,.false.,0.d0,0.d0) if(result_dx.eq.EPHEMERIS_INVALID_INPUT .or. & result_dx.eq.EPHEMERIS_UNAVAILABLE) then ephemeris_result=result_dx @@ -48,7 +50,8 @@ subroutine astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, & call astro(nyear,month,nday,uth,freq8,mygrid_calc,1,1, & AzSun,ElSun,AzMoon,ElMoon,ntsky,doppler00,doppler, & dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, & - day,xlon1,xlat1,xlst,techo,result_self) + day,xlon1,xlat1,xlst,techo,result_self,use_home_coordinates, & + home_latitude,home_longitude) if(result_self.eq.EPHEMERIS_INVALID_INPUT .or. & result_self.eq.EPHEMERIS_UNAVAILABLE) then ephemeris_result=result_self diff --git a/lib/astrosub.f90 b/lib/astrosub.f90 index 35437cc2..a2d627ad 100644 --- a/lib/astrosub.f90 +++ b/lib/astrosub.f90 @@ -10,7 +10,8 @@ module astro_module contains subroutine astrosub(nyear,month,nday,uth8,freq8,mygrid_cp, & - hisgrid_cp,AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8, & + hisgrid_cp,use_home_coordinates,home_latitude,home_longitude, & + AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8, & ntsky,ndop,ndop00,RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8,extraazel, & techo8,width1,width2,bTx,AzElFileName_cp,jpleph_file_name_cp, & ephemeris_result) & @@ -23,8 +24,8 @@ contains C_string_value, assignment(=) integer(C_int), intent(in), value :: nyear, month, nday - logical(C_bool), intent(in), value :: extraazel - real(C_double), intent(in), value :: uth8, freq8 + logical(C_bool), intent(in), value :: extraazel, use_home_coordinates + real(C_double), intent(in), value :: uth8, freq8, home_latitude, home_longitude real(C_double), intent(out) :: AzSun8, ElSun8, AzMoon8, ElMoon8, AzMoonB8, & ElMoonB8, Ramoon8, DecMoon8, Dgrd8, poloffset8, xnr8, techo8, width1, & width2 @@ -34,6 +35,7 @@ contains jpleph_file_name_cp character(len=6) :: mygrid, hisgrid + logical :: use_home_coordinates_f character(len=:), allocatable :: AzElFileName character(len=1) :: c1 character(len=32) :: envvar @@ -50,9 +52,11 @@ contains mygrid = mygrid_cp hisgrid = hisgrid_cp + use_home_coordinates_f = use_home_coordinates AzElFileName = C_string_value (AzElFileName_cp) jpleph_file_name = jpleph_file_name_cp call astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, & + use_home_coordinates_f,home_latitude,home_longitude, & AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & width1,width2,xlst8,techo8,ephemeris_result) diff --git a/lib/blanker.f90 b/lib/blanker.f90 index ec94f0df..52c14a7e 100644 --- a/lib/blanker.f90 +++ b/lib/blanker.f90 @@ -1,31 +1,31 @@ -subroutine blanker(iwave,nz,ndropmax,npct,c_bigfft) +subroutine blanker(iwave,nz,ndropmax,npct,c_bigfft,hist) - integer*2 iwave(nz) + integer*2, intent(in) :: iwave(nz) complex c_bigfft(0:nz/2) - integer hist(0:32768) + integer, intent(inout) :: hist(0:32768) real fblank !Fraction of points to be blanked - save hist - fblank=0.01*npct - hist=0 - do i=1,nz -! ### NB: if iwave(i)=-32768, abs(iwave(i))=-32768 ### - if(iwave(i).eq.-32768) iwave(i)=-32767 - n=abs(iwave(i)) - hist(n)=hist(n)+1 - enddo - n=0 - do i=32768,0,-1 - n=n+hist(i) - if(n.ge.nint(nz*fblank/ndropmax)) exit - enddo - nthresh=i + nthresh=32768 + if(npct>0) then + fblank=0.01*npct + hist=0 + do i=1,nz + n=abs(max(-32767,int(iwave(i)))) + hist(n)=hist(n)+1 + enddo + n=0 + do i=32768,0,-1 + n=n+hist(i) + if(n.ge.nint(nz*fblank/ndropmax)) exit + enddo + nthresh=i + endif ndrop=0 ndropped=0 xx=0. do i=1,nz - i0=iwave(i) + i0=max(-32767,int(iwave(i))) if(ndrop.gt.0) then i0=0 ndropped=ndropped+1 diff --git a/lib/decode65a.f90 b/lib/decode65a.f90 index be2f84c8..27b4f022 100644 --- a/lib/decode65a.f90 +++ b/lib/decode65a.f90 @@ -9,9 +9,6 @@ subroutine decode65a(dd,npts,newdat,nqd,f0,nflip,mode65,ntrials, & parameter (NMAX=60*12000) !Samples per 60 s real*4 dd(NMAX) !92 MB: raw data from Linrad timf2 - complex cx(NMAX/8) !Data at 1378.125 sps - complex cx1(NMAX/8) !Data at 1378.125 sps, offset by 355.3 Hz - complex c5x(NMAX/32) !Data at 344.53125 Hz complex c5a(512) real s2(66,126) real a(5) @@ -22,11 +19,21 @@ subroutine decode65a(dd,npts,newdat,nqd,f0,nflip,mode65,ntrials, & data first/.true./,jjjmin/1000/,jjjmax/-1000/,cr/'(C) 2016, Joe Taylor - K1JT'/ save + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%cx)) allocate(jt65_work%cx(NMAX/8),jt65_work%cx1(NMAX/8),jt65_work%c5x(NMAX/32)) + associate(cx=>jt65_work%cx,cx1=>jt65_work%cx1,c5x=>jt65_work%c5x) + a=0. + qual=0. + sync2=0. + nhist=0 + nsmo=0 + decoded='' ! Mix sync tone to baseband, low-pass filter, downsample to 1378.125 Hz call timer('filbig ',0) call filbig(dd,npts,f0,newdat,cx,n5,sq0) if(mode65.eq.4) call filbig(dd,npts,f0+355.297852,newdat,cx1,n5,sq0) call timer('filbig ',1) + if(sq0<=0.) go to 900 ! NB: cx has sample rate 12000*77125/672000 = 1378.125 Hz ! Check for a shorthand message @@ -53,7 +60,7 @@ subroutine decode65a(dd,npts,newdat,nqd,f0,nflip,mode65,ntrials, & dtbest=dtbest+0.003628 !Remove decimation filter and coh. integrator delay dt=dtbest !Return new, improved estimate of dt sync2=3.7e-4*ccfbest/sq0 !Constant is empirical - if(mode65.eq.4) cx=cx1 + if(mode65.eq.4) cx(:n5)=cx1(:n5) ! Apply AFC corrections to the time-domain signal ! Now we are back to using the 1378.125 Hz sample rate, enough to @@ -71,7 +78,7 @@ subroutine decode65a(dd,npts,newdat,nqd,f0,nflip,mode65,ntrials, & do k=1,nsym do i=1,nfft j=j+1 - if(j.ge.1 .and. j.le.NMAX/8) then + if(j.ge.1 .and. j.le.n5) then c5a(i)=cx(j) else c5a(i)=0. @@ -150,5 +157,7 @@ subroutine decode65a(dd,npts,newdat,nqd,f0,nflip,mode65,ntrials, & call timer('dec65b ',1) -900 return +900 continue + end associate + return end subroutine decode65a diff --git a/lib/decode9w.f90 b/lib/decode9w.f90 index 2c043c72..f9a681eb 100644 --- a/lib/decode9w.f90 +++ b/lib/decode9w.f90 @@ -1,4 +1,4 @@ -subroutine decode9w(nfqso,ntol,nsubmode,ss,id2,sync,nsnr,xdt1,f0,decoded) +subroutine decode9w(nfqso,ntol,nsubmode,ss,nzhsym,id2,sync,nsnr,xdt1,f0,decoded) ! Decode a weak signal in a wide/slow JT9 submode. @@ -9,26 +9,44 @@ subroutine decode9w(nfqso,ntol,nsubmode,ss,id2,sync,nsnr,xdt1,f0,decoded) real a(5) !Fitted Lorentzian params integer*2 id2(NZMAX) !Raw 16-bit data integer*1 i1SoftSymbols(207) !Binary soft symbols + logical :: valid,narrow character*22 decoded !Decoded message + decoded=' ' + sync=0. + nsnr=-99 + xdt1=0. + f0=nfqso + df=12000.0/16384.0 !Bin spacing in ss() nsps=6912 !Samples per 9-FSK symbol tstep=nsps*0.5/12000.0 !Half-symbol duration npts=52*12000 limit=10000 !Fano timeout parameter - ia=max(1,nint((nfqso-ntol)/df)) !Start frequency bin - ib=min(NSMAX,nint((nfqso+ntol)/df)) !End frequency bin + ia=max(1,nint((nfqso-ntol)/df)+1) !Start frequency bin + ib=min(NSMAX,nint((nfqso+ntol)/df)+1) !End frequency bin + if(ib.lt.ia) return + narrow=ib-ia+1.lt.20 + ifita=ia + ifitb=ib + if(narrow) then + ! Fit both 20-bin baseline flanks without widening candidate selection. + ifita=max(1,min(NSMAX-40,nint(nfqso/df)+1-20)) + ifitb=ifita+40 + endif lag1=-int(2.5/tstep + 0.9999) !Start lag lag2=int(5.0/tstep + 0.9999) !End lag - nhsym=184 !Number of half-symbols + nhsym=max(0,min(184,nzhsym)) + if(nhsym.eq.0) return ! First sync pass finds approximate Doppler spread; second pass does a ! good Lorentzian fit to determine frequency f0. do iter=1,2 nadd=3 if(iter.eq.2) nadd=2*nint(0.375*a(4)) + 1 - call sync9w(ss,nhsym,lag1,lag2,ia,ib,ccfred,ccfblue,ipk,lagpk,nadd) + call sync9w(ss,nhsym,lag1,lag2,ifita,ifitb,ia,ib,ccfred,ccfblue,ipk,lagpk,nadd) + if(ipk.eq.0) return s=0. sq=0. ns=0 @@ -40,15 +58,19 @@ subroutine decode9w(nfqso,ntol,nsubmode,ss,id2,sync,nsnr,xdt1,f0,decoded) endif enddo base=s/ns - rms=sqrt(sq/ns - base**2) + rms=sqrt(max(0.,sq/ns - base**2)) + if(rms.le.0.) return sync=(ccfblue(lagpk)-base)/rms xdt0=lagpk*tstep - call lorentzian(ccfred(ia),ib-ia+1,a) - f0=(ia+a(3))*df + call lorentzian(ccfred(ifita),ifitb-ifita+1,a) + f0=(ifita+a(3)-2)*df enddo + if(narrow .and. abs(f0-nfqso).gt.ntol) return ccfblue=(ccfblue-base)/rms - call softsym9w(id2,npts,xdt0,f0,a(4)*df,nsubmode,xdt1-1.05,snrdb,i1softsymbols) + call softsym9w(id2,npts,xdt0,f0,a(4)*df,nsubmode,xdt1,snrdb,i1softsymbols,valid) + if(.not.valid) return + xdt1=xdt1-1.05 nsnr=nint(snrdb) call jt9fano(i1softsymbols,limit,nlim,decoded) diff --git a/lib/decoder.f90 b/lib/decoder.f90 index d588ffa5..4bcbe87f 100644 --- a/lib/decoder.f90 +++ b/lib/decoder.f90 @@ -5,34 +5,17 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen use timer_module, only: timer use jt4_decode use jt65_decode + use jt65_host_support, only: load_jt65_calls use jt9_decode - use ft8_decode - use ft8_decode_ranges, only: max_ft8_decode_ranges, partition_ft8_decode_range - use ft8_mtd_residual, only: mtd_prepare,mtd_finish,mtd_worker_residual, & - mtd_worker_spectrum - use ft8_decodevar - use ft4_decode - use fst4_decode - use q65_decode use decoder_callbacks, only: decoder_callback_context, & counting_jt4_decoder, counting_jt65_decoder, counting_jt9_decoder, & - counting_ft8_decoder, counting_ft8_decodervar, counting_ft4_decoder, & - counting_fst4_decoder, counting_q65_decoder, ft8_decodedvar, & - ft8_decoded, ft4_decoded, fst4_decoded, q65_decoded, jt4_decoded, & + jt4_decoded, & jt4_average, jt65_decoded, jt9_decoded use streaming_emit, only: streaming_emit_enabled, & streaming_emit_decode use decode_completion_module, only: decode_completion_result, & reset_decode_completion, set_decode_completion, write_decode_progress -!ft8md added 3 uses below - use ft8_mod1, only : ndecodes,allmessages,allsnrs,allfreq,mycall12_0, & - mycall12_00,hiscall12_0,nmsg,odd,even,oddcopy,evencopy,nlasttx, & - lqsomsgdcd,mycalllen1,msgroot,msgrootlen,lapmyc,sumxdtt,avexdt, & - nfawide,nfbwide,mycall,hiscall,lhound,mybcall,hisbcall,lenabledxcsearch, & - lwidedxcsearch,hisgrid4,lmultinst,dd8,nft8cycles,lskiptx1,ncandallthr, & - nincallthr,incall,msgincall,xdtincall,maskincallthr,ltxing,hisgrid, & - lastrxmsg,lasthcall include 'jt9com.f90' @@ -47,43 +30,36 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen end subroutine wsjt_tsan_release_decoder_section_secondary end interface - logical first,firstsd !ft8md - logical(1) lhoundprev !ft8md - integer nutc,ndelay - integer :: ft8_range_low(max_ft8_decode_ranges) - integer :: ft8_range_high(max_ft8_decode_ranges) - integer :: ft8_range_count - integer :: requested_threads - integer :: nthr integer, intent(in) :: progress_generation integer :: active_progress_generation type(params_block) :: params type(decode_completion_result), intent(out) :: completion + external :: run_decoder_engine type(decoder_callback_context) :: callback_context - data ndelay/0/ - data first/.true./ !ft8md - data firstsd/.true./ !ft8md - data lhoundprev/.false./ !ft8md real ss(184,NSMAX) - logical baddata,newdat65,newdat9,single_decode,bVHF,q65_pileup,bad0,newdat,ex - logical lprinthash22 + logical baddata,newdat65,newdat9,bVHF,bad0,ex integer*2 id2(NTMAX*12000) - integer nqf(20) real*4 dd(NTMAX*12000) character(len=20) :: datetime - !character(len=12) :: mycall, hiscall !ft8md - character(len=6) :: mygrid!, hisgrid !ft8md + character(len=12) :: mycall, hiscall + character(len=6) :: mygrid, hisgrid character*60 line - data ndec8/0/,ntr0/-1/ + character(len=12), allocatable :: jt65_calls(:) + character(len=4), allocatable :: jt65_grids(:) + data ntr0/-1/ save type(counting_jt4_decoder) :: my_jt4 type(counting_jt65_decoder) :: my_jt65 type(counting_jt9_decoder) :: my_jt9 - type(counting_ft8_decoder) :: my_ft8 - type(counting_ft8_decodervar) :: my_ft8var - type(counting_ft4_decoder) :: my_ft4 - type(counting_fst4_decoder) :: my_fst4 - type(counting_q65_decoder) :: my_q65 + + if(params%nmode.eq.8.or.params%nmode.eq.5.or.params%nmode.eq.9.or.params%nmode.eq.65.or. & + params%nmode.eq.66.or.params%nmode.eq.240.or.params%nmode.eq.241.or.params%nmode.eq.242) then + call run_decoder_engine(id2,params,nfsample,completion,progress_generation, & + 0_c_int64_t,0_c_int64_t,0_c_int, & + merge(params%kin,0_c_int,params%nmode==5.or.params%nmode==9.or.params%nmode==65.or.params%nmode==66.or. & + params%nmode==240.or.params%nmode==241.or.params%nmode==242)) + return + endif call reset_decode_completion(completion) active_progress_generation=progress_generation @@ -91,13 +67,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen my_jt4%decoded = 0 my_jt65%decoded = 0 my_jt9%decoded = 0 - my_ft8%decoded = 0 - my_ft8var%decodedvar = 0 - my_ft8var%callback => ft8_decodedvar !Set once in serial init; avoids racing writes in decodevar - my_ft4%decoded = 0 - my_fst4%decoded = 0 - my_q65%decoded = 0 - my_ft8var%xdtt=0. nsynced=0 navg0=0 @@ -109,18 +78,9 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen ! Cast C character arrays to Fortran character strings datetime=transfer(params%datetime, datetime) mycall=transfer(params%mycall,mycall) - mybcall=transfer(params%mybcall,mybcall) hiscall=transfer(params%hiscall,hiscall) - hisbcall=transfer(params%hisbcall,hisbcall) mygrid=transfer(params%mygrid,mygrid) hisgrid=transfer(params%hisgrid,hisgrid) - hisgrid4=hisgrid(1:4) - - ncandall=0 !ft8md - ncandallthr=0 !ft8md - -! FT8 defaults at start to enable a8 decoding - if(params%nzhsym.eq.41 .or. params%lmultift8) ltry_a8=.true. ! For testing only: return Rx messages stored in a file as decodes inquire(file='rx_messages.txt',exist=ex) @@ -138,9 +98,7 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen endif ncontest=iand(params%nexp_decode,7) - single_decode=iand(params%nexp_decode,32).ne.0 bVHF=iand(params%nexp_decode,64).ne.0 - q65_pileup=iand(params%nexp_decode,128).ne.0 ! bit 7 is reserved for Q65 Pileup if(mod(params%nranera,2).eq.0) ntrials=10**(params%nranera/2) if(mod(params%nranera,2).eq.1) ntrials=3*10**(params%nranera/2) if(params%nranera.eq.0) ntrials=0 @@ -170,452 +128,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen my_jt4%context = callback_context my_jt65%context = callback_context my_jt9%context = callback_context - my_ft8%context = callback_context - my_ft8var%context = callback_context - my_ft4%context = callback_context - my_fst4%context = callback_context - my_q65%context = callback_context - - if(params%nmode.eq.8) then - ! We're in FT8 mode - if(ncontest.eq.6) then !Fox=6, Hound=7 - ! Fox mode: initialize and open houndcallers.txt - inquire(file=trim(temp_dir)//'/houndcallers.txt',exist=ex) - if(.not.ex) then - c2fox=' ' - g2fox=' ' - nsnrfox=-99 - nfreqfox=-99 - n30z=0 - nwrap=0 - nfox=0 - endif - open(19,file=trim(temp_dir)//'/houndcallers.txt',status='unknown') - endif - - if(ncontest.eq.7 .and. params%b_superfox .and. params%b_even_seq) then - if(params%nzhsym.lt.50) go to 800 - ! Call the superFox decoder - call sfrx_sub(params%yymmdd,params%nutc,params%nfqso,params%ntol,id2) - else - call timer('decft8 ',0) - if(params%nfa.gt.params%nfb) then - call timer('decft8 ',1) - go to 800 - endif - newdat=params%newdat - if(params%emedelay.ne.0.0) then - id2(1:156000)=id2(24001:180000) ! Drop the first 2 seconds of data - id2(156001:180000)=0 - endif - -! ft8md below - if(params%lmultift8 .and. params%nmode.eq.8) then - if(params%lmodechanged) then - avexdt=0. - nintcount=3 - endif ! avexdt fast track in FT8 after mode change - - if(.not.params%nagain) ndelay=params%ndelay - lqsomsgdcd=.false. - if(ndelay.gt.0) then ! received incomplete interval - call partintft8(ndelay,params%nutc) - lqsomsgdcd=.true. - endif - ntrials=params%nranera - if(params%nsecbandchanged.gt.0) then - nsamplesdel=params%nsecbandchanged*12000 - if(params%nsecbandchanged.gt.14) then - dd8=0. ! protection - else - dd8(1:nsamplesdel)=0. - endif - endif - - if(.not.params%nagain) nutc=params%nutc - - if(first) then - call cwfilter(first) - first=.false. - endif ! + ALLCALL to memory - lenabledxcsearch=params%lenabledxcsearch - lwidedxcsearch=params%lwidedxcsearch - - lmultinst=params%lmultinst - lskiptx1=params%lskiptx1 - ltxing=params%ltxing - - mycalllen1=len_trim(mycall)+1 - msgroot='' - msgroot=trim(mycall)//' '//trim(hiscall)//' ' - msgrootlen=len_trim(msgroot) - lhound=params%lhound - nft8cycles=params%nft8cycles - forcedt=0. - - if((hiscall.ne.hiscall12_0 .and. hiscall.ne.' ') & - .or. (mycall.ne.mycall12_0 .and. mycall.ne.' ') .or. & - (lhound.neqv.lhoundprev)) then - if(hiscall.ne.' ') then - call tone8(params%lmycallstd,params%lhiscallstd) - hiscall12_0=hiscall - mycall12_0=mycall - endif - lhoundprev=lhound - endif - if(params%lmycallstd .and. mycall.ne.' ' .and. & - mycall12_00.ne.mycall) then - call tone8myc() - mycall12_00=mycall - endif - - ndecodes=0 !Initialize arrays for multi-threaded decoding - allmessages="" - allsnrs=0 - allfreq=0. - numcores=1 -!$ numcores=omp_get_num_procs() - nuserthr=params%nmt - - numthreads=1 ! fallback - if(nuserthr.eq.0) then ! auto - if(numcores.eq.1) then - numthreads=1 - else if(numcores.gt.1 .and. numcores.lt.5) then - numthreads=numcores-1 - else if(numcores.gt.4 .and. numcores.lt.9) then - numthreads=numcores-2 - else if(numcores.gt.8 .and. numcores.lt.16) then - numthreads=numcores-3 - else - numthreads=12 - endif - else if(nuserthr.gt.0 .and. nuserthr.lt.13) then - ! number of threads shall not exceed number of logical cores - if(numcores.ge.nuserthr) then - numthreads=nuserthr - else - numthreads=numcores - endif - endif - -!$ call omp_set_dynamic(.false.) -!$ call omp_set_max_active_levels(omp_get_supported_active_levels()) - - nfa=params%nfa - nfb=params%nfb - nfqso=params%nfqso - nfawide=params%nfa - nfbwide=params%nfb - - if(params%nagainfil) then - if(nfqso.lt.nfa .or. nfqso.gt.nfb) then - write(*,64) nutc,'nfqso is out of bandwidth','d' -64 format(i6.6,2x,a25,16x,a1) - go to 800 - endif - nfa=max(nfa,nfqso-25) ! 50Hz bandwidth for decode via double click - nfb=min(nfb,nfqso+25) - numthreads=min(4,numthreads) -! To do: withdraw limitation when threads are in sync at main passes? - endif - - call partition_ft8_decode_range(nfa,nfb,numthreads,ft8_range_low, & - ft8_range_high,ft8_range_count) - if(ft8_range_count.eq.0) then - call timer('decft8 ',1) - go to 800 - endif - numthreads=ft8_range_count - requested_threads=numthreads - - nsec=mod(nutc,100) - nmsg=0 - if(nsec.ne.0 .and. nsec.ne.15 .and. nsec.ne.30 .and. nsec.ne.45) then -! Reading simulated wav file - odd%lstate=.false. - even%lstate=.false. - oddcopy%lstate=.false. - evencopy%lstate=.false. - endif - - if(firstsd) then - odd%lstate=.false. - even%lstate=.false. - firstsd=.false. - endif - - if(nsec.eq.0 .or. nsec.eq.30) then - evencopy%msg=even%msg - evencopy%freq=even%freq - evencopy%dt=even%dt - evencopy%lstate=even%lstate - even%lstate=.false. - endif - - if(nsec.eq.15 .or. nsec.eq.45) then - oddcopy%msg=odd%msg - oddcopy%freq=odd%freq - oddcopy%dt=odd%dt - oddcopy%lstate=odd%lstate - odd%lstate=.false. - endif - - nlasttx=params%nlasttx - lapmyc=params%lapmyc - nFT8decd=0 - sumxdt=0.0 - if(params%nmode.eq.4) sumxdtt=0.0 - - if(hiscall.eq.'') then - lastrxmsg(1)%lstate=.false. - else if(lastrxmsg(1)%lstate .and. lasthcall.ne.hiscall .and. & - index(lastrxmsg(1)%lastmsg,trim(hiscall)).le.0) then - lastrxmsg(1)%lstate=.false. - endif - -!$omp parallel num_threads(requested_threads) private(nthr) shared(numthreads) -!$omp single - numthreads=1 -!$ numthreads=omp_get_num_threads() -! Reduced teams cover wider frequency slices, so fixed per-worker candidate limits can lower crowded-band yield. - call partition_ft8_decode_range(nfa,nfb,numthreads,ft8_range_low, & - ft8_range_high,ft8_range_count) - numthreads=ft8_range_count - call mtd_prepare(dd8,numthreads) - call fillhashvar(numthreads,.false.) - call ft8apsetvar(params%lmycallstd,params%lhiscallstd,numthreads) -!$omp end single - - nthr=1 -!$ nthr=omp_get_thread_num()+1 - call my_ft8var%decodevar(params%nQSOProgress,nfqso, & - params%nft8rxfsens,params%nftx,ft8_range_low(nthr), & - ft8_range_high(nthr),params%ncandthin,params%ndtcenter,nsec, & - params%napwid,params%lmycallstd,params%lhiscallstd, & - params%nstophint,nthr,numthreads,logical(params%nagainfil), & - params%lft8lowth,params%lft8subpass,params%lhideft8dupes, & - active_progress_generation, & - mtd_worker_residual(:,nthr), & - mtd_worker_spectrum(:,nthr)) -!$omp end parallel - - call write_decode_progress(active_progress_generation) - call mtd_finish(dd8) - - call write_decode_progress(active_progress_generation) - call run_ft8_mtd_a8_decode() - call write_decode_progress(active_progress_generation) - - do i=1,numthreads - do m=1,nincallthr(i) - nindex=maskincallthr(i)+m - incall(30:2:-1)=incall(30-1:1:-1) - incall(1)%msg=msgincall(nindex) - incall(1)%xdt=xdtincall(nindex) - enddo - enddo - - if(nsec.eq.0 .or. nsec.eq.30) even(nmsg+1:130)%lstate=.false. - if(nsec.eq.15 .or. nsec.eq.45) odd(nmsg+1:130)%lstate=.false. - - if(params%ndelay.eq.0) then - nFT8decd=my_ft8var%decodedvar - dtmed=0. -! if(params%lforcesync) then; nintcount=3 ! fast track after Sync -! elseif(nintcount.gt.0) then; nintcount=nintcount-1 - if(nintcount.gt.0) then - nintcount=nintcount-1 - endif -! if(params%lforcesync .and. nFT8decd.eq.0) then - if(nFT8decd.eq.0) then - avexdt=forcedt - else - if(nFT8decd.gt.2) then - do i=1,nFT8decd - if(i.lt.nFT8decd-1) then - if((my_ft8var%xdtt(i).gt.my_ft8var%xdtt(i+1) .and. & - my_ft8var%xdtt(i).lt.my_ft8var%xdtt(i+2)) .or. & - (my_ft8var%xdtt(i).lt.my_ft8var%xdtt(i+1) .and. & - my_ft8var%xdtt(i).gt.my_ft8var%xdtt(i+2))) then - dtmed=my_ft8var%xdtt(i) - else if((my_ft8var%xdtt(i+1).gt.my_ft8var%xdtt(i) .and. & - my_ft8var%xdtt(i+1).lt.my_ft8var%xdtt(i+2)) .or. & - (my_ft8var%xdtt(i+1).lt.my_ft8var%xdtt(i) .and. & - my_ft8var%xdtt(i+1).gt.my_ft8var%xdtt(i+2))) then - dtmed=my_ft8var%xdtt(i+1) - else if((my_ft8var%xdtt(i+2).gt.my_ft8var%xdtt(i) .and. & - my_ft8var%xdtt(i+2).lt.my_ft8var%xdtt(i+1)) .or. & - (my_ft8var%xdtt(i+2).lt.my_ft8var%xdtt(i) .and. & - my_ft8var%xdtt(i+2).gt.my_ft8var%xdtt(i+1))) then - dtmed=my_ft8var%xdtt(i+2) - else - dtmed=my_ft8var%xdtt(i) - endif - sumxdt=sumxdt+dtmed - else - sumxdt=sumxdt+dtmed ! use last median value - endif - enddo - if(nFT8decd.gt.5) then - avexdt=(avexdt+sumxdt/nFT8decd)/2 - else if(nFT8decd.eq.5) then - avexdt=(1.1*avexdt+0.9*sumxdt/nFT8decd)/2 - else if(nFT8decd.eq.4) then - avexdt=(1.25*avexdt+0.75*sumxdt/nFT8decd)/2 - else if(nFT8decd.eq.3) then - avexdt=(1.35*avexdt+0.65*sumxdt/nFT8decd)/2 - endif - else if(nFT8decd.gt.0) then - sumxdt=sum(my_ft8var%xdtt(1:nFT8decd)) - if(nFT8decd.eq.2) then - avexdt=(1.5*avexdt+0.5*sumxdt/nFT8decd)/2 - else if(nFT8decd.eq.1) then - avexdt=(1.75*avexdt+0.25*sumxdt)/2 - endif - endif - endif - endif - - if(nFT8decd.gt.10 .and. nintcount.eq.1) avexdt=sumxdt/nFT8decd ! fast track after Sync or mode change on crowded bands - call fillhashvar(numthreads,.true.) - call write_decode_progress(active_progress_generation) - ncandall=sum(ncandallthr(1:numthreads)) - if(nFT8decd.eq.0) avexdt=0. ! reset to let correct sliding in decoder - call timer('decft8 ',1) - else ! still FT8 but not ft8md - call my_ft8%decode(ft8_decoded,id2,params%nQSOProgress,params%nfqso, & - params%nftx,newdat,params%nutc,params%nfa,params%nfb, & - params%nzhsym,params%ndepth,params%emedelay,ncontest, & - logical(params%nagain),logical(params%lft8apon),ltry_a8, & - logical(params%lapcqonly),params%napwid,mycall,hiscall,hisgrid, & - params%ndiskdat) - call timer('decft8 ',1) - endif ! end of 'still FT8 but not ft8md' - endif ! end of 'if not in SuperFox mode' - - j=0 - if(ncontest.eq.6) then - ! Fox mode: save decoded Hound calls for possible selection by FoxOp - n=params%nutc - n30=(3600*(n/10000) + 60*mod((n/100),100) + mod(n,100))/30 - if(n30.lt.n30z) nwrap=nwrap+2880 !New UTC day, handle the wrap - n30z=n30 - n30=n30+nwrap - - rewind 19 - if(nfox.eq.0) then - endfile 19 - rewind 19 - else - do i=1,nfox - n=n30fox(i) - nage=min(99,mod(n30-n+288000,2880)) - if(nage.le.4) then - j=j+1 - c2fox(j)=c2fox(i) - g2fox(j)=g2fox(i) - nsnrfox(j)=nsnrfox(i) - nfreqfox(j)=nfreqfox(i) - n30fox(j)=n - ! nage=min(99,mod(n30-n+288000,2880)) - if(len(trim(g2fox(j))).eq.4) then - call azdist(mygrid,g2fox(j)//' ',0.d0,nAz,nEl,nDmiles, & - nDkm,nHotAz,nHotABetter) - else - nDkm=9999 - endif - write(19,1004) c2fox(j),g2fox(j),nsnrfox(j),nfreqfox(j), & - nDkm,nage -1004 format(a12,1x,a4,i5,i6,i7,i3) - endif - enddo - nfox=j - flush(19) - endif - endif - go to 800 - endif ! end of code for FT8 mode - - if(params%nmode.eq.5) then - call timer('decft4 ',0) - call my_ft4%decode(ft4_decoded,id2,params%nQSOProgress,params%nfqso, & - params%nfa,params%nfb,params%ndepth, & - logical(params%lapcqonly),ncontest,mycall,hiscall) - call timer('decft4 ',1) - go to 800 - endif - - if(params%nmode.eq.66) then !NB: JT65 = 65, Q65 = 66. - ! We're in Q65 mode - open(17,file=trim(temp_dir)//'/red.dat',status='unknown') - open(14,file=trim(temp_dir)//'/avemsg.txt',status='unknown') - call timer('dec_q65 ',0) - nqd=1 - call my_q65%decode(q65_decoded,id2,nqd,params%nutc,params%ntr, & - params%nsubmode,params%nfqso,params%ntol,params%ndepth, & - params%nfa,params%nfb,logical(params%nclearave), & - single_decode,logical(params%nagain),params%max_drift, & - logical(params%newdat),params%emedelay,mycall,hiscall,hisgrid, & - params%nQSOProgress,ncontest,q65_pileup,logical(params%lapcqonly), & - navg0,nqf) - params%nclearave=.false. - - if(.not.params%nagain) then - ! Go through identified candidates again, treating each as if it had been - ! double-clicked on the waterfall. - do k=1,20 - if(nqf(k).eq.0) exit - if(params%nagain .and. abs(nqf(k)-params%nfqso).gt.params%ntol) cycle - nqd=1 - navg0=0 - ntol=5 - call my_q65%decode(q65_decoded,id2,nqd,params%nutc,params%ntr, & - params%nsubmode,nqf(k),ntol,params%ndepth, & - params%nfa,params%nfb,logical(params%nclearave), & - .true.,.true.,params%max_drift, & - .false.,params%emedelay,mycall,hiscall,hisgrid, & - params%nQSOProgress,ncontest,q65_pileup, & - logical(params%lapcqonly),navg0,nqf) - enddo - endif - - call timer('dec_q65 ',1) - close(17) - go to 800 - endif - - if(params%nmode.eq.240) then - ! We're in FST4 mode - ndepth=iand(params%ndepth,3) - iwspr=0 - lprinthash22=.false. - params%nsubmode=0 - call timer('dec_fst4',0) - call my_fst4%decode(fst4_decoded,id2,params%nutc, & - params%nQSOProgress,params%nfa,params%nfb, & - params%nfqso,ndepth,params%ntr,params%nexp_decode, & - params%ntol,params%emedelay,logical(params%nagain), & - logical(params%lapcqonly),mycall,hiscall,iwspr,lprinthash22) - call timer('dec_fst4',1) - go to 800 - endif - - if(params%nmode.eq.241 .or. params%nmode.eq.242) then - ! We're in FST4W mode - ndepth=iand(params%ndepth,3) - iwspr=1 - lprinthash22=.false. - if(params%nmode.eq.242) lprinthash22=.true. - call timer('dec_fst4',0) - call my_fst4%decode(fst4_decoded,id2,params%nutc, & - params%nQSOProgress,params%nfa,params%nfb, & - params%nfqso,ndepth,params%ntr,params%nexp_decode, & - params%ntol,params%emedelay,logical(params%nagain), & - logical(params%lapcqonly),mycall,hiscall,iwspr,lprinthash22) - call timer('dec_fst4',1) - go to 800 - endif ! Zap data at start that might come from T/R switching transient? nadd=100 @@ -639,7 +151,7 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen ! id2(1:nz)=0 ! temporarily disabled as it can breaak the JT9 decoder, maybe others endif - if(params%nmode.eq.4 .or. params%nmode.eq.65) open(14,file=trim(temp_dir)// & + if(params%nmode.eq.4) open(14,file=trim(temp_dir)// & '/avemsg.txt',status='unknown') if(params%nmode.eq.4) then @@ -669,6 +181,11 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen newdat65=params%newdat newdat9=params%newdat + if(params%nmode==74.and.iand(params%ndepth,32)/=0) then + call load_jt65_calls(jt65_calls,jt65_grids) + call my_jt65%set_calls(jt65_calls,jt65_grids) + endif + !$ call omp_set_dynamic(.true.) call wsjt_tsan_release_decoder_section_primary() @@ -677,21 +194,7 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen !$omp section call wsjt_tsan_acquire_decoder_section_primary() - if(params%nmode.eq.65) then ! We're in JT65 mode - if(newdat65) dd(1:npts65)=id2(1:npts65) - nf1=params%nfa - nf2=params%nfb - call timer('jt65a ',0) - call my_jt65%decode(jt65_decoded,dd,npts65,newdat65,params%nutc, & - nf1,nf2,params%nfqso,ntol65,params%nsubmode,params%minsync, & - logical(params%nagain),params%n2pass,logical(params%nrobust), & - ntrials,params%naggressive,params%ndepth,params%emedelay, & - logical(params%nclearave),mycall,hiscall, & - hisgrid,params%nexp_decode,params%nQSOProgress, & - logical(params%ljt65apon)) - call timer('jt65a ',1) - - else if(params%nmode.eq.9 .or. (params%nmode.eq.(65+9) .and. & + if(params%nmode.eq.9 .or. (params%nmode.eq.(65+9) .and. & params%ntxmode.eq.9)) then ! We're in JT9 mode, or should do JT9 first call timer('decjt9 ',0) @@ -736,71 +239,12 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen ! JT65 is not yet producing info for nsynced, ndecoded. -800 ndecoded = my_jt4%decoded + my_jt65%decoded + my_jt9%decoded + & - my_ft8%decoded + my_ft8var%decodedvar + my_ft4%decoded + & - my_fst4%decoded + my_q65%decoded - if(params%lmultift8 .and. params%nmode.eq.8) then - if(params%nzhsym.eq.41) ndec41=0 - if(params%nzhsym.eq.46) ndec46=ndecoded - if(params%nzhsym.eq.47) ndec47=ndecoded - if(params%nzhsym.eq.48) ndec48=ndecoded - if(params%nzhsym.eq.49) ndec49=ndecoded - if(params%nzhsym.eq.50) then - ndecoded=ndec41+ndec46+ndec47+ndec48+ndec49+ndecoded - endif - elseif(params%nmode.eq.8 .and. params%nzhsym.eq.41) then - ndec41=ndecoded - elseif(params%nmode.eq.8 .and. params%nzhsym.eq.47) then - ndec47=ndecoded - elseif(params%nmode.eq.8 .and. params%nzhsym.eq.50) then - ndecoded=ndec41+ndec47+ndecoded - endif - if(params%nmode.ne.8 .or. params%nzhsym.eq.50 .or. & - (params%lmultift8 .and. params%nmode.eq.8 .and. params%nzhsym.gt.45) .or. & - .not.params%ndiskdat) then !ft8md - call set_decode_completion(completion,nsynced,ndecoded,navg0) - call write_decode_progress(active_progress_generation) - endif +800 ndecoded = my_jt4%decoded + my_jt65%decoded + my_jt9%decoded + call set_decode_completion(completion,nsynced,ndecoded,navg0) + call write_decode_progress(active_progress_generation) close(13) - if(ncontest.eq.6) close(19) - if(params%nmode.eq.4 .or. params%nmode.eq.65 .or. params%nmode.eq.66) close(14) + if(params%nmode.eq.4) close(14) return - -contains - - subroutine run_ft8_mtd_a8_decode() - implicit none - - external ft8_a8d - real f1,xdt,fbest,xsnr,plog,qual - integer nsnr,iaptype - character(len=6) dxgrid - character(len=37) msg37 - - if(.not.params%lft8apon) return - if(ncontest.eq.6 .or. ncontest.eq.7) return - if(len(trim(hiscall)).lt.3 .or. len(trim(hisgrid4)).lt.4) return - if(.not.ltry_a8) return - - f1=nfqso - dxgrid=hisgrid4 - call timer('ft8_a8d ',0) - call ft8_a8d(dd8,mycall,hiscall,dxgrid,f1,xdt,fbest,xsnr,plog,msg37, & - active_progress_generation) - call timer('ft8_a8d ',1) - - if(msg37(1:1).ne.' ') then - if(associated(my_ft8var%callback)) then - nsnr=nint(xsnr) - iaptype=8 - qual=1.0 - if(plog.lt.-147.0) qual=0.16 - call my_ft8var%callback(nsnr,xdt,fbest,msg37,iaptype,qual) - endif - endif - end subroutine run_ft8_mtd_a8_decode - - end subroutine multimode_decoder_core subroutine multimode_decoder(ss,id2,params,nfsample) @@ -821,7 +265,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample) if (.not. completion%available) return if (streaming_emit_enabled()) then - call streaming_emit_decode_finished(params%nutc) + call streaming_emit_decode_finished(params%nutc,params%nmode==66.or.params%nmode==240.or. & + params%nmode==241.or.params%nmode==242) else if (.not. lquiet) then call write_decode_completion(completion) end if diff --git a/lib/decoder_callbacks.f90 b/lib/decoder_callbacks.f90 index 33c2ac85..186290c7 100644 --- a/lib/decoder_callbacks.f90 +++ b/lib/decoder_callbacks.f90 @@ -2,25 +2,37 @@ module decoder_callbacks use jt4_decode use jt65_decode - use jt9_decode + use jt9_decode, only: jt9_decoder use ft8_decode use ft8_decodevar use ft4_decode - use fst4_decode + use fst4_decode, only: fst4_decoder use q65_decode use streaming_emit, only: streaming_emit_enabled, streaming_emit_decode + use decoder_engine_types + use jt65_host_support, only: write_jt65_averages + use, intrinsic :: iso_c_binding, only: c_ptr,c_null_ptr,c_char,c_null_char implicit none type :: decoder_callback_context ! Callback state is stored on each decoder instead of captured by a nested procedure. + integer :: mode = 0 integer :: nutc = 0 integer :: nfqso = 0 integer :: ncontest = 0 + integer :: submode = 0 integer :: ios13 = -1 + integer :: ios14 = -1 logical :: bVHF = .false. logical :: b_superfox = .false. character(len=12) :: mycall = ' ' + real :: waveform_input_offset_seconds = 0.0 + procedure(engine_observation_sink), pointer, nopass :: sink => null() + procedure(engine_superfox_sink), pointer, nopass :: superfox_sink => null() + type(c_ptr) :: sink_user = c_null_ptr + logical :: render_legacy = .true. + logical :: utc_is_hhmmss = .false. end type decoder_callback_context type, extends(jt4_decoder) :: counting_jt4_decoder @@ -41,12 +53,16 @@ module decoder_callbacks type, extends(ft8_decoder) :: counting_ft8_decoder type(decoder_callback_context) :: context integer :: decoded = 0 + logical :: first_result = .true. + integer :: day_wrap = 0 end type counting_ft8_decoder type, extends(ft8_decodervar) :: counting_ft8_decodervar type(decoder_callback_context) :: context integer :: decodedvar = 0 real :: xdtt(200) + logical :: first_result = .true. + integer :: day_wrap = 0 end type counting_ft8_decodervar type, extends(ft4_decoder) :: counting_ft4_decoder @@ -57,6 +73,7 @@ module decoder_callbacks type, extends(fst4_decoder) :: counting_fst4_decoder type(decoder_callback_context) :: context integer :: decoded = 0 + logical :: print_hash22 = .false. end type counting_fst4_decoder type, extends(q65_decoder) :: counting_q65_decoder @@ -171,9 +188,12 @@ contains logical context_bVHF logical is_deep,is_average character decoded*22,csync*2,cflags*3 + type(decoder_callback_context) :: context + type(engine_observation) :: observation select type (typed_this => this) type is (counting_jt65_decoder) + context = typed_this%context context_nutc = typed_this%context%nutc context_ios13 = typed_this%context%ios13 context_bVHF = typed_this%context%bVHF @@ -181,7 +201,32 @@ contains return end select + observation=engine_observation() + observation%mode=engine_mode_jt65 + observation%variant=context%submode + observation%snr_db=snr + observation%frequency_hz=real(freq) + observation%dt_seconds=dt + observation%sync=sync + observation%quality=real(qual) + observation%ap_type=ishft(ft,-2) + observation%jt65%kind=merge(1,0,len_trim(decoded0)>0) + observation%jt65%method=iand(ft,3) + observation%jt65%average_count=nsum + observation%jt65%sync_polarity=nflip + observation%jt65%smoothing=nsmo + observation%jt65%has_width=merge(1,0,context%bVHF) + if(context%bVHF) observation%jt65%width_hz=width + observation%jt65%has_drift=merge(1,0,nflip/=0) + if(nflip/=0) observation%jt65%drift_hz=real(drift) + do i=1,len_trim(decoded0) + observation%message(i)=decoded0(i:i) + enddo + if(associated(context%sink)) call context%sink(context%sink_user,observation) + + if(context%render_legacy) then !$omp critical(decode_results) + if(context%ios14==0) call write_jt65_averages(this,14) decoded=decoded0 cflags=' ' is_deep=ft.eq.2 @@ -243,9 +288,10 @@ contains call flush(6) !$omp end critical(decode_results) + endif select type (typed_this => this) type is (counting_jt65_decoder) - typed_this%decoded = typed_this%decoded + 1 + if(len_trim(decoded0)>0) typed_this%decoded = typed_this%decoded + 1 end select end subroutine jt65_decoded @@ -259,16 +305,36 @@ contains real, intent(in) :: freq integer, intent(in) :: drift character(len=22), intent(in) :: decoded - integer context_nutc, context_ios13 + type(engine_observation) :: observation + type(decoder_callback_context) :: context + integer context_nutc, context_ios13,i select type (typed_this => this) type is (counting_jt9_decoder) + context = typed_this%context context_nutc = typed_this%context%nutc context_ios13 = typed_this%context%ios13 class default return end select + observation=engine_observation() + observation%mode=engine_mode_jt9 + observation%variant=context%submode + observation%snr_db=snr + observation%frequency_hz=freq + observation%dt_seconds=dt + observation%sync=sync + if(context%submode==0) then + observation%jt9%has_drift=1 + observation%jt9%drift_hz_per_minute=real(drift)*(12000.0/16384.0)*60.0/48.96 + endif + do i=1,len_trim(decoded) + observation%message(i)=decoded(i:i) + enddo + if(associated(context%sink)) call context%sink(context%sink_user,observation) + + if(context%render_legacy) then !$omp critical(decode_results) if (streaming_emit_enabled()) then @@ -282,14 +348,19 @@ contains 1002 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a22,' JT9') call flush(6) !$omp end critical(decode_results) + endif select type (typed_this => this) type is (counting_jt9_decoder) typed_this%decoded = typed_this%decoded + 1 end select end subroutine jt9_decoded - subroutine ft8_decodedvar (this,snr,dt,freq,decodedvar,nap,qual) + subroutine ft8_decodedvar (this,snr,dt,freq,decodedvar,nap,qual,evidence) implicit none + type(ft8_signal_evidence), optional, intent(in) :: evidence + type(engine_observation) :: observation + type(decoder_callback_context) :: context + integer :: message_index class(ft8_decodervar), intent(inout) :: this integer, intent(in) :: snr @@ -307,8 +378,6 @@ contains integer context_nutc, context_nfqso, context_ncontest, context_ios13 logical context_b_superfox character(len=12) context_mycall - data first/.true./ - save :: first,nwrap isgrid4(w)=(len_trim(w).eq.4 .and. & ichar(w(1:1)).ge.ichar('A') .and. ichar(w(1:1)).le.ichar('R') .and. & @@ -318,6 +387,9 @@ contains select type (typed_this => this) type is (counting_ft8_decodervar) + context=typed_this%context + first=typed_this%first_result + nwrap=typed_this%day_wrap context_nutc = typed_this%context%nutc context_nfqso = typed_this%context%nfqso context_ncontest = typed_this%context%ncontest @@ -354,6 +426,7 @@ contains if(qual.lt.0.17) decoded0(37:37)='?' endif + if(context%render_legacy) then if (streaming_emit_enabled()) then call streaming_emit_decode("FT8", context_nutc, snr, dt, nint(freq), decoded0) else @@ -361,6 +434,8 @@ contains end if 1000 format(i6.6,i4,f5.1,i5,' ~ ',1x,a37,1x,a2) + endif + if(context_ncontest.eq.6) then i1=index(decoded0,' ') i2=i1 + index(decoded0(i1+1:),' ') @@ -394,18 +469,42 @@ contains endif endif endif - call flush(6) - if(context_ios13.eq.0) call flush(13) + if(context%render_legacy) then + call flush(6) + if(context_ios13.eq.0) call flush(13) + endif + + observation%variant=1 + observation%snr_db=snr + observation%frequency_hz=freq + observation%dt_seconds=dt + observation%ap_type=nap + observation%quality=qual + do message_index=1,min(len_trim(decodedvar),37) + observation%message(message_index)=decodedvar(message_index:message_index) + enddo + if(present(evidence)) then + observation%ft8=evidence + if(evidence%has_waveform_start/=0) observation%ft8%waveform_start_seconds= & + evidence%waveform_start_seconds+context%waveform_input_offset_seconds + endif + if(associated(context%sink)) call context%sink(context%sink_user,observation) select type (typed_this => this) type is (counting_ft8_decodervar) + typed_this%first_result=first + typed_this%day_wrap=nwrap typed_this%decodedvar = typed_this%decodedvar + 1 - typed_this%xdtt(typed_this%decodedvar)=dt + if(typed_this%decodedvar.le.size(typed_this%xdtt)) typed_this%xdtt(typed_this%decodedvar)=dt end select end subroutine ft8_decodedvar - subroutine ft8_decoded (this,sync,snr,dt,freq,decoded,nap,qual) + subroutine ft8_decoded (this,sync,snr,dt,freq,decoded,nap,qual,evidence) implicit none + type(ft8_signal_evidence), optional, intent(in) :: evidence + type(engine_observation) :: observation + type(decoder_callback_context) :: context + integer :: message_index class(ft8_decoder), intent(inout) :: this real, intent(in) :: sync @@ -424,8 +523,6 @@ contains integer context_nutc, context_nfqso, context_ncontest, context_ios13 logical context_b_superfox character(len=12) context_mycall - data first/.true./ - save :: first,nwrap isgrid4(w)=(len_trim(w).eq.4 .and. & ichar(w(1:1)).ge.ichar('A') .and. ichar(w(1:1)).le.ichar('R') .and. & @@ -435,6 +532,9 @@ contains select type (typed_this => this) type is (counting_ft8_decoder) + context=typed_this%context + first=typed_this%first_result + nwrap=typed_this%day_wrap context_nutc = typed_this%context%nutc context_nfqso = typed_this%context%nfqso context_ncontest = typed_this%context%ncontest @@ -467,6 +567,7 @@ contains endif i0=1 + if(context%render_legacy) then if (streaming_emit_enabled()) then if (i0.le.0) call streaming_emit_decode("FT8", context_nutc, snr, dt, nint(freq), decoded0(1:22)) if (i0.gt.0) call streaming_emit_decode("FT8", context_nutc, snr, dt, nint(freq), decoded0) @@ -479,6 +580,8 @@ contains if(context_ios13.eq.0) write(13,1002) context_nutc,nint(sync),snr,dt,freq,0,decoded0 1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FT8') + endif + if(context_ncontest.eq.6) then i1=index(decoded0,' ') i2=i1 + index(decoded0(i1+1:),' ') @@ -513,34 +616,74 @@ contains endif endif - call flush(6) - if(context_ios13.eq.0) call flush(13) + if(context%render_legacy) then + call flush(6) + if(context_ios13.eq.0) call flush(13) + endif + + observation%variant=0 + observation%snr_db=snr + observation%frequency_hz=freq + observation%dt_seconds=dt + observation%ap_type=nap + observation%quality=qual + observation%sync=sync + do message_index=1,min(len_trim(decoded),37) + observation%message(message_index)=decoded(message_index:message_index) + enddo + if(present(evidence)) then + observation%ft8=evidence + if(evidence%has_waveform_start/=0) observation%ft8%waveform_start_seconds= & + evidence%waveform_start_seconds+context%waveform_input_offset_seconds + endif + if(associated(context%sink)) call context%sink(context%sink_user,observation) select type (typed_this => this) type is (counting_ft8_decoder) + typed_this%first_result=first + typed_this%day_wrap=nwrap typed_this%decoded = typed_this%decoded + 1 end select end subroutine ft8_decoded - subroutine ft4_decoded (this,sync,snr,dt,freq,decoded,nap,qual) + subroutine ft4_decoded (this,sync,snr,dt,freq,decoded,nap,qual,evidence) implicit none class(ft4_decoder), intent(inout) :: this + type(ft4_signal_evidence), intent(in) :: evidence + type(engine_observation) :: observation + type(decoder_callback_context) :: context real, intent(in) :: sync,dt,freq,qual integer, intent(in) :: snr,nap character(len=37), intent(in) :: decoded character*2 annot character*37 decoded0 - integer context_nutc, context_ios13 + integer context_nutc, context_ios13,i select type (typed_this => this) type is (counting_ft4_decoder) + context=typed_this%context context_nutc = typed_this%context%nutc context_ios13 = typed_this%context%ios13 class default return end select + observation=engine_observation() + observation%mode=engine_mode_ft4 + observation%snr_db=snr + observation%ap_type=nap + observation%dt_seconds=dt + observation%frequency_hz=freq + observation%sync=sync + observation%quality=qual + observation%ft4=evidence + do i=1,len_trim(decoded) + observation%message(i)=decoded(i:i) + enddo + if(associated(context%sink)) call context%sink(context%sink_user,observation) + if(.not.context%render_legacy) go to 20 + decoded0=decoded annot=' ' @@ -564,6 +707,7 @@ contains 10 call flush(6) +20 continue select type (typed_this => this) type is (counting_ft4_decoder) typed_this%decoded = typed_this%decoded + 1 @@ -571,7 +715,7 @@ contains end subroutine ft4_decoded subroutine fst4_decoded (this,nutc,sync,nsnr,dt,freq,decoded,nap, & - qual,ntrperiod,fmid,w50) + qual,ntrperiod,fmid,w50,result) implicit none @@ -587,19 +731,29 @@ contains integer, intent(in) :: ntrperiod real, intent(in) :: fmid real, intent(in) :: w50 + type(fst4_result), intent(in), optional :: result + type(engine_observation) :: observation + type(decoder_callback_context) :: context + integer :: display_utc,message_index,space + logical :: print_hash22 character*2 annot character*37 decoded0 + character*37 suffix character*70 line integer context_ios13 select type (typed_this => this) type is (counting_fst4_decoder) - context_ios13 = typed_this%context%ios13 + context=typed_this%context + context_ios13 = context%ios13 + print_hash22=typed_this%print_hash22 class default return end select + display_utc=nutc + if(context%utc_is_hhmmss.and.ntrperiod>=60) display_utc=nutc/100 decoded0=decoded annot=' ' if(nap.ne.0) then @@ -607,15 +761,24 @@ contains if(qual.lt.0.17) decoded0(37:37)='?' endif + if(context%render_legacy) then + if(present(result)) then + if(print_hash22.and.result%has_hash22/=0) then + space=index(decoded0,' ') + suffix=decoded0(space+1:) + write(decoded0,'(a1,i7.7,a1)') '<',result%hash22,'>' + decoded0=trim(decoded0)//' '//trim(suffix) + endif + endif if(ntrperiod.lt.60) then - write(line,1001) nutc,nsnr,dt,nint(freq),decoded0,annot + write(line,1001) display_utc,nsnr,dt,nint(freq),decoded0,annot 1001 format(i6.6,i4,f5.1,i5,' ` ',1x,a37,1x,a2) - if(context_ios13.eq.0) write(13,1002) nutc,nint(sync),nsnr,dt,freq,0,decoded0 + if(context_ios13.eq.0) write(13,1002) display_utc,nint(sync),nsnr,dt,freq,0,decoded0 1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FST4') else - write(line,1003) nutc,nsnr,dt,nint(freq),decoded0,annot + write(line,1003) display_utc,nsnr,dt,nint(freq),decoded0,annot 1003 format(i4.4,i4,f5.1,i5,' ` ',1x,a37,1x,a2,2f7.3) - if(context_ios13.eq.0) write(13,1004) nutc,nint(sync),nsnr,dt,freq,0,decoded0 + if(context_ios13.eq.0) write(13,1004) display_utc,nint(sync),nsnr,dt,freq,0,decoded0 1004 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a37,' FST4') endif @@ -625,7 +788,7 @@ contains endif if (streaming_emit_enabled()) then - call streaming_emit_decode("FST4", nutc, nsnr, dt, nint(freq), decoded0) + call streaming_emit_decode("FST4", nutc, nsnr, dt, nint(freq), decoded0,context%utc_is_hhmmss) else write(*,1005) line end if @@ -633,6 +796,21 @@ contains call flush(6) if(context_ios13.eq.0) call flush(13) + endif + + observation=engine_observation() + observation%mode=context%mode + observation%snr_db=nsnr + observation%ap_type=nap + observation%dt_seconds=dt + observation%frequency_hz=freq + observation%sync=sync + observation%quality=qual + if(present(result)) observation%fst4=result + do message_index=1,min(len_trim(decoded),37) + observation%message(message_index)=decoded(message_index:message_index) + enddo + if(associated(context%sink)) call context%sink(context%sink_user,observation) select type (typed_this => this) type is (counting_fst4_decoder) @@ -657,16 +835,40 @@ contains integer, intent(in) :: ntrperiod integer, intent(in) :: iflagdec !Recovered spare 78th bit (see genq65/q65_ap) character*4 cflags - integer context_ios13 + integer context_ios13,display_utc,i + type(engine_observation) :: observation + type(decoder_callback_context) :: context select type (typed_this => this) type is (counting_q65_decoder) context_ios13 = typed_this%context%ios13 + context=typed_this%context class default return end select + observation=engine_observation() + observation%mode=engine_mode_q65 + observation%variant=context%submode + observation%snr_db=nsnr + observation%frequency_hz=freq + observation%dt_seconds=dt + observation%sync=snr1 + observation%ap_type=idec + observation%q65%period_seconds=ntrperiod + observation%q65%method=idec + observation%q65%average_count=nused + observation%q65%recovered_bit78=iflagdec + do i=1,len_trim(decoded) + observation%message(i)=decoded(i:i) + enddo + if(associated(context%sink)) call context%sink(context%sink_user,observation) + display_utc=nutc + if(context%utc_is_hhmmss.and.ntrperiod>=60) display_utc=nutc/100 + + if(context%render_legacy) then cflags=' ' + if(idec.ge.0) then cflags='q ' write(cflags(2:2),'(i1)') idec @@ -679,35 +881,36 @@ contains if(ntrperiod.lt.60) then if (streaming_emit_enabled()) then - call streaming_emit_decode("Q65", nutc, nsnr, dt, nint(freq), decoded) + call streaming_emit_decode("Q65", nutc, nsnr, dt, nint(freq), decoded,context%utc_is_hhmmss) else if(len_trim(cflags).gt.3) then - write(*,1005) nutc,nsnr,dt,nint(freq),decoded,cflags + write(*,1005) display_utc,nsnr,dt,nint(freq),decoded,cflags else - write(*,1001) nutc,nsnr,dt,nint(freq),decoded,cflags + write(*,1001) display_utc,nsnr,dt,nint(freq),decoded,cflags endif end if 1001 format(i6.6,i4,f5.1,i5,' : ',1x,a37,1x,a3) 1005 format(i6.6,i4,f5.1,i5,' : ',1x,a37,1x,a4) - if(context_ios13.eq.0) write(13,1002) nutc,nint(snr1),nsnr,dt,freq,0,decoded + if(context_ios13.eq.0) write(13,1002) display_utc,nint(snr1),nsnr,dt,freq,0,decoded 1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' Q65') else if (streaming_emit_enabled()) then - call streaming_emit_decode("Q65", nutc, nsnr, dt, nint(freq), decoded) + call streaming_emit_decode("Q65", nutc, nsnr, dt, nint(freq), decoded,context%utc_is_hhmmss) else if(len_trim(cflags).gt.3) then - write(*,1006) nutc,nsnr,dt,nint(freq),decoded,cflags + write(*,1006) display_utc,nsnr,dt,nint(freq),decoded,cflags else - write(*,1003) nutc,nsnr,dt,nint(freq),decoded,cflags + write(*,1003) display_utc,nsnr,dt,nint(freq),decoded,cflags endif end if 1003 format(i4.4,i4,f5.1,i5,' : ',1x,a37,1x,a3) 1006 format(i4.4,i4,f5.1,i5,' : ',1x,a37,1x,a4) - if(context_ios13.eq.0) write(13,1004) nutc,nint(snr1),nsnr,dt,freq,0,decoded + if(context_ios13.eq.0) write(13,1004) display_utc,nint(snr1),nsnr,dt,freq,0,decoded 1004 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a37,' Q65') endif call flush(6) if(context_ios13.eq.0) call flush(13) + endif select type (typed_this => this) type is (counting_q65_decoder) diff --git a/lib/decoder_engine.f90 b/lib/decoder_engine.f90 new file mode 100644 index 00000000..eee39e74 --- /dev/null +++ b/lib/decoder_engine.f90 @@ -0,0 +1,1366 @@ +module decoder_engine + use, intrinsic :: iso_c_binding + use decoder_engine_types + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + use packjt77, only: pack77_state,initialize_pack77_state,reset_pack77_state + use ft8_engine_kernel, only: ft8_kernel_state,params_block,run_ft8_kernel,reset_ft8_kernel,release_ft8_input + use decoder_callbacks, only: decoder_callback_context,counting_ft4_decoder,ft4_decoded, & + counting_jt9_decoder,jt9_decoded,counting_jt65_decoder,jt65_decoded, & + counting_q65_decoder,q65_decoded,counting_fst4_decoder,fst4_decoded + use q65_decode, only: q65_options + use fst4_decode, only: fst4_options + use fst4_host_support, only: prepare_fst4_host,finish_fst4_host + use q65_host_support, only: load_q65_history,save_q65_history,write_q65_curves,write_q65_diagnostic + use q65_callers, only: Q65_MAX_CALLERS + use types, only: q3list + use jt65_decode, only: jt65_options,jt65_average_entry + use jt65_host_support, only: load_jt65_calls,write_jt65_averages + use decode_completion_module, only: decode_completion_result,set_decode_completion,write_decode_progress + use prog_args, only: temp_dir + use timer_module, only: timer + implicit none + private + public :: engine_host_decode + integer(c_int), parameter :: ok=0,invalid=1,busy=2,unsupported=3,capacity=4,internal_error=5 + integer, parameter :: evidence_capacity=1024 + + type, bind(C) :: engine_options + integer(c_int) :: abi_version + end type + type, bind(C) :: engine_capabilities + integer(c_int) :: abi_version,supported_modes,cancellation,concurrent_sessions,evidence_capacity + end type + type, bind(C) :: ft8_options + integer(c_int) :: half_symbol_stage=50 + integer(c_int) :: reuse_spectrum=0 + integer(c_int) :: utc=0 + integer(c_int) :: qso_progress=0 + integer(c_int) :: receive_frequency_hz=0 + integer(c_int) :: transmit_frequency_hz=0 + integer(c_int) :: search_low_hz=0 + integer(c_int) :: search_high_hz=0 + integer(c_int) :: tolerance_hz=0 + integer(c_int) :: depth=0 + integer(c_int) :: ap_width_hz=0 + integer(c_int) :: contest=0 + integer(c_int) :: candidate_thinning=0 + integer(c_int) :: time_center=0 + integer(c_int) :: cycles=0 + integer(c_int) :: trials=0 + integer(c_int) :: last_transmit=0 + integer(c_int) :: delay=0 + integer(c_int) :: threads=0 + integer(c_int) :: receive_sensitivity=0 + integer(c_int) :: discard_leading_seconds=0 + integer(c_int) :: date=0 + integer(c_int) :: ap_enabled=0 + integer(c_int) :: cq_only=0 + integer(c_int) :: even_sequence=0 + integer(c_int) :: superfox=0 + integer(c_int) :: filtered_retry=0 + integer(c_int) :: stop_hint=0 + integer(c_int) :: mtd=0 + integer(c_int) :: low_threshold=0 + integer(c_int) :: subtract_pass=0 + integer(c_int) :: transmitting=0 + integer(c_int) :: hide_duplicates=0 + integer(c_int) :: hound=0 + integer(c_int) :: standard_mycall=0 + integer(c_int) :: standard_hiscall=0 + integer(c_int) :: ap_mycall=0 + integer(c_int) :: mode_changed=0 + integer(c_int) :: band_changed=0 + integer(c_int) :: dx_search=0 + integer(c_int) :: wide_dx_search=0 + integer(c_int) :: multiple_instances=0 + integer(c_int) :: skip_first_message=0 + real(c_float) :: eme_delay_seconds=0 + character(c_char) :: mycall(12)=' ' + character(c_char) :: my_base_call(12)=' ' + character(c_char) :: hiscall(12)=' ' + character(c_char) :: his_base_call(12)=' ' + character(c_char) :: mygrid(6)=' ' + character(c_char) :: hisgrid(6)=' ' + end type + type, bind(C) :: ft4_options + integer(c_int) :: utc=0 + integer(c_int) :: qso_progress=0 + integer(c_int) :: receive_frequency_hz=0 + integer(c_int) :: search_low_hz=0 + integer(c_int) :: search_high_hz=0 + integer(c_int) :: depth=0 + integer(c_int) :: cq_only=0 + integer(c_int) :: contest=0 + character(c_char) :: mycall(12)=' ' + character(c_char) :: hiscall(12)=' ' + end type + type, bind(C) :: jt9_options + integer(c_int) :: utc=0 + integer(c_int) :: receive_frequency_hz=0 + integer(c_int) :: search_low_hz=0 + integer(c_int) :: search_high_hz=0 + integer(c_int) :: tolerance_hz=0 + integer(c_int) :: depth=0 + integer(c_int) :: submode=0 + end type + type, bind(C) :: engine_jt65_options + integer(c_int) :: utc=0,qso_progress=0,receive_frequency_hz=0,search_low_hz=0,search_high_hz=0 + integer(c_int) :: tolerance_hz=0,depth=0,submode=0,min_sync=0,passes=0,trials=0,aggressiveness=0 + integer(c_int) :: single_decode=0,vhf=0,averaging=0,auto_clear=0,deep_search=0,ap_enabled=0 + character(c_char) :: mycall(12)=' ',hiscall(12)=' ',hisgrid(6)=' ' + end type + type, bind(C) :: engine_jt65_call + character(c_char) :: call(12),grid(4) + end type + type, bind(C) :: engine_jt65_average_entry + integer(c_int) :: utc,frequency_hz,polarity,used + real(c_float) :: sync,dt_seconds + end type + type, bind(C) :: engine_q65_options + integer(c_int) :: utc=0,period_seconds=60,submode=0,receive_frequency_hz=0,tolerance_hz=0 + integer(c_int) :: search_low_hz=0,search_high_hz=0,depth=0,max_drift_symbol_rates=0 + integer(c_int) :: qso_progress=0,contest=0,averaging=0,auto_clear=0,single_decode=0 + integer(c_int) :: extended_eme_search=0,pileup=0,ap_cq_only=0,now_seconds=0 + character(c_char) :: mycall(12)=' ',hiscall(12)=' ',hisgrid(6)=' ' + end type + type, bind(C) :: engine_q65_caller + character(c_char) :: call(12),grid(4) + integer(c_int) :: last_seen,frequency_hz + end type + type, bind(C) :: engine_q65_snapshot + integer(c_int) :: even_count=0,odd_count=0,curve_count=0,curve_average_count=0 + real(c_float) :: frequency_step_hz=0,dt_seconds=0 + end type + type, bind(C) :: engine_fst4_options + integer(c_int) :: utc=0,period_seconds=15,receive_frequency_hz=1500,search_low_hz=200,search_high_hz=4000 + integer(c_int) :: tolerance_hz=100,depth=1,qso_progress=0,single_decode=0,ap_cq_only=0 + integer(c_int) :: blanker_mode=0,blanker_percent=0,measure_doppler=0 + real(c_float) :: eme_delay_seconds=0 + character(c_char) :: mycall(12)=' ',hiscall(12)=' ' + end type + type, bind(C) :: engine_fst4w_call + character(c_char) :: call_grid(20) + end type + type, bind(C) :: attempt_request + integer(c_int64_t) :: input_id=0,analysis_id=0 + integer(c_int) :: attempt_no=0,mode=8,phase=2,source=0 + type(ft8_options) :: ft8 + type(ft4_options) :: ft4 + type(jt9_options) :: jt9 + type(engine_jt65_options) :: jt65 + type(engine_q65_options) :: q65 + type(engine_fst4_options) :: fst4 + end type + type, bind(C) :: audio_view + type(c_ptr) :: samples + integer(c_int) :: sample_count,sample_rate_hz + end type + type, bind(C) :: attempt_outcome + integer(c_int) :: status=ok,observation_count=0,retained_count=0,evidence_dropped=0 + end type + abstract interface + subroutine observation_callback(observation,user) bind(C) + import :: engine_observation,c_ptr + type(engine_observation), intent(in) :: observation + type(c_ptr), value :: user + end subroutine + end interface + type :: engine_session + type(pack77_state) :: knowledge + type(ft8_kernel_state) :: kernel + type(counting_ft4_decoder) :: ft4 + ! GCC 13 can finalize an uninitialized temporary for an embedded finalizable extension. + type(counting_jt9_decoder), allocatable :: jt9 + type(counting_jt65_decoder), allocatable :: jt65 + type(counting_q65_decoder), allocatable :: q65 + type(counting_fst4_decoder), allocatable :: fst4 + type(attempt_request) :: request + type(engine_observation), allocatable :: evidence(:) + integer(c_short), allocatable :: audio(:) + integer(c_int64_t) :: input_id=0,analysis_id=0 + integer :: input_mode=0,input_sample_count=0 + integer :: last_attempt=0,retained=0,dropped=0,emitted=0 + logical :: running=.false.,render_legacy=.false. + type(c_funptr) :: callback=c_null_funptr + type(c_ptr) :: user=c_null_ptr + type(decode_completion_result) :: completion + end type + type(engine_session), allocatable, target, save :: session + integer(c_int), target, save :: token=1 + type(c_ptr), save :: host_handle=c_null_ptr + integer(c_int64_t), save :: fallback_input=0,fallback_analysis=0 + integer, save :: fallback_utc=-1 + +contains + + pure integer function analysis_extent(mode,period) result(samples) + integer, intent(in) :: mode + integer, optional, intent(in) :: period + select case(mode) + case(engine_mode_ft4) + samples=72576 + case(engine_mode_ft8) + samples=180000 + case(engine_mode_jt9,engine_mode_jt65) + samples=720000 + case(engine_mode_q65) + samples=0 + if(present(period)) then + if(any(period==[15,30,60,120,300])) samples=period*12000 + endif + case(engine_mode_fst4,engine_mode_fst4w) + samples=0 + if(present(period)) then + if(any(period==[15,30,60,120,300,900,1800])) samples=period*12000 + endif + case default + samples=0 + end select + end function analysis_extent + + subroutine initialize_session(state) + type(engine_session), intent(inout) :: state + allocate(state%jt9) + allocate(state%jt65) + allocate(state%q65) + allocate(state%fst4) + allocate(state%audio(analysis_extent(engine_mode_ft8)),state%evidence(evidence_capacity)) + state%audio=0 + call initialize_pack77_state(state%knowledge) + call reset_ft8_kernel(state%kernel) + end subroutine initialize_session + + logical function valid_handle(handle) + type(c_ptr), value :: handle + valid_handle=allocated(session).and.c_associated(handle,c_loc(token)) + end function + + integer(c_int) function engine_create(options,handle) bind(C,name='decoder_engine_create') result(status) + type(engine_options), intent(in) :: options + type(c_ptr), intent(out) :: handle + handle=c_null_ptr + status=unsupported + if(options%abi_version/=engine_abi) return + status=busy + if(allocated(session)) return + allocate(session) + call initialize_session(session) + handle=c_loc(token) + status=ok + end function + + integer(c_int) function engine_get_capabilities(handle,caps) & + bind(C,name='decoder_engine_get_capabilities') result(status) + type(c_ptr), value :: handle + type(engine_capabilities), intent(out) :: caps + caps=engine_capabilities(engine_abi, & + ior(ior(engine_support_ft8,engine_support_ft4), & + ior(ior(ior(engine_support_jt9,engine_support_jt65),engine_support_q65), & + ior(engine_support_fst4,engine_support_fst4w))), & + 0,0,evidence_capacity) + status=invalid + if(valid_handle(handle)) status=ok + end function + + recursive integer(c_int) function engine_decode(handle,request,audio,callback,user,outcome) & + bind(C,name='decoder_engine_decode') result(status) + type(c_ptr), value :: handle,user + type(attempt_request), intent(in) :: request + type(audio_view), intent(in) :: audio + type(c_funptr), value :: callback + type(attempt_outcome), intent(out) :: outcome + status=decode_attempt(handle,request,audio,callback,user,outcome,.false.,0) + end function + + recursive integer(c_int) function decode_attempt(handle,request,audio,callback,user,outcome,render,progress) result(status) + type(c_ptr), intent(in) :: handle,user + type(attempt_request), intent(in) :: request + type(audio_view), intent(in) :: audio + type(c_funptr), intent(in) :: callback + type(attempt_outcome), intent(out) :: outcome + logical, intent(in) :: render + integer, intent(in) :: progress + integer(c_short), pointer :: samples(:) + integer :: analysis_samples + type(params_block) :: params + type(decoder_callback_context) :: context + outcome=attempt_outcome() + status=invalid + if(.not.valid_handle(handle)) go to 900 + status=busy + if(session%running) go to 900 + status=unsupported + if(request%mode/=engine_mode_ft8.and.request%mode/=engine_mode_ft4.and. & + request%mode/=engine_mode_jt9.and.request%mode/=engine_mode_jt65.and.request%mode/=engine_mode_q65.and. & + request%mode/=engine_mode_fst4.and.request%mode/=engine_mode_fst4w) go to 900 + if(audio%sample_rate_hz/=12000) go to 900 + status=invalid + if(request%input_id<=0.or.request%analysis_id<=0.or.request%attempt_no<=0) go to 900 + if(request%phase<1.or.request%phase>3.or.request%source<0.or.request%source>1) go to 900 + if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) then + analysis_samples=analysis_extent(request%mode,request%fst4%period_seconds) + else + analysis_samples=analysis_extent(request%mode,request%q65%period_seconds) + endif + if(audio%sample_count<1.or.audio%sample_count>analysis_samples) go to 900 + if(.not.c_associated(audio%samples)) go to 900 + if(request%mode==engine_mode_ft4) then + if(request%phase==1) go to 900 + if(request%ft4%search_low_hz<0.or.request%ft4%search_high_hz>6000.or. & + request%ft4%search_low_hz>request%ft4%search_high_hz) go to 900 + if(request%ft4%depth<1.or.request%ft4%depth>3) go to 900 + if(request%ft4%qso_progress<0.or.request%ft4%qso_progress>5) go to 900 + if(request%ft4%contest<0.or.request%ft4%contest>7) go to 900 + if(request%ft4%cq_only<0.or.request%ft4%cq_only>1) go to 900 + else if(request%mode==engine_mode_jt9) then + if(request%phase==1) go to 900 + if(request%jt9%search_low_hz<0.or.request%jt9%search_high_hz>5000.or. & + request%jt9%search_low_hz>request%jt9%search_high_hz) go to 900 + if(request%jt9%receive_frequency_hz<0.or.request%jt9%receive_frequency_hz>5000) go to 900 + if(request%jt9%tolerance_hz<0.or.request%jt9%tolerance_hz>5000) go to 900 + if(request%jt9%depth<1.or.request%jt9%depth>3) go to 900 + if(request%jt9%submode<0.or.request%jt9%submode>7) go to 900 + else if(request%mode==engine_mode_jt65) then + if(request%phase==1) go to 900 + if(.not.valid_jt65_options(request%jt65)) go to 900 + else if(request%mode==engine_mode_q65) then + if(request%phase==1) go to 900 + if(.not.valid_q65_options(request%q65)) go to 900 + else if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) then + if(request%phase==1) go to 900 + if(.not.valid_fst4_options(request%fst4)) go to 900 + else + if(request%ft8%search_low_hz<0.or.request%ft8%search_high_hz>6000.or. & + request%ft8%search_low_hz>request%ft8%search_high_hz) go to 900 + if(request%ft8%half_symbol_stage<41.or.request%ft8%half_symbol_stage>50) go to 900 + if(request%ft8%reuse_spectrum<0.or.request%ft8%reuse_spectrum>1) go to 900 + if(request%ft8%threads<0.or.request%ft8%threads>24) go to 900 + endif + if(session%input_id/=0.and.session%input_id/=request%input_id) go to 900 + if(session%input_id/=0.and.session%input_mode/=request%mode) go to 900 + if(request%mode==engine_mode_q65.and.session%input_id/=0) then + if(audio%sample_count/=session%input_sample_count) go to 900 + endif + if((request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w).and.session%input_id/=0) then + if(audio%sample_count/=session%input_sample_count) go to 900 + if(request%fst4%period_seconds/=session%request%fst4%period_seconds) go to 900 + endif + if(session%analysis_id==request%analysis_id.and.request%attempt_no<=session%last_attempt) go to 900 + + if(size(session%audio)<analysis_samples) then + deallocate(session%audio) + allocate(session%audio(analysis_samples)) + endif + session%running=.true. + session%request=request + session%input_id=request%input_id + session%input_mode=request%mode + session%input_sample_count=audio%sample_count + session%analysis_id=request%analysis_id + session%last_attempt=request%attempt_no + session%callback=callback + session%user=user + session%render_legacy=render + session%emitted=0 + call c_f_pointer(audio%samples,samples,[audio%sample_count]) + session%audio(1:audio%sample_count)=samples + session%audio(audio%sample_count+1:analysis_samples)=0 + status=ok + context%sink=>collect_observation + context%superfox_sink=>collect_superfox + context%sink_user=handle + context%render_legacy=render + if(request%mode==engine_mode_ft4) then + call run_ft4_attempt(request%ft4,request%phase,context,progress) + else if(request%mode==engine_mode_jt9) then + call run_jt9_attempt(request%jt9,request%phase,audio%sample_count,context,progress) + else if(request%mode==engine_mode_jt65) then + call run_jt65_attempt(request%jt65,request%phase,audio%sample_count,context,progress) + else if(request%mode==engine_mode_q65) then + call run_q65_attempt(request%q65,request%phase,audio%sample_count,context,progress,status) + else if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) then + call run_fst4_attempt(request%fst4,request%mode,request%phase,context,progress,status) + else + call request_to_params(request,audio%sample_count,params) + call run_ft8_kernel(session%kernel,session%knowledge,session%audio(:180000), & + params,session%completion,progress,context) + endif + outcome%observation_count=session%emitted + outcome%retained_count=session%retained + outcome%evidence_dropped=session%dropped + session%callback=c_null_funptr + session%user=c_null_ptr + session%running=.false. +900 outcome%status=status + end function + + subroutine open_legacy_output(phase,ios) + integer, intent(in) :: phase + integer, intent(out) :: ios + integer :: tries + + do tries=1,4 + if(phase==3) then + open(13,file=trim(temp_dir)//'/decoded.txt',status='unknown',position='append',iostat=ios) + else + open(13,file=trim(temp_dir)//'/decoded.txt',status='unknown',iostat=ios) + endif + if(ios==0) exit + if(tries<4) call sleep_msec(10) + enddo + end subroutine open_legacy_output + + subroutine run_ft4_attempt(options,phase,callback_context,progress) + type(ft4_options), intent(in) :: options + integer, intent(in) :: phase,progress + type(decoder_callback_context), intent(in) :: callback_context + type(decoder_callback_context) :: context + character(len=12) :: mycall,hiscall + + context=callback_context + context%nutc=options%utc + context%nfqso=options%receive_frequency_hz + context%ncontest=options%contest + context%ios13=-1 + if(context%render_legacy) call open_legacy_output(phase,context%ios13) + session%ft4%context=context + session%ft4%decoded=0 + mycall=transfer(options%mycall,mycall) + hiscall=transfer(options%hiscall,hiscall) + if(any(session%audio(:72576)/=0)) then + call timer('decft4 ',0) + call session%ft4%decode(ft4_decoded,session%audio(:72576),options%qso_progress, & + options%receive_frequency_hz,options%search_low_hz,options%search_high_hz, & + options%depth,options%cq_only/=0,options%contest,mycall,hiscall,session%knowledge) + call timer('decft4 ',1) + endif + call set_decode_completion(session%completion,0,session%ft4%decoded,0) + call write_decode_progress(progress) + if(context%ios13==0) close(13) + end subroutine + + subroutine run_jt9_attempt(options,phase,sample_count,callback_context,progress) + type(jt9_options), intent(in) :: options + integer, intent(in) :: phase,sample_count,progress + type(decoder_callback_context), intent(in) :: callback_context + type(decoder_callback_context) :: context + + context=callback_context + context%nutc=options%utc + context%nfqso=options%receive_frequency_hz + context%submode=options%submode + context%ios13=-1 + session%jt9%decoded=0 + if(sqrt(sum(real(session%audio(:sample_count))**2)/real(sample_count))<0.5) go to 100 + if(context%render_legacy) call open_legacy_output(phase,context%ios13) + session%jt9%context=context + call timer('decjt9 ',0) + call session%jt9%decode_pcm(jt9_decoded,session%audio,sample_count,options%receive_frequency_hz, & + options%search_low_hz,options%search_high_hz,options%tolerance_hz,options%depth, & + options%submode,phase==3) + call timer('decjt9 ',1) + if(context%ios13==0) close(13) +100 call set_decode_completion(session%completion,0,session%jt9%decoded,0) + call write_decode_progress(progress) + end subroutine + + logical function valid_jt65_options(options) result(valid) + type(engine_jt65_options), intent(in) :: options + valid=.false. + if(options%search_low_hz<0.or.options%search_high_hz>5000.or. & + options%search_low_hz>options%search_high_hz) return + if(options%receive_frequency_hz<0.or.options%receive_frequency_hz>5000) return + if(options%tolerance_hz<0.or.options%tolerance_hz>5000) return + if(options%depth<1.or.options%depth>3.or.options%submode<0.or.options%submode>2) return + if(options%passes<1.or.options%passes>2) return + if(options%trials<0.or.options%trials>1000000) return + if(options%aggressiveness<0.or.options%aggressiveness>11) return + if(options%qso_progress<0.or.options%qso_progress>5) return + if(any([options%single_decode,options%vhf,options%averaging,options%auto_clear, & + options%deep_search,options%ap_enabled]<0)) return + if(any([options%single_decode,options%vhf,options%averaging,options%auto_clear, & + options%deep_search,options%ap_enabled]>1)) return + valid=.true. + end function + + subroutine run_jt65_attempt(options,phase,sample_count,callback_context,progress) + type(engine_jt65_options), intent(in) :: options + integer, intent(in) :: phase,sample_count,progress + type(decoder_callback_context), intent(in) :: callback_context + type(decoder_callback_context) :: context + type(jt65_options) :: kernel_options + logical, external :: baddata + + context=callback_context + context%nutc=options%utc + context%nfqso=options%receive_frequency_hz + context%submode=options%submode + context%bVHF=options%vhf/=0 + context%ios13=-1 + context%ios14=-1 + if(context%render_legacy) then + call open_legacy_output(phase,context%ios13) + open(14,file=trim(temp_dir)//'/avemsg.txt',status='unknown',iostat=context%ios14) + endif + session%jt65%context=context + session%jt65%decoded=0 + kernel_options%utc=options%utc + kernel_options%low_frequency=options%search_low_hz + kernel_options%high_frequency=options%search_high_hz + kernel_options%receive_frequency=options%receive_frequency_hz + kernel_options%tolerance=options%tolerance_hz + kernel_options%submode=options%submode + kernel_options%min_sync=options%min_sync + kernel_options%passes=options%passes + kernel_options%trials=options%trials + kernel_options%aggressiveness=options%aggressiveness + kernel_options%effort=options%depth + kernel_options%qso_progress=options%qso_progress + kernel_options%repeat=phase==3 + kernel_options%single_decode=options%single_decode/=0 + kernel_options%vhf=options%vhf/=0 + kernel_options%average=options%averaging/=0 + kernel_options%auto_clear=options%auto_clear/=0 + kernel_options%deep_search=options%deep_search/=0 + kernel_options%ap=options%ap_enabled/=0 + kernel_options%mycall=transfer(options%mycall,kernel_options%mycall) + kernel_options%hiscall=transfer(options%hiscall,kernel_options%hiscall) + kernel_options%hisgrid=transfer(options%hisgrid,kernel_options%hisgrid) + call timer('decjt65 ',0) + if(.not.baddata(session%audio,52*12000)) then + call session%jt65%decode_pcm(jt65_decoded,session%audio,sample_count,kernel_options,session%input_id) + endif + call timer('decjt65 ',1) + if(context%ios14==0) then + call write_jt65_averages(session%jt65,14) + close(14) + endif + if(context%ios13==0) close(13) + call set_decode_completion(session%completion,0,session%jt65%decoded,0) + call write_decode_progress(progress) + end subroutine + + integer(c_int) function engine_set_jt65_calls(handle,entries,count) & + bind(C,name='decoder_engine_set_jt65_calls') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: count + type(engine_jt65_call), pointer :: records(:) + character(len=12), allocatable :: calls(:) + character(len=4), allocatable :: grids(:) + integer :: i + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(count<0.or.count>10000) return + if(count>0.and..not.c_associated(entries)) return + allocate(calls(count),grids(count)) + if(count>0) then + call c_f_pointer(entries,records,[count]) + do i=1,count + calls(i)=transfer(records(i)%call,calls(i)) + grids(i)=transfer(records(i)%grid,grids(i)) + enddo + endif + call session%jt65%set_calls(calls,grids) + status=ok + end function + + integer(c_int) function engine_get_jt65_averages(handle,entries,entry_capacity,count) & + bind(C,name='decoder_engine_get_jt65_averages') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: entry_capacity + integer(c_int), intent(out) :: count + type(engine_jt65_average_entry), pointer :: records(:) + type(jt65_average_entry) :: averages(64) + integer :: i,n + count=0 + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(entry_capacity<0) return + if(entry_capacity>0.and..not.c_associated(entries)) return + call session%jt65%get_averages(averages,n) + count=n + if(entry_capacity>0) then + call c_f_pointer(entries,records,[entry_capacity]) + do i=1,min(entry_capacity,n) + records(i)%utc=averages(i)%utc + records(i)%frequency_hz=averages(i)%frequency + records(i)%polarity=averages(i)%polarity + records(i)%used=merge(1,0,averages(i)%used) + records(i)%sync=averages(i)%sync + records(i)%dt_seconds=averages(i)%dt + enddo + endif + status=ok + if(entry_capacity>0.and.entry_capacity<n) status=capacity + end function + + integer(c_int) function engine_clear_jt65_averages(handle) & + bind(C,name='decoder_engine_clear_jt65_averages') result(status) + type(c_ptr), value :: handle + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + call session%jt65%clear_averages() + status=ok + end function + + logical function valid_fst4_options(options) result(valid) + type(engine_fst4_options), intent(in) :: options + integer :: hours,minutes,seconds + valid=.false. + if(analysis_extent(engine_mode_fst4,options%period_seconds)==0) return + if(options%depth<1.or.options%depth>3) return + if(options%qso_progress<0.or.options%qso_progress>5) return + if(options%search_low_hz<0.or.options%search_high_hz>5000.or. & + options%search_low_hz>=options%search_high_hz) return + if(options%receive_frequency_hz<0.or.options%receive_frequency_hz>5000) return + if(options%tolerance_hz<0.or.options%tolerance_hz>5000) return + if(.not.any(options%blanker_mode==[0,1,2,5])) return + if(options%blanker_percent<0.or.options%blanker_percent>25) return + if(.not.ieee_is_finite(options%eme_delay_seconds)) return + if(options%eme_delay_seconds<0.or.options%eme_delay_seconds>real(options%period_seconds)) return + if(any([options%single_decode,options%ap_cq_only,options%measure_doppler]<0)) return + if(any([options%single_decode,options%ap_cq_only,options%measure_doppler]>1)) return + hours=options%utc/10000 + minutes=mod(options%utc/100,100) + seconds=mod(options%utc,100) + if(options%utc<0.or.hours>23.or.minutes>59.or.seconds>59) return + valid=.true. + end function + + subroutine run_fst4_attempt(options,mode,phase,callback_context,progress,status) + type(engine_fst4_options), intent(in) :: options + integer, intent(in) :: mode,phase,progress + type(decoder_callback_context), intent(in) :: callback_context + integer(c_int), intent(out) :: status + type(decoder_callback_context) :: context + type(fst4_options) :: kernel_options + integer :: kernel_status + + kernel_options=fst4_options() + context=callback_context + context%nutc=options%utc + context%utc_is_hhmmss=.true. + context%mode=mode + context%nfqso=options%receive_frequency_hz + context%ios13=-1 + if(context%render_legacy) call open_legacy_output(phase,context%ios13) + session%fst4%context=context + session%fst4%decoded=0 + session%fst4%knowledge=>session%knowledge + kernel_options%utc=options%utc + kernel_options%period=options%period_seconds + kernel_options%receive_frequency=options%receive_frequency_hz + kernel_options%low_frequency=options%search_low_hz + kernel_options%high_frequency=options%search_high_hz + kernel_options%tolerance=options%tolerance_hz + kernel_options%effort=options%depth + kernel_options%qso_progress=options%qso_progress + kernel_options%blanker_percent=options%blanker_percent + kernel_options%blanker_step=options%blanker_mode + kernel_options%eme_delay=options%eme_delay_seconds + kernel_options%wspr=mode==engine_mode_fst4w + kernel_options%single_decode=options%single_decode/=0 + kernel_options%ap_cq_only=options%ap_cq_only/=0 + kernel_options%measure_doppler=options%measure_doppler/=0 + kernel_options%mycall=transfer(options%mycall,kernel_options%mycall) + kernel_options%hiscall=transfer(options%hiscall,kernel_options%hiscall) + if(context%render_legacy) call prepare_fst4_host(session%fst4,kernel_options) + call timer('dec_fst4',0) + call session%fst4%decode_pcm(fst4_decoded,session%audio,options%period_seconds*12000,kernel_options, & + kernel_status) + call timer('dec_fst4',1) + if(context%render_legacy) call finish_fst4_host(session%fst4) + if(context%ios13==0) close(13) + call set_decode_completion(session%completion,0,session%fst4%decoded,0) + call write_decode_progress(progress) + status=ok + if(kernel_status/=0) status=internal_error + end subroutine + + integer(c_int) function engine_set_fst4w_calls(handle,entries,count) & + bind(C,name='decoder_engine_set_fst4w_calls') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: count + type(engine_fst4w_call), pointer :: records(:) + character(len=20), allocatable :: calls(:) + integer :: i,kernel_status + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(count<0.or.count>100) return + if(count>0.and..not.c_associated(entries)) return + allocate(calls(count)) + if(count>0) then + call c_f_pointer(entries,records,[count]) + do i=1,count + calls(i)=transfer(records(i)%call_grid,calls(i)) + enddo + endif + call session%fst4%set_known_calls(calls,kernel_status) + if(kernel_status/=0) return + status=ok + end function + + integer(c_int) function engine_get_fst4w_calls(handle,entries,entry_capacity,count) & + bind(C,name='decoder_engine_get_fst4w_calls') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: entry_capacity + integer(c_int), intent(out) :: count + type(engine_fst4w_call), pointer :: records(:) + character(len=20) :: calls(100) + integer :: i,n + count=0 + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(entry_capacity<0) return + if(entry_capacity>0.and..not.c_associated(entries)) return + call session%fst4%get_known_calls(calls,n) + count=n + if(entry_capacity>0) then + call c_f_pointer(entries,records,[entry_capacity]) + do i=1,min(entry_capacity,n) + records(i)%call_grid=transfer(calls(i),records(i)%call_grid) + enddo + endif + status=ok + if(entry_capacity>0.and.entry_capacity<n) status=capacity + end function + + + logical function valid_q65_options(options) result(valid) + type(engine_q65_options), intent(in) :: options + integer :: hours,minutes,seconds + valid=.false. + if(.not.any(options%period_seconds==[15,30,60,120,300])) return + if(options%submode<0.or.options%submode>5) return + if(options%depth<1.or.options%depth>3) return + if(options%max_drift_symbol_rates<0.or.options%max_drift_symbol_rates>50) return + if(options%search_low_hz<0.or.options%search_high_hz>5000.or. & + options%search_low_hz>=options%search_high_hz) return + if(options%receive_frequency_hz<0.or.options%receive_frequency_hz>5000) return + if(options%tolerance_hz<0.or.options%tolerance_hz>5000) return + if(options%qso_progress<0.or.options%qso_progress>5) return + if(options%contest<0.or.options%contest>7) return + if(any([options%averaging,options%auto_clear,options%single_decode,options%extended_eme_search, & + options%pileup,options%ap_cq_only]<0)) return + if(any([options%averaging,options%auto_clear,options%single_decode,options%extended_eme_search, & + options%pileup,options%ap_cq_only]>1)) return + hours=options%utc/10000 + minutes=mod(options%utc/100,100) + seconds=mod(options%utc,100) + if(options%utc<0.or.hours>23.or.minutes>59.or.seconds>59) return + valid=.true. + end function + + subroutine run_q65_attempt(options,phase,sample_count,callback_context,progress,status) + type(engine_q65_options), intent(in) :: options + integer, intent(in) :: phase,sample_count,progress + type(decoder_callback_context), intent(in) :: callback_context + integer(c_int), intent(out) :: status + type(decoder_callback_context) :: context + type(q65_options) :: kernel_options + integer :: kernel_status,even_count,odd_count,count + real :: df,dt,empty_current(0),empty_average(0) + + context=callback_context + context%nutc=options%utc + context%submode=options%submode + context%utc_is_hhmmss=.true. + context%ios13=-1 + if(context%render_legacy) call open_legacy_output(phase,context%ios13) + session%q65%context=context + session%q65%decoded=0 + nullify(session%q65%diagnostic) + if(context%render_legacy) session%q65%diagnostic=>write_q65_diagnostic + kernel_options%utc=options%utc + kernel_options%period=options%period_seconds + kernel_options%submode=options%submode + kernel_options%receive_frequency=options%receive_frequency_hz + kernel_options%tolerance=options%tolerance_hz + kernel_options%low_frequency=options%search_low_hz + kernel_options%high_frequency=options%search_high_hz + kernel_options%effort=options%depth + kernel_options%max_drift=options%max_drift_symbol_rates + kernel_options%qso_progress=options%qso_progress + kernel_options%contest=options%contest + kernel_options%now=options%now_seconds + kernel_options%repeat=phase==3 + kernel_options%single_decode=options%single_decode/=0 + kernel_options%average=options%averaging/=0 + kernel_options%auto_clear=options%auto_clear/=0 + kernel_options%eme=options%extended_eme_search/=0 + kernel_options%pileup=options%pileup/=0 + kernel_options%ap_cq_only=options%ap_cq_only/=0 + kernel_options%mycall=transfer(options%mycall,kernel_options%mycall) + kernel_options%hiscall=transfer(options%hiscall,kernel_options%hiscall) + kernel_options%hisgrid=transfer(options%hisgrid,kernel_options%hisgrid) + call timer('dec_q65 ',0) + call session%q65%decode_pcm(q65_decoded,session%audio,sample_count,kernel_options, & + session%input_id,kernel_status) + call timer('dec_q65 ',1) + if(context%render_legacy) call write_q65_curves(session%q65,kernel_options) + if(context%ios13==0) close(13) + nullify(session%q65%diagnostic) + call session%q65%get_curves(even_count,odd_count,df,dt,empty_current,empty_average,count) + call set_decode_completion(session%completion,0,session%q65%decoded,1000*even_count+odd_count) + call write_decode_progress(progress) + status=ok + if(kernel_status/=0) status=internal_error + end subroutine + + integer(c_int) function engine_set_q65_callers(handle,entries,count) & + bind(C,name='decoder_engine_set_q65_callers') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: count + type(engine_q65_caller), pointer :: records(:) + type(q3list) :: callers(Q65_MAX_CALLERS) + character(len=12) :: call + integer :: i + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(count<0.or.count>Q65_MAX_CALLERS) return + if(count>0.and..not.c_associated(entries)) return + callers=q3list('','',0,0,0) + if(count>0) then + call c_f_pointer(entries,records,[count]) + do i=1,count + call=transfer(records(i)%call,call) + if(len_trim(call)>6) return + callers(i)%call=call + callers(i)%grid=transfer(records(i)%grid,callers(i)%grid) + callers(i)%nsec=records(i)%last_seen + callers(i)%nfreq=records(i)%frequency_hz + if(callers(i)%nfreq<0.or.callers(i)%nfreq>5000) return + enddo + endif + call session%q65%set_callers(callers,count) + status=ok + end function + + integer(c_int) function engine_get_q65_callers(handle,entries,entry_capacity,count) & + bind(C,name='decoder_engine_get_q65_callers') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: entry_capacity + integer(c_int), intent(out) :: count + type(engine_q65_caller), pointer :: records(:) + type(q3list) :: callers(Q65_MAX_CALLERS) + character(len=12) :: call + integer :: i,n + count=0 + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(entry_capacity<0) return + if(entry_capacity>0.and..not.c_associated(entries)) return + call session%q65%get_callers(callers,n) + count=n + if(entry_capacity>0) then + call c_f_pointer(entries,records,[entry_capacity]) + do i=1,min(entry_capacity,n) + call=callers(i)%call + records(i)%call=transfer(call,records(i)%call) + records(i)%grid=transfer(callers(i)%grid,records(i)%grid) + records(i)%last_seen=callers(i)%nsec + records(i)%frequency_hz=callers(i)%nfreq + enddo + endif + status=ok + if(entry_capacity>0.and.entry_capacity<n) status=capacity + end function + + integer(c_int) function engine_get_q65_snapshot(handle,snapshot,instant,averaged,curve_capacity) & + bind(C,name='decoder_engine_get_q65_snapshot') result(status) + type(c_ptr), value :: handle,instant,averaged + type(engine_q65_snapshot), intent(out) :: snapshot + integer(c_int), value :: curve_capacity + real(c_float), pointer :: current(:),average(:) + real :: empty_current(0),empty_average(0) + snapshot=engine_q65_snapshot() + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(curve_capacity<0) return + if(curve_capacity>0) then + if(.not.c_associated(instant).or..not.c_associated(averaged)) return + call c_f_pointer(instant,current,[curve_capacity]) + call c_f_pointer(averaged,average,[curve_capacity]) + call session%q65%get_curves(snapshot%even_count,snapshot%odd_count,snapshot%frequency_step_hz, & + snapshot%dt_seconds,current,average,snapshot%curve_count,snapshot%curve_average_count) + else + call session%q65%get_curves(snapshot%even_count,snapshot%odd_count,snapshot%frequency_step_hz, & + snapshot%dt_seconds,empty_current,empty_average,snapshot%curve_count,snapshot%curve_average_count) + endif + status=ok + if(curve_capacity>0.and.curve_capacity<snapshot%curve_count) status=capacity + end function + + integer(c_int) function engine_clear_q65_averages(handle) & + bind(C,name='decoder_engine_clear_q65_averages') result(status) + type(c_ptr), value :: handle + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + call session%q65%clear_averages() + status=ok + end function + + subroutine collect_observation(user,observation) + type(c_ptr), intent(in) :: user + type(engine_observation), intent(in) :: observation + type(engine_observation) :: record + procedure(observation_callback), pointer :: callback + if(.not.valid_handle(user)) return + record=observation + record%input_id=session%request%input_id + record%analysis_id=session%request%analysis_id + record%attempt_no=session%request%attempt_no + session%emitted=session%emitted+1 + if(session%retained<evidence_capacity) then + session%retained=session%retained+1 + session%evidence(session%retained)=record + else + session%dropped=session%dropped+1 + endif + if(c_associated(session%callback)) then + call c_f_procpointer(session%callback,callback) + call callback(record,session%user) + endif + end subroutine + + subroutine collect_superfox(user,observation) + type(c_ptr), intent(in) :: user + type(superfox_observation), intent(in) :: observation + type(engine_observation) :: record + integer :: i + record%variant=2 + record%superfox%kind=observation%kind + record%superfox%child_index=observation%child_index + record%snr_db=observation%snr_db + record%frequency_hz=observation%frequency_hz + record%dt_seconds=observation%dt_seconds + record%superfox%symbols=observation%symbols + do i=1,min(37,len_trim(observation%message)) + record%message(i)=observation%message(i:i) + enddo + call collect_observation(user,record) + if(session%render_legacy.and.observation%legacy_line_length>0) then + write(*,'(a)') observation%legacy_line(:observation%legacy_line_length) + flush(6) + endif + end subroutine + + integer(c_int) function engine_release_input(handle,input_id) & + bind(C,name='decoder_engine_release_input') result(status) + type(c_ptr), value :: handle + integer(c_int64_t), value :: input_id + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(input_id<=0.or.session%input_id/=input_id) return + call release_ft8_input(session%kernel) + call session%jt9%release_input() + call session%jt65%release_input() + call session%q65%release_input() + session%input_id=0 + session%input_mode=0 + session%input_sample_count=0 + session%analysis_id=0 + session%last_attempt=0 + session%retained=0 + session%dropped=0 + status=ok + end function + + integer(c_int) function engine_reset_session(handle) bind(C,name='decoder_engine_reset_session') result(status) + type(c_ptr), value :: handle + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + call reset_ft8_kernel(session%kernel) + call session%ft4%reset() + call session%jt9%reset() + call session%jt65%reset() + call session%q65%reset() + call session%fst4%reset() + call reset_pack77_state(session%knowledge) + session%input_id=0 + session%input_mode=0 + session%input_sample_count=0 + session%analysis_id=0 + session%last_attempt=0 + session%retained=0 + session%dropped=0 + status=ok + end function + + integer(c_int) function engine_destroy(handle) bind(C,name='decoder_engine_destroy') result(status) + type(c_ptr), value :: handle + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + call reset_ft8_kernel(session%kernel) + call session%fst4%destroy() + deallocate(session) + host_handle=c_null_ptr + status=ok + end function + + subroutine request_to_params(request,valid_samples,params) + type(attempt_request), intent(in) :: request + integer, intent(in) :: valid_samples + type(params_block), intent(out) :: params + integer(c_int8_t) :: zeros(c_sizeof(params)) + zeros=0 + params=transfer(zeros,params) + params%nmode=8 + params%ntr=15 + params%kin=valid_samples + params%ndiskdat=request%source==1 + params%nagain=request%phase==3 + params%newdat=request%ft8%reuse_spectrum==0 + params%nzhsym=request%ft8%half_symbol_stage + params%nutc=request%ft8%utc + params%nQSOProgress=request%ft8%qso_progress + params%nfqso=request%ft8%receive_frequency_hz + params%nftx=request%ft8%transmit_frequency_hz + params%nfa=request%ft8%search_low_hz + params%nfb=request%ft8%search_high_hz + params%ntol=request%ft8%tolerance_hz + params%ndepth=request%ft8%depth + params%napwid=request%ft8%ap_width_hz + params%nexp_decode=request%ft8%contest + params%ncandthin=request%ft8%candidate_thinning + params%ndtcenter=request%ft8%time_center + params%nft8cycles=request%ft8%cycles + params%nranera=request%ft8%trials + params%nlasttx=request%ft8%last_transmit + params%ndelay=request%ft8%delay + params%nmt=request%ft8%threads + params%nft8rxfsens=request%ft8%receive_sensitivity + params%nsecbandchanged=request%ft8%discard_leading_seconds + params%yymmdd=request%ft8%date + params%lft8apon=request%ft8%ap_enabled/=0 + params%lapcqonly=request%ft8%cq_only/=0 + params%b_even_seq=request%ft8%even_sequence/=0 + params%b_superfox=request%ft8%superfox/=0 + params%nagainfil=request%ft8%filtered_retry/=0 + params%nstophint=request%ft8%stop_hint/=0 + params%lmultift8=request%ft8%mtd/=0 + params%lft8lowth=request%ft8%low_threshold/=0 + params%lft8subpass=request%ft8%subtract_pass/=0 + params%ltxing=request%ft8%transmitting/=0 + params%lhideft8dupes=request%ft8%hide_duplicates/=0 + params%lhound=request%ft8%hound/=0 + params%lmycallstd=request%ft8%standard_mycall/=0 + params%lhiscallstd=request%ft8%standard_hiscall/=0 + params%lapmyc=request%ft8%ap_mycall/=0 + params%lmodechanged=request%ft8%mode_changed/=0 + params%lbandchanged=request%ft8%band_changed/=0 + params%lenabledxcsearch=request%ft8%dx_search/=0 + params%lwidedxcsearch=request%ft8%wide_dx_search/=0 + params%lmultinst=request%ft8%multiple_instances/=0 + params%lskiptx1=request%ft8%skip_first_message/=0 + params%emedelay=request%ft8%eme_delay_seconds + params%mycall=request%ft8%mycall + params%mybcall=request%ft8%my_base_call + params%hiscall=request%ft8%hiscall + params%hisbcall=request%ft8%his_base_call + params%mygrid=request%ft8%mygrid + params%hisgrid=request%ft8%hisgrid + end subroutine + + subroutine engine_host_decode(id2,params,nfsample,completion,progress,input_id,analysis_id,attempt_no,valid_samples) + integer(c_short), target, intent(in) :: id2(*) + type(params_block), intent(in) :: params + integer, intent(in) :: nfsample,progress,attempt_no,valid_samples + integer(c_int64_t), intent(in) :: input_id,analysis_id + type(decode_completion_result), intent(out) :: completion + type(attempt_request) :: request + type(audio_view) :: audio + type(attempt_outcome) :: outcome + type(engine_options) :: options + integer(c_int) :: status + integer :: time,history_status,blanker,period_samples + character(len=12), allocatable :: calls(:) + character(len=4), allocatable :: grids(:) + options%abi_version=engine_abi + completion=decode_completion_result(.true.,0,0,0) + if(params%nmode==engine_mode_ft4) then + ! The legacy host's low-signal gate includes its zero-padded 15-second window. + if(sqrt(sum(real(id2(1:180000))**2)/180000.0)<0.5) return + endif + request%input_id=input_id + request%mode=params%nmode + if(request%mode==242) request%mode=engine_mode_fst4w + request%analysis_id=analysis_id + request%attempt_no=attempt_no + if(.not.valid_handle(host_handle)) then + status=engine_create(options,host_handle) + if(status/=ok) then + call report_host_rejection(status,request,'create') + return + endif + endif + if(input_id<=0.or.analysis_id<=0) then + if(session%input_id==0.or.params%nutc/=fallback_utc.or.session%input_mode/=request%mode.or. & + ((params%nmode==engine_mode_ft4.or.params%nmode==engine_mode_jt9.or. & + params%nmode==engine_mode_jt65.or.params%nmode==engine_mode_q65.or. & + request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w).and..not.params%nagain).or. & + (params%nzhsym==41.and..not.params%nagain)) then + fallback_input=fallback_input+1 + fallback_analysis=fallback_analysis+1 + else if(params%nagain) then + fallback_analysis=fallback_analysis+1 + endif + request%input_id=max(1_c_int64_t,fallback_input) + request%analysis_id=max(1_c_int64_t,fallback_analysis) + request%attempt_no=session%last_attempt+1 + fallback_utc=params%nutc + endif + if(session%input_id/=0.and.(session%input_id/=request%input_id.or.session%input_mode/=request%mode)) then + status=engine_release_input(host_handle,session%input_id) + if(status/=ok) then + call report_host_rejection(status,request,'release-input') + return + endif + endif + request%phase=2 + if(params%nmode==engine_mode_ft8.and.params%nzhsym<50) request%phase=1 + if(params%nagain) request%phase=3 + request%source=merge(1,0,params%ndiskdat) + if(request%mode==engine_mode_ft4) then + request%ft4%utc=params%nutc + request%ft4%qso_progress=params%nQSOProgress + request%ft4%receive_frequency_hz=params%nfqso + request%ft4%search_low_hz=params%nfa + request%ft4%search_high_hz=params%nfb + request%ft4%depth=iand(params%ndepth,7) + request%ft4%cq_only=merge(1,0,params%lapcqonly) + request%ft4%contest=iand(params%nexp_decode,7) + request%ft4%mycall=params%mycall + request%ft4%hiscall=params%hiscall + else if(request%mode==engine_mode_jt9) then + request%jt9%utc=params%nutc + request%jt9%receive_frequency_hz=params%nfqso + request%jt9%search_low_hz=params%nfa + request%jt9%search_high_hz=params%nfb + request%jt9%tolerance_hz=params%ntol + request%jt9%depth=iand(params%ndepth,7) + request%jt9%submode=params%nsubmode + else if(request%mode==engine_mode_jt65) then + request%jt65%utc=params%nutc + request%jt65%qso_progress=params%nQSOProgress + request%jt65%receive_frequency_hz=params%nfqso + request%jt65%search_low_hz=params%nfa + request%jt65%search_high_hz=params%nfb + request%jt65%tolerance_hz=params%ntol + request%jt65%depth=iand(params%ndepth,7) + request%jt65%submode=params%nsubmode + request%jt65%min_sync=params%minsync + request%jt65%passes=max(1,min(2,params%n2pass)) + request%jt65%trials=10**(params%nranera/2) + if(mod(params%nranera,2)==1) request%jt65%trials=3*request%jt65%trials + if(params%nranera==0) request%jt65%trials=0 + request%jt65%aggressiveness=params%naggressive + request%jt65%single_decode=merge(1,0,iand(params%nexp_decode,32)/=0) + request%jt65%vhf=merge(1,0,iand(params%nexp_decode,64)/=0) + request%jt65%averaging=merge(1,0,iand(params%ndepth,16)/=0) + request%jt65%auto_clear=merge(1,0,iand(params%ndepth,128)/=0) + request%jt65%deep_search=merge(1,0,iand(params%ndepth,32)/=0) + request%jt65%ap_enabled=merge(1,0,params%ljt65apon) + request%jt65%mycall=params%mycall + request%jt65%hiscall=params%hiscall + request%jt65%hisgrid=params%hisgrid + if(params%nclearave) call session%jt65%clear_averages() + if(request%jt65%deep_search/=0) then + call load_jt65_calls(calls,grids) + call session%jt65%set_calls(calls,grids) + endif + else if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) then + request%fst4%utc=params%nutc + request%fst4%period_seconds=params%ntr + request%fst4%receive_frequency_hz=params%nfqso + request%fst4%search_low_hz=max(0,params%nfa) + request%fst4%search_high_hz=min(params%nfb,5000) + request%fst4%tolerance_hz=params%ntol + request%fst4%depth=iand(params%ndepth,3) + request%fst4%qso_progress=params%nQSOProgress + request%fst4%single_decode=merge(1,0,iand(params%nexp_decode,32)/=0) + request%fst4%ap_cq_only=merge(1,0,params%lapcqonly) + blanker=params%nexp_decode/256-3 + if(blanker>=0) then + request%fst4%blanker_percent=blanker + else + select case(blanker) + case(-1); request%fst4%blanker_mode=5 + case(-2); request%fst4%blanker_mode=2 + case(-3); request%fst4%blanker_mode=1 + end select + endif + session%fst4%print_hash22=params%nmode==242 + request%fst4%eme_delay_seconds=params%emedelay + request%fst4%mycall=params%mycall + request%fst4%hiscall=params%hiscall + else if(request%mode==engine_mode_q65) then + request%q65%utc=params%nutc + request%q65%period_seconds=params%ntr + request%q65%submode=params%nsubmode + request%q65%receive_frequency_hz=params%nfqso + request%q65%tolerance_hz=params%ntol + request%q65%search_low_hz=params%nfa + request%q65%search_high_hz=min(params%nfb,5000) + request%q65%depth=iand(params%ndepth,3) + request%q65%max_drift_symbol_rates=params%max_drift + request%q65%qso_progress=params%nQSOProgress + request%q65%contest=iand(params%nexp_decode,7) + request%q65%averaging=merge(1,0,iand(params%ndepth,16)/=0) + request%q65%auto_clear=merge(1,0,iand(params%ndepth,128)/=0) + request%q65%single_decode=merge(1,0,iand(params%nexp_decode,32)/=0) + request%q65%extended_eme_search=merge(1,0,params%emedelay>0) + request%q65%pileup=merge(1,0,iand(params%nexp_decode,128)/=0) + request%q65%ap_cq_only=merge(1,0,params%lapcqonly) + request%q65%now_seconds=time() + request%q65%mycall=params%mycall + request%q65%hiscall=params%hiscall + request%q65%hisgrid=params%hisgrid + if(params%nclearave) call session%q65%clear_averages() + history_status=0 + if(request%q65%contest==1) call load_q65_history(session%q65,history_status) + else + request%ft8%reuse_spectrum=merge(0,1,params%newdat) + request%ft8%half_symbol_stage=params%nzhsym + request%ft8%utc=params%nutc + request%ft8%qso_progress=params%nQSOProgress + request%ft8%receive_frequency_hz=params%nfqso + request%ft8%transmit_frequency_hz=params%nftx + request%ft8%search_low_hz=params%nfa + request%ft8%search_high_hz=params%nfb + request%ft8%tolerance_hz=params%ntol + request%ft8%depth=params%ndepth + request%ft8%ap_width_hz=params%napwid + request%ft8%contest=params%nexp_decode + request%ft8%candidate_thinning=params%ncandthin + request%ft8%time_center=params%ndtcenter + request%ft8%cycles=params%nft8cycles + request%ft8%trials=params%nranera + request%ft8%last_transmit=params%nlasttx + request%ft8%delay=params%ndelay + request%ft8%threads=params%nmt + request%ft8%receive_sensitivity=params%nft8rxfsens + request%ft8%discard_leading_seconds=params%nsecbandchanged + request%ft8%date=params%yymmdd + request%ft8%ap_enabled=merge(1,0,params%lft8apon) + request%ft8%cq_only=merge(1,0,params%lapcqonly) + request%ft8%even_sequence=merge(1,0,params%b_even_seq) + request%ft8%superfox=merge(1,0,params%b_superfox) + request%ft8%filtered_retry=merge(1,0,params%nagainfil) + request%ft8%stop_hint=merge(1,0,params%nstophint) + request%ft8%mtd=merge(1,0,params%lmultift8) + request%ft8%low_threshold=merge(1,0,params%lft8lowth) + request%ft8%subtract_pass=merge(1,0,params%lft8subpass) + request%ft8%transmitting=merge(1,0,params%ltxing) + request%ft8%hide_duplicates=merge(1,0,params%lhideft8dupes) + request%ft8%hound=merge(1,0,params%lhound) + request%ft8%standard_mycall=merge(1,0,params%lmycallstd) + request%ft8%standard_hiscall=merge(1,0,params%lhiscallstd) + request%ft8%ap_mycall=merge(1,0,params%lapmyc) + request%ft8%mode_changed=merge(1,0,params%lmodechanged) + request%ft8%band_changed=merge(1,0,params%lbandchanged) + request%ft8%dx_search=merge(1,0,params%lenabledxcsearch) + request%ft8%wide_dx_search=merge(1,0,params%lwidedxcsearch) + request%ft8%multiple_instances=merge(1,0,params%lmultinst) + request%ft8%skip_first_message=merge(1,0,params%lskiptx1) + request%ft8%eme_delay_seconds=params%emedelay + request%ft8%mycall=params%mycall + request%ft8%my_base_call=params%mybcall + request%ft8%hiscall=params%hiscall + request%ft8%his_base_call=params%hisbcall + request%ft8%mygrid=params%mygrid + request%ft8%hisgrid=params%hisgrid + endif + audio%samples=c_loc(id2(1)) + period_samples=analysis_extent(request%mode,request%q65%period_seconds) + if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) & + period_samples=analysis_extent(request%mode,request%fst4%period_seconds) + audio%sample_count=min(period_samples,valid_samples) + if(valid_samples<=0.and.input_id<=0) then + audio%sample_count=period_samples + if(request%mode==engine_mode_jt9.or.request%mode==engine_mode_jt65) audio%sample_count=624000 + endif + if(request%mode==engine_mode_ft8) then + if(params%lmultift8.and..not.(iand(params%nexp_decode,7)==7.and. & + params%b_superfox.and.params%b_even_seq)) & + audio%sample_count=min(audio%sample_count,params%nzhsym*3456) + endif + audio%sample_rate_hz=nfsample + status=decode_attempt(host_handle,request,audio,c_null_funptr,c_null_ptr,outcome,.true.,progress) + if(status==ok) then + if(request%mode==engine_mode_q65.and.request%q65%contest==1) & + call save_q65_history(session%q65,history_status) + completion=session%completion + else + call report_host_rejection(status,request,'decode') + endif + end subroutine + + subroutine report_host_rejection(status,request,operation) + integer(c_int), intent(in) :: status + type(attempt_request), intent(in) :: request + character(len=*), intent(in) :: operation + character(len=12) :: status_name + select case(status) + case(invalid) + status_name='invalid' + case(busy) + status_name='busy' + case(unsupported) + status_name='unsupported' + case default + write(status_name,'(i0)') status + end select + write(*,'(a,a,a,a,4(a,i0))') '<DecodeRejected> status=',trim(status_name), & + ' operation=',operation,' mode=',request%mode,' input=',request%input_id, & + ' analysis=',request%analysis_id,' attempt=',request%attempt_no + flush(6) + end subroutine report_host_rejection +end module decoder_engine + +subroutine run_decoder_engine(id2,params,nfsample,completion,progress_generation, & + input_id,analysis_id,attempt_no,valid_samples) + use, intrinsic :: iso_c_binding, only: c_short,c_int,c_int64_t + use decoder_engine, only: engine_host_decode + use ft8_engine_kernel, only: params_block + use decode_completion_module, only: decode_completion_result + implicit none + integer(c_short), target, intent(in) :: id2(*) + type(params_block), intent(in) :: params + integer(c_int), intent(in) :: nfsample,progress_generation,attempt_no,valid_samples + integer(c_int64_t), intent(in) :: input_id,analysis_id + type(decode_completion_result), intent(out) :: completion + call engine_host_decode(id2,params,nfsample,completion,progress_generation,input_id,analysis_id,attempt_no,valid_samples) +end subroutine diff --git a/lib/decoder_engine_types.f90 b/lib/decoder_engine_types.f90 new file mode 100644 index 00000000..5c378646 --- /dev/null +++ b/lib/decoder_engine_types.f90 @@ -0,0 +1,99 @@ +module decoder_engine_types + use, intrinsic :: iso_c_binding + implicit none + private + public :: ft8_signal_evidence, ft4_signal_evidence, superfox_evidence, superfox_observation + public :: jt9_result,jt65_result,q65_result,fst4_result + public :: engine_payload_none,engine_payload_decoded,engine_payload_hypothesis + public :: sf_kind_cq,sf_kind_exchange,sf_kind_free_text,sf_kind_verification + public :: engine_observation, engine_observation_sink, engine_superfox_sink + public :: engine_abi,engine_mode_ft8,engine_mode_ft4,engine_mode_jt9,engine_mode_jt65,engine_mode_q65 + public :: engine_support_ft8,engine_support_ft4,engine_support_jt9,engine_support_jt65,engine_support_q65 + + integer(c_int), parameter :: engine_abi=7,engine_mode_ft8=8,engine_mode_ft4=5,engine_mode_jt9=9,engine_mode_jt65=65 + integer(c_int), parameter :: engine_support_ft8=1,engine_support_ft4=2,engine_support_jt9=4,engine_support_jt65=8 + + integer(c_int), parameter :: engine_mode_q65=66,engine_support_q65=16 + + public :: engine_mode_fst4,engine_mode_fst4w,engine_support_fst4,engine_support_fst4w + integer(c_int), parameter :: engine_mode_fst4=240,engine_mode_fst4w=241 + integer(c_int), parameter :: engine_support_fst4=32,engine_support_fst4w=64 + + integer, parameter :: engine_payload_none=0,engine_payload_decoded=1,engine_payload_hypothesis=2 + integer, parameter :: sf_kind_cq=1,sf_kind_exchange=2,sf_kind_free_text=3,sf_kind_verification=4 + + type, bind(C) :: ft8_signal_evidence + integer(c_int8_t) :: payload77(77)=0,tones(79)=0 + integer(c_int) :: payload_origin=engine_payload_none,has_tones=0,has_waveform_start=0,method=0 + real(c_float) :: waveform_start_seconds=0.0 + end type + + type, bind(C) :: ft4_signal_evidence + integer(c_int8_t) :: payload77(77)=0,tones(103)=0 + integer(c_int) :: payload_origin=engine_payload_none,has_tones=0,has_waveform_start=0,method=0 + real(c_float) :: waveform_start_seconds=0.0 + end type + + type, bind(C) :: superfox_evidence + integer(c_int8_t) :: symbols(50)=0 + integer(c_int) :: kind=0,child_index=0 + end type + + type :: superfox_observation + integer(c_int8_t) :: symbols(50)=0 + integer(c_int) :: kind=0,child_index=0,snr_db=0 + real(c_float) :: frequency_hz=0.0,dt_seconds=0.0 + character(len=37) :: message='' + character(len=160) :: legacy_line='' + integer(c_int) :: legacy_line_length=0 + end type + + type, bind(C) :: jt9_result + integer(c_int) :: has_drift=0 + real(c_float) :: drift_hz_per_minute=0.0 + end type + + type, bind(C) :: jt65_result + integer(c_int) :: kind=0,method=0,average_count=0,sync_polarity=0,smoothing=0 + integer(c_int) :: has_width=0,has_drift=0 + real(c_float) :: width_hz=0.0,drift_hz=0.0 + end type + + type, bind(C) :: q65_result + integer(c_int) :: period_seconds=0,method=0,average_count=0,recovered_bit78=0 + end type + + type, bind(C) :: fst4_result + integer(c_int) :: period_seconds=0,effective_bits=0,blanker_percent=0,has_doppler=0 + integer(c_int) :: has_hash22=0,hash22=0 + real(c_float) :: fmid_hz=0,width_hz=0 + end type + + type, bind(C) :: engine_observation + integer(c_int64_t) :: input_id=0,analysis_id=0 + integer(c_int) :: attempt_no=0,mode=engine_mode_ft8,variant=0 + integer(c_int) :: snr_db=0,ap_type=0 + real(c_float) :: frequency_hz=0,dt_seconds=0,sync=0,quality=0 + character(c_char) :: message(38)=c_null_char + type(ft8_signal_evidence) :: ft8 + type(ft4_signal_evidence) :: ft4 + type(superfox_evidence) :: superfox + type(jt9_result) :: jt9 + type(jt65_result) :: jt65 + type(q65_result) :: q65 + type(fst4_result) :: fst4 + end type + + abstract interface + subroutine engine_observation_sink(user,observation) + import :: c_ptr,engine_observation + type(c_ptr), intent(in) :: user + type(engine_observation), intent(in) :: observation + end subroutine + subroutine engine_superfox_sink(user,observation) + import :: c_ptr,superfox_observation + type(c_ptr), intent(in) :: user + type(superfox_observation), intent(in) :: observation + end subroutine + end interface +end module decoder_engine_types diff --git a/lib/decoder_ipc_control.cpp b/lib/decoder_ipc_control.cpp index e72251d7..7ea4887a 100644 --- a/lib/decoder_ipc_control.cpp +++ b/lib/decoder_ipc_control.cpp @@ -80,10 +80,9 @@ extern "C" void decoder_ipc_control_initialize (int * generation, int * state, } extern "C" void decoder_ipc_control_shutdown (int * state, - int * legacy_acknowledgment) + int *) { atomicStore (state, DECODER_IPC_SHUTDOWN); - atomicStore (legacy_acknowledgment, 1); } extern "C" int decoder_ipc_control_publish (int * generation, int * state, diff --git a/lib/decoder_ipc_control.h b/lib/decoder_ipc_control.h index 5bf593ba..b42791f3 100644 --- a/lib/decoder_ipc_control.h +++ b/lib/decoder_ipc_control.h @@ -19,7 +19,7 @@ extern "C" { int decoder_ipc_atomic_load (int const * value); void decoder_ipc_control_initialize (int * generation, int * state, int * version, int * progress); -void decoder_ipc_control_shutdown (int * state, int * legacy_acknowledgment); +void decoder_ipc_control_shutdown (int * state, int * version); int decoder_ipc_control_publish (int * generation, int * state, int const * version, int * progress, int request_generation); diff --git a/lib/decoder_ipc_layout.cpp b/lib/decoder_ipc_layout.cpp new file mode 100644 index 00000000..32890658 --- /dev/null +++ b/lib/decoder_ipc_layout.cpp @@ -0,0 +1,230 @@ +#include "decoder_ipc_layout.h" + +#include "../commons.h" +#include "decoder_ipc_control.h" + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <limits> + +static_assert (sizeof (int) == 4, "decoder IPC layout words require 32-bit integers"); +static_assert (sizeof (decoder_ipc_layout_t) == (14 + 2 * DECODER_IPC_LAYOUT_FIELDS) * 4, + "decoder IPC layout descriptor must not contain padding"); +static_assert (sizeof (shared_dec_data_t) <= std::numeric_limits<int>::max (), + "decoder IPC sizes must fit in layout words"); + +extern "C" void decoder_ipc_expected_layout (decoder_ipc_layout_t * layout) +{ + if (!layout) return; + *layout = {}; + layout->magic = DECODER_IPC_LAYOUT_MAGIC; + layout->protocol_version = DECODER_IPC_VERSION; + layout->header_bytes = offsetof (shared_dec_data_t, payload); + layout->payload_bytes = sizeof (dec_data_t); + layout->logical_bytes = sizeof (shared_dec_data_t); + layout->payload_offset = offsetof (shared_dec_data_t, payload); + layout->capabilities = DECODER_IPC_CAPABILITIES; + layout->int_bytes = sizeof (int); + layout->short_bytes = sizeof (short); + layout->float_bytes = sizeof (float); + layout->bool_bytes = sizeof (bool); + layout->char_bytes = sizeof (char); + layout->endian_marker = DECODER_IPC_ENDIAN_MARKER; + layout->field_count = DECODER_IPC_LAYOUT_FIELDS; + + std::size_t index {0}; +#define FIELD(member) \ + layout->fields[index++] = {offsetof (shared_dec_data_t, member), \ + sizeof (((shared_dec_data_t *) nullptr)->member)} + FIELD (control.generation); + FIELD (control.state); + FIELD (control.version); + FIELD (control.progress); + FIELD (payload.ss); + FIELD (payload.savg); + FIELD (payload.sred); + FIELD (payload.d2); + FIELD (payload.params); + FIELD (payload.params.nutc); + FIELD (payload.params.ndiskdat); + FIELD (payload.params.ntrperiod); + FIELD (payload.params.nQSOProgress); + FIELD (payload.params.nfqso); + FIELD (payload.params.nftx); + FIELD (payload.params.newdat); + FIELD (payload.params.npts8); + FIELD (payload.params.nfa); + FIELD (payload.params.nfSplit); + FIELD (payload.params.nfb); + FIELD (payload.params.ntol); + FIELD (payload.params.kin); + FIELD (payload.params.nzhsym); + FIELD (payload.params.nsubmode); + FIELD (payload.params.nagain); + FIELD (payload.params.ndepth); + FIELD (payload.params.lft8apon); + FIELD (payload.params.lapcqonly); + FIELD (payload.params.ljt65apon); + FIELD (payload.params.napwid); + FIELD (payload.params.ntxmode); + FIELD (payload.params.nmode); + FIELD (payload.params.minw); + FIELD (payload.params.nclearave); + FIELD (payload.params.minSync); + FIELD (payload.params.emedelay); + FIELD (payload.params.dttol); + FIELD (payload.params.nlist); + FIELD (payload.params.listutc); + FIELD (payload.params.n2pass); + FIELD (payload.params.nranera); + FIELD (payload.params.naggressive); + FIELD (payload.params.nrobust); + FIELD (payload.params.nexp_decode); + FIELD (payload.params.max_drift); + FIELD (payload.params.datetime); + FIELD (payload.params.mycall); + FIELD (payload.params.mygrid); + FIELD (payload.params.hiscall); + FIELD (payload.params.hisgrid); + FIELD (payload.params.b_even_seq); + FIELD (payload.params.b_superfox); + FIELD (payload.params.yymmdd); + FIELD (payload.params.mybcall); + FIELD (payload.params.hisbcall); + FIELD (payload.params.ncandthin); + FIELD (payload.params.ndtcenter); + FIELD (payload.params.nft8cycles); + FIELD (payload.params.ntrials10); + FIELD (payload.params.ntrialsrxf10); + FIELD (payload.params.nharmonicsdepth); + FIELD (payload.params.ntopfreq65); + FIELD (payload.params.nprepass); + FIELD (payload.params.nsdecatt); + FIELD (payload.params.nlasttx); + FIELD (payload.params.ndelay); + FIELD (payload.params.nmt); + FIELD (payload.params.nft8rxfsens); + FIELD (payload.params.nft4depth); + FIELD (payload.params.nsecbandchanged); + FIELD (payload.params.nagainfil); + FIELD (payload.params.nstophint); + FIELD (payload.params.nhint); + FIELD (payload.params.fmaskact); + FIELD (payload.params.lmultift8); + FIELD (payload.params.lft8lowth); + FIELD (payload.params.lft8subpass); + FIELD (payload.params.ltxing); + FIELD (payload.params.lhideft8dupes); + FIELD (payload.params.lhound); + FIELD (payload.params.lcommonft8b); + FIELD (payload.params.lmycallstd); + FIELD (payload.params.lhiscallstd); + FIELD (payload.params.lapmyc); + FIELD (payload.params.lmodechanged); + FIELD (payload.params.lbandchanged); + FIELD (payload.params.lenabledxcsearch); + FIELD (payload.params.lwidedxcsearch); + FIELD (payload.params.lmultinst); + FIELD (payload.params.lskiptx1); + FIELD (payload.params.ndecoderstart); + FIELD (metadata); + FIELD (metadata.input_id); + FIELD (metadata.analysis_id); + FIELD (metadata.attempt_no); + FIELD (metadata.valid_samples); +#undef FIELD +} + +extern "C" int decoder_ipc_validate_layout ( + void const * storage, std::size_t available_bytes, + decoder_ipc_layout_t const * peer_layout) +{ + if (!storage) return DECODER_IPC_LAYOUT_NULL; + if (available_bytes < sizeof (decoder_ipc_control_t)) + return DECODER_IPC_LAYOUT_TRUNCATED; + if (reinterpret_cast<std::uintptr_t> (storage) % alignof (shared_dec_data_t)) + return DECODER_IPC_LAYOUT_ALIGNMENT; + + auto const * control = static_cast<decoder_ipc_control_t const *> (storage); + if (decoder_ipc_atomic_load (&control->version) != DECODER_IPC_VERSION) + return DECODER_IPC_LAYOUT_VERSION; + if (available_bytes < offsetof (shared_dec_data_t, payload)) + return DECODER_IPC_LAYOUT_TRUNCATED; + + decoder_ipc_layout_t expected; + decoder_ipc_expected_layout (&expected); + if (peer_layout && std::memcmp (peer_layout, &expected, sizeof expected)) + return DECODER_IPC_LAYOUT_MISMATCH; + + decoder_ipc_layout_t actual; + std::memcpy (&actual, static_cast<unsigned char const *> (storage) + + offsetof (shared_dec_data_t, layout), sizeof actual); + if (actual.protocol_version != expected.protocol_version) + return DECODER_IPC_LAYOUT_VERSION; + if (actual.header_bytes != expected.header_bytes) + return DECODER_IPC_LAYOUT_HEADER_SIZE; + if (actual.payload_bytes != expected.payload_bytes) + return DECODER_IPC_LAYOUT_PAYLOAD_SIZE; + if (actual.logical_bytes != expected.logical_bytes) + return DECODER_IPC_LAYOUT_LOGICAL_SIZE; + if (actual.capabilities != expected.capabilities) + return DECODER_IPC_LAYOUT_CAPABILITIES; + if (std::memcmp (&actual, &expected, sizeof expected)) + return DECODER_IPC_LAYOUT_MISMATCH; + if (available_bytes < static_cast<std::size_t> (expected.logical_bytes)) + return DECODER_IPC_LAYOUT_TRUNCATED; + + auto const state = decoder_ipc_atomic_load (&control->state); + if (state != DECODER_IPC_IDLE && state != DECODER_IPC_READY + && state != DECODER_IPC_DECODING && state != DECODER_IPC_COMPLETE + && state != DECODER_IPC_SHUTDOWN) + return DECODER_IPC_LAYOUT_STATE; + return DECODER_IPC_LAYOUT_OK; +} + +extern "C" char const * decoder_ipc_layout_status_name (int status) +{ + switch (status) + { + case DECODER_IPC_LAYOUT_OK: return "ok"; + case DECODER_IPC_LAYOUT_NULL: return "null-segment"; + case DECODER_IPC_LAYOUT_TRUNCATED: return "truncated-segment"; + case DECODER_IPC_LAYOUT_ALIGNMENT: return "misaligned-segment"; + case DECODER_IPC_LAYOUT_VERSION: return "unsupported-version"; + case DECODER_IPC_LAYOUT_HEADER_SIZE: return "wrong-header-size"; + case DECODER_IPC_LAYOUT_PAYLOAD_SIZE: return "wrong-payload-size"; + case DECODER_IPC_LAYOUT_MISMATCH: return "incompatible-layout"; + case DECODER_IPC_LAYOUT_CAPABILITIES: return "unsupported-capabilities"; + case DECODER_IPC_LAYOUT_STATE: return "invalid-state"; + case DECODER_IPC_LAYOUT_LOGICAL_SIZE: return "wrong-logical-size"; + case DECODER_IPC_LAYOUT_ATTACH: return "attach-failed"; + default: return "unknown-status"; + } +} + +extern "C" void decoder_ipc_report_layout_error ( + int status, void const * storage, std::size_t available_bytes) +{ + decoder_ipc_layout_t expected; + decoder_ipc_expected_layout (&expected); + int version {-1}; + int header {-1}; + int payload {-1}; + auto const * bytes = static_cast<unsigned char const *> (storage); + if (storage && available_bytes >= offsetof (decoder_ipc_control_t, version) + sizeof version) + std::memcpy (&version, bytes + offsetof (decoder_ipc_control_t, version), sizeof version); + if (storage && available_bytes >= offsetof (shared_dec_data_t, layout) + sizeof expected) + { + decoder_ipc_layout_t actual; + std::memcpy (&actual, bytes + offsetof (shared_dec_data_t, layout), sizeof actual); + header = actual.header_bytes; + payload = actual.payload_bytes; + } + std::fprintf (stdout, "<DecoderError> status=%s\n", decoder_ipc_layout_status_name (status)); + std::fprintf (stdout, "Decoder IPC expected version=%d header=%d payload=%d; " + "actual version=%d header=%d payload=%d available=%zu\n", + DECODER_IPC_VERSION, expected.header_bytes, expected.payload_bytes, + version, header, payload, available_bytes); + std::fflush (stdout); +} diff --git a/lib/decoder_ipc_layout.f90 b/lib/decoder_ipc_layout.f90 new file mode 100644 index 00000000..7904b511 --- /dev/null +++ b/lib/decoder_ipc_layout.f90 @@ -0,0 +1,174 @@ +module decoder_ipc_layout_module + use, intrinsic :: iso_c_binding + include 'jt9com.f90' + private + public :: decoder_ipc_fortran_layout, decoder_ipc_fortran_validate + public :: decoder_ipc_report_layout_error + public :: DECODER_IPC_LAYOUT_VERSION, DECODER_IPC_LAYOUT_ATTACH + + integer(c_int), parameter :: DECODER_IPC_LAYOUT_VERSION = 4 + integer(c_int), parameter :: DECODER_IPC_LAYOUT_ATTACH = 11 + + interface + subroutine decoder_ipc_report_layout_error(status, storage, available_bytes) bind(C) + import :: c_ptr, c_size_t, c_int + integer(c_int), value :: status + type(c_ptr), value :: storage + integer(c_size_t), value :: available_bytes + end subroutine decoder_ipc_report_layout_error + + function validate_c(storage, available_bytes, peer_layout) & + bind(C, name="decoder_ipc_validate_layout") result(status) + import :: c_ptr, c_size_t, c_int + type(c_ptr), value :: storage, peer_layout + integer(c_size_t), value :: available_bytes + integer(c_int) :: status + end function validate_c + end interface + +contains + + subroutine decoder_ipc_fortran_layout(layout) bind(C) + type(decoder_ipc_layout), intent(out) :: layout + type(shared_dec_data), target, save :: local + integer(c_intptr_t) :: base + integer :: index + + base=transfer(c_loc(local),base) + layout%magic=int(z'57534a54',c_int) + layout%protocol_version=DECODER_IPC_VERSION + layout%header_bytes=int(transfer(c_loc(local%payload),base)-base,c_int) + layout%payload_bytes=int(c_sizeof(local%payload),c_int) + layout%logical_bytes=int(c_sizeof(local),c_int) + layout%payload_offset=layout%header_bytes + layout%capabilities=7 + layout%int_bytes=int(c_sizeof(local%control%generation),c_int) + layout%short_bytes=int(c_sizeof(local%payload%id2(1)),c_int) + layout%float_bytes=int(c_sizeof(local%payload%ss(1,1)),c_int) + layout%bool_bytes=int(c_sizeof(local%payload%params%ndiskdat),c_int) + layout%char_bytes=int(c_sizeof(local%payload%params%datetime(1)),c_int) + layout%endian_marker=int(z'01020304',c_int) + layout%field_count=size(layout%fields) + index=0 + call field(c_loc(local%control%generation), c_sizeof(local%control%generation)) + call field(c_loc(local%control%state), c_sizeof(local%control%state)) + call field(c_loc(local%control%version), c_sizeof(local%control%version)) + call field(c_loc(local%control%progress), c_sizeof(local%control%progress)) + call field(c_loc(local%payload%ss), c_sizeof(local%payload%ss)) + call field(c_loc(local%payload%savg), c_sizeof(local%payload%savg)) + call field(c_loc(local%payload%sred), c_sizeof(local%payload%sred)) + call field(c_loc(local%payload%id2), c_sizeof(local%payload%id2)) + call field(c_loc(local%payload%params), c_sizeof(local%payload%params)) + call field(c_loc(local%payload%params%nutc), c_sizeof(local%payload%params%nutc)) + call field(c_loc(local%payload%params%ndiskdat), c_sizeof(local%payload%params%ndiskdat)) + call field(c_loc(local%payload%params%ntr), c_sizeof(local%payload%params%ntr)) + call field(c_loc(local%payload%params%nQSOProgress), c_sizeof(local%payload%params%nQSOProgress)) + call field(c_loc(local%payload%params%nfqso), c_sizeof(local%payload%params%nfqso)) + call field(c_loc(local%payload%params%nftx), c_sizeof(local%payload%params%nftx)) + call field(c_loc(local%payload%params%newdat), c_sizeof(local%payload%params%newdat)) + call field(c_loc(local%payload%params%npts8), c_sizeof(local%payload%params%npts8)) + call field(c_loc(local%payload%params%nfa), c_sizeof(local%payload%params%nfa)) + call field(c_loc(local%payload%params%nfSplit), c_sizeof(local%payload%params%nfSplit)) + call field(c_loc(local%payload%params%nfb), c_sizeof(local%payload%params%nfb)) + call field(c_loc(local%payload%params%ntol), c_sizeof(local%payload%params%ntol)) + call field(c_loc(local%payload%params%kin), c_sizeof(local%payload%params%kin)) + call field(c_loc(local%payload%params%nzhsym), c_sizeof(local%payload%params%nzhsym)) + call field(c_loc(local%payload%params%nsubmode), c_sizeof(local%payload%params%nsubmode)) + call field(c_loc(local%payload%params%nagain), c_sizeof(local%payload%params%nagain)) + call field(c_loc(local%payload%params%ndepth), c_sizeof(local%payload%params%ndepth)) + call field(c_loc(local%payload%params%lft8apon), c_sizeof(local%payload%params%lft8apon)) + call field(c_loc(local%payload%params%lapcqonly), c_sizeof(local%payload%params%lapcqonly)) + call field(c_loc(local%payload%params%ljt65apon), c_sizeof(local%payload%params%ljt65apon)) + call field(c_loc(local%payload%params%napwid), c_sizeof(local%payload%params%napwid)) + call field(c_loc(local%payload%params%ntxmode), c_sizeof(local%payload%params%ntxmode)) + call field(c_loc(local%payload%params%nmode), c_sizeof(local%payload%params%nmode)) + call field(c_loc(local%payload%params%minw), c_sizeof(local%payload%params%minw)) + call field(c_loc(local%payload%params%nclearave), c_sizeof(local%payload%params%nclearave)) + call field(c_loc(local%payload%params%minSync), c_sizeof(local%payload%params%minSync)) + call field(c_loc(local%payload%params%emedelay), c_sizeof(local%payload%params%emedelay)) + call field(c_loc(local%payload%params%dttol), c_sizeof(local%payload%params%dttol)) + call field(c_loc(local%payload%params%nlist), c_sizeof(local%payload%params%nlist)) + call field(c_loc(local%payload%params%listutc), c_sizeof(local%payload%params%listutc)) + call field(c_loc(local%payload%params%n2pass), c_sizeof(local%payload%params%n2pass)) + call field(c_loc(local%payload%params%nranera), c_sizeof(local%payload%params%nranera)) + call field(c_loc(local%payload%params%naggressive), c_sizeof(local%payload%params%naggressive)) + call field(c_loc(local%payload%params%nrobust), c_sizeof(local%payload%params%nrobust)) + call field(c_loc(local%payload%params%nexp_decode), c_sizeof(local%payload%params%nexp_decode)) + call field(c_loc(local%payload%params%max_drift), c_sizeof(local%payload%params%max_drift)) + call field(c_loc(local%payload%params%datetime), c_sizeof(local%payload%params%datetime)) + call field(c_loc(local%payload%params%mycall), c_sizeof(local%payload%params%mycall)) + call field(c_loc(local%payload%params%mygrid), c_sizeof(local%payload%params%mygrid)) + call field(c_loc(local%payload%params%hiscall), c_sizeof(local%payload%params%hiscall)) + call field(c_loc(local%payload%params%hisgrid), c_sizeof(local%payload%params%hisgrid)) + call field(c_loc(local%payload%params%b_even_seq), c_sizeof(local%payload%params%b_even_seq)) + call field(c_loc(local%payload%params%b_superfox), c_sizeof(local%payload%params%b_superfox)) + call field(c_loc(local%payload%params%yymmdd), c_sizeof(local%payload%params%yymmdd)) + call field(c_loc(local%payload%params%mybcall), c_sizeof(local%payload%params%mybcall)) + call field(c_loc(local%payload%params%hisbcall), c_sizeof(local%payload%params%hisbcall)) + call field(c_loc(local%payload%params%ncandthin), c_sizeof(local%payload%params%ncandthin)) + call field(c_loc(local%payload%params%ndtcenter), c_sizeof(local%payload%params%ndtcenter)) + call field(c_loc(local%payload%params%nft8cycles), c_sizeof(local%payload%params%nft8cycles)) + call field(c_loc(local%payload%params%ntrials10), c_sizeof(local%payload%params%ntrials10)) + call field(c_loc(local%payload%params%ntrialsrxf10), c_sizeof(local%payload%params%ntrialsrxf10)) + call field(c_loc(local%payload%params%nharmonicsdepth), c_sizeof(local%payload%params%nharmonicsdepth)) + call field(c_loc(local%payload%params%ntopfreq65), c_sizeof(local%payload%params%ntopfreq65)) + call field(c_loc(local%payload%params%nprepass), c_sizeof(local%payload%params%nprepass)) + call field(c_loc(local%payload%params%nsdecatt), c_sizeof(local%payload%params%nsdecatt)) + call field(c_loc(local%payload%params%nlasttx), c_sizeof(local%payload%params%nlasttx)) + call field(c_loc(local%payload%params%ndelay), c_sizeof(local%payload%params%ndelay)) + call field(c_loc(local%payload%params%nmt), c_sizeof(local%payload%params%nmt)) + call field(c_loc(local%payload%params%nft8rxfsens), c_sizeof(local%payload%params%nft8rxfsens)) + call field(c_loc(local%payload%params%nft4depth), c_sizeof(local%payload%params%nft4depth)) + call field(c_loc(local%payload%params%nsecbandchanged), c_sizeof(local%payload%params%nsecbandchanged)) + call field(c_loc(local%payload%params%nagainfil), c_sizeof(local%payload%params%nagainfil)) + call field(c_loc(local%payload%params%nstophint), c_sizeof(local%payload%params%nstophint)) + call field(c_loc(local%payload%params%nhint), c_sizeof(local%payload%params%nhint)) + call field(c_loc(local%payload%params%fmaskact), c_sizeof(local%payload%params%fmaskact)) + call field(c_loc(local%payload%params%lmultift8), c_sizeof(local%payload%params%lmultift8)) + call field(c_loc(local%payload%params%lft8lowth), c_sizeof(local%payload%params%lft8lowth)) + call field(c_loc(local%payload%params%lft8subpass), c_sizeof(local%payload%params%lft8subpass)) + call field(c_loc(local%payload%params%ltxing), c_sizeof(local%payload%params%ltxing)) + call field(c_loc(local%payload%params%lhideft8dupes), c_sizeof(local%payload%params%lhideft8dupes)) + call field(c_loc(local%payload%params%lhound), c_sizeof(local%payload%params%lhound)) + call field(c_loc(local%payload%params%lcommonft8b), c_sizeof(local%payload%params%lcommonft8b)) + call field(c_loc(local%payload%params%lmycallstd), c_sizeof(local%payload%params%lmycallstd)) + call field(c_loc(local%payload%params%lhiscallstd), c_sizeof(local%payload%params%lhiscallstd)) + call field(c_loc(local%payload%params%lapmyc), c_sizeof(local%payload%params%lapmyc)) + call field(c_loc(local%payload%params%lmodechanged), c_sizeof(local%payload%params%lmodechanged)) + call field(c_loc(local%payload%params%lbandchanged), c_sizeof(local%payload%params%lbandchanged)) + call field(c_loc(local%payload%params%lenabledxcsearch), c_sizeof(local%payload%params%lenabledxcsearch)) + call field(c_loc(local%payload%params%lwidedxcsearch), c_sizeof(local%payload%params%lwidedxcsearch)) + call field(c_loc(local%payload%params%lmultinst), c_sizeof(local%payload%params%lmultinst)) + call field(c_loc(local%payload%params%lskiptx1), c_sizeof(local%payload%params%lskiptx1)) + call field(c_loc(local%payload%params%ndecoderstart), c_sizeof(local%payload%params%ndecoderstart)) + + call field(c_loc(local%metadata), c_sizeof(local%metadata)) + call field(c_loc(local%metadata%input_id), c_sizeof(local%metadata%input_id)) + call field(c_loc(local%metadata%analysis_id), c_sizeof(local%metadata%analysis_id)) + call field(c_loc(local%metadata%attempt_no), c_sizeof(local%metadata%attempt_no)) + call field(c_loc(local%metadata%valid_samples), c_sizeof(local%metadata%valid_samples)) + + contains + + subroutine field(address, bytes) + type(c_ptr), value :: address + integer(c_size_t), value :: bytes + integer(c_intptr_t) :: location + + index=index+1 + location=transfer(address,location) + layout%fields(index)%offset=int(location-base,c_int) + layout%fields(index)%bytes=int(bytes,c_int) + end subroutine field + end subroutine decoder_ipc_fortran_layout + + function decoder_ipc_fortran_validate(storage, available_bytes) bind(C) result(status) + type(c_ptr), value :: storage + integer(c_size_t), value :: available_bytes + integer(c_int) :: status + type(decoder_ipc_layout), target :: expected + + call decoder_ipc_fortran_layout(expected) + status=validate_c(storage,available_bytes,c_loc(expected)) + end function decoder_ipc_fortran_validate +end module decoder_ipc_layout_module diff --git a/lib/decoder_ipc_layout.h b/lib/decoder_ipc_layout.h new file mode 100644 index 00000000..d1a144fc --- /dev/null +++ b/lib/decoder_ipc_layout.h @@ -0,0 +1,69 @@ +#ifndef DECODER_IPC_LAYOUT_H +#define DECODER_IPC_LAYOUT_H + +#include <stddef.h> + +#define DECODER_IPC_LAYOUT_MAGIC 0x57534a54 +#define DECODER_IPC_ENDIAN_MARKER 0x01020304 +#define DECODER_IPC_CAP_GENERATIONS 1 +#define DECODER_IPC_CAP_PROGRESS 2 +#define DECODER_IPC_CAP_HANDSHAKE 4 +#define DECODER_IPC_CAPABILITIES 7 +#define DECODER_IPC_LAYOUT_FIELDS 96 + +typedef struct decoder_ipc_field_layout { + int offset; + int bytes; +} decoder_ipc_field_layout_t; + +typedef struct decoder_ipc_layout { + int magic; + int protocol_version; + int header_bytes; + int payload_bytes; + int logical_bytes; + int payload_offset; + int capabilities; + int int_bytes; + int short_bytes; + int float_bytes; + int bool_bytes; + int char_bytes; + int endian_marker; + int field_count; + decoder_ipc_field_layout_t fields[DECODER_IPC_LAYOUT_FIELDS]; +} decoder_ipc_layout_t; + +enum decoder_ipc_layout_status { + DECODER_IPC_LAYOUT_OK = 0, + DECODER_IPC_LAYOUT_NULL = 1, + DECODER_IPC_LAYOUT_TRUNCATED = 2, + DECODER_IPC_LAYOUT_ALIGNMENT = 3, + DECODER_IPC_LAYOUT_VERSION = 4, + DECODER_IPC_LAYOUT_HEADER_SIZE = 5, + DECODER_IPC_LAYOUT_PAYLOAD_SIZE = 6, + DECODER_IPC_LAYOUT_MISMATCH = 7, + DECODER_IPC_LAYOUT_CAPABILITIES = 8, + DECODER_IPC_LAYOUT_STATE = 9, + DECODER_IPC_LAYOUT_LOGICAL_SIZE = 10, + DECODER_IPC_LAYOUT_ATTACH = 11 +}; + +#ifdef __cplusplus +extern "C" { +#endif + +void decoder_ipc_expected_layout (decoder_ipc_layout_t * layout); +int decoder_ipc_validate_layout (void const * storage, size_t available_bytes, + decoder_ipc_layout_t const * peer_layout); +char const * decoder_ipc_layout_status_name (int status); +void decoder_ipc_report_layout_error (int status, void const * storage, + size_t available_bytes); +void decoder_ipc_fortran_layout (decoder_ipc_layout_t * layout); +int decoder_ipc_fortran_validate (void const * storage, size_t available_bytes); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/lib/downsam9.f90 b/lib/downsam9.f90 index 7cd1962a..95f9d80f 100644 --- a/lib/downsam9.f90 +++ b/lib/downsam9.f90 @@ -1,72 +1,122 @@ -subroutine downsam9(id2,npts8,nsps8,newdat,nspsd,fpk,c2) - -!Downsample from id2() into c2() so as to yield nspsd samples per symbol, -!mixing from fpk down to zero frequency. The downsample factor is 432. - +module jt9_downsample use, intrinsic :: iso_c_binding use FFTW3 + implicit none + private + public :: jt9_downsample_workspace, downsam9 + + integer, parameter :: NFFT1=653184, NFFT2=1512 + + type :: jt9_downsample_workspace + private + type(c_ptr) :: plan=c_null_ptr, storage=c_null_ptr + real(c_float), pointer :: samples(:)=>null() + complex(c_float_complex), allocatable :: spectrum(:) + real, allocatable :: power(:) + logical :: valid=.false. + integer :: sample_count=0 + integer :: plan_patience=-1, plan_threads=0 + contains + procedure :: initialize + procedure :: invalidate + procedure :: clear + final :: finalize + end type jt9_downsample_workspace + +contains + + subroutine initialize(this) + class(jt9_downsample_workspace), intent(inout) :: this + integer :: npatience,nthreads,nflags + common/patience/npatience,nthreads + + if(c_associated(this%plan)) then + if(this%plan_patience==npatience.and.this%plan_threads==nthreads) return + call this%clear() + endif + nflags=FFTW_ESTIMATE + if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT + if(npatience.eq.2) nflags=FFTW_MEASURE + if(npatience.eq.3) nflags=FFTW_PATIENT + if(npatience.eq.4) nflags=FFTW_EXHAUSTIVE + allocate(this%spectrum(0:NFFT1/2),this%power(5000)) + !$omp critical(fftw) + this%storage=fftwf_alloc_real(int(NFFT1,c_size_t)) + call c_f_pointer(this%storage,this%samples,[NFFT1]) + this%samples(0:NFFT1-1) => this%samples + call fftwf_plan_with_nthreads(nthreads) + this%plan=fftwf_plan_dft_r2c_1d(NFFT1,this%samples,this%spectrum,nflags) + call fftwf_plan_with_nthreads(1) + !$omp end critical(fftw) + this%plan_patience=npatience + this%plan_threads=nthreads + end subroutine initialize + + subroutine invalidate(this) + class(jt9_downsample_workspace), intent(inout) :: this + this%valid=.false. + end subroutine invalidate + + subroutine clear(this) + class(jt9_downsample_workspace), intent(inout) :: this + !$omp critical(fftw) + if(c_associated(this%plan)) call fftwf_destroy_plan(this%plan) + if(c_associated(this%storage)) call fftwf_free(this%storage) + !$omp end critical(fftw) + this%plan=c_null_ptr + this%storage=c_null_ptr + nullify(this%samples) + if(allocated(this%spectrum)) deallocate(this%spectrum,this%power) + this%valid=.false. + this%sample_count=0 + end subroutine clear + + subroutine finalize(this) + type(jt9_downsample_workspace), intent(inout) :: this + call this%clear() + end subroutine finalize + +subroutine downsam9(workspace,id2,npts8,fpk,c2) + +! Downsample by 432 to 16 samples per JT9 symbol, mixing fpk to zero frequency. + use timer_module, only: timer + implicit none - include 'constants.f90' - integer(C_SIZE_T) NMAX1 - parameter (NMAX1=653184) - parameter (NFFT1=653184,NFFT2=1512) - type(C_PTR) :: plan !Pointers plan for big FFT - integer*2 id2(0:8*npts8-1) - logical, intent(inout) :: newdat - real*4, pointer :: x1(:) - complex c1(0:NFFT1/2) - complex c2(0:NFFT2-1) - real s(5000) - logical first - common/patience/npatience,nthreads - data first/.true./ - save plan,first,c1,s,x1 + type(jt9_downsample_workspace), intent(inout) :: workspace + integer, intent(in) :: npts8 + integer(c_short), intent(in) :: id2(0:*) + real, intent(in) :: fpk + complex, intent(out) :: c2(0:NFFT2-1) + integer :: npts, nadd, i, j, n, nh2, nf, i0, nw, ia, ib + real :: df1, avenoise, fac df1=12000.0/NFFT1 npts=8*npts8 - if(npts.gt.NFFT1) npts=NFFT1 !### Fix! ### - - if(first) then - nflags=FFTW_ESTIMATE - if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT - if(npatience.eq.2) nflags=FFTW_MEASURE - if(npatience.eq.3) nflags=FFTW_PATIENT - if(npatience.eq.4) nflags=FFTW_EXHAUSTIVE -! Plan the FFTs just once - - !$omp critical(fftw) ! serialize non thread-safe FFTW3 calls - plan=fftwf_alloc_real(NMAX1) - call c_f_pointer(plan,x1,[NMAX1]) - x1(0:NMAX1-1) => x1 !remap bounds - call fftwf_plan_with_nthreads(nthreads) - plan=fftwf_plan_dft_r2c_1d(NFFT1,x1,c1,nflags) - call fftwf_plan_with_nthreads(1) - !$omp end critical(fftw) - - first=.false. - endif + npts=min(npts,NFFT1) + + call workspace%initialize() - if(newdat) then - x1(0:npts-1)=id2(0:npts-1) - x1(npts:NFFT1-1)=0. !Zero the rest of x1 + if(.not.workspace%valid .or. workspace%sample_count.ne.npts) then + workspace%samples(0:npts-1)=id2(0:npts-1) + workspace%samples(npts:NFFT1-1)=0. call timer('FFTbig9 ',0) - call fftwf_execute_dft_r2c(plan,x1,c1) + call fftwf_execute_dft_r2c(workspace%plan,workspace%samples,workspace%spectrum) call timer('FFTbig9 ',1) nadd=int(1.0/df1) - s=0. + workspace%power=0. do i=1,5000 j=int((i-1)/df1) do n=1,nadd j=j+1 - s(i)=s(i)+real(c1(j))**2 + aimag(c1(j))**2 + workspace%power(i)=workspace%power(i)+real(workspace%spectrum(j))**2 + aimag(workspace%spectrum(j))**2 enddo enddo - newdat=.false. + workspace%valid=.true. + workspace%sample_count=npts endif - ndown=8*nsps8/nspsd !Downsample factor = 432 nh2=NFFT2/2 nf=nint(fpk) i0=int(fpk/df1) @@ -74,15 +124,22 @@ subroutine downsam9(id2,npts8,nsps8,newdat,nspsd,fpk,c2) nw=100 ia=max(1,nf-nw) ib=min(5000,nf+nw) - call pctile(s(ia),ib-ia+1,40,avenoise) + call pctile(workspace%power(ia),ib-ia+1,40,avenoise) + if(avenoise.le.0.) then + c2=0. + return + endif fac=sqrt(1.0/avenoise) do i=0,NFFT2-1 j=i0+i if(i.gt.nh2) j=j-NFFT2 - c2(i)=fac*c1(j) + c2(i)=0. + if(j.ge.0 .and. j.le.NFFT1/2) c2(i)=fac*workspace%spectrum(j) enddo call four2a(c2,NFFT2,1,1,1) !FFT back to time domain return end subroutine downsam9 + +end module jt9_downsample diff --git a/lib/extract.f90 b/lib/extract.f90 index 234f5137..2f659727 100644 --- a/lib/extract.f90 +++ b/lib/extract.f90 @@ -27,6 +27,7 @@ subroutine extract(s3,nadd,mode65,ntrials,naggressive,ndepth,nflip, & integer apsymbols(7,12),ap(12) integer nappasses(0:5) ! the number of decoding passes to use for each QSO state integer naptypes(0:5,4) ! (nQSOProgress, decoding pass) maximum of 4 passes for now + integer :: cache_epoch=-1 integer dat4(12) integer mrsym(63),mr2sym(63),mrprob(63),mr2prob(63) integer correct(63),tmp(63) @@ -36,7 +37,11 @@ subroutine extract(s3,nadd,mode65,ntrials,naggressive,ndepth,nflip, & save if(mode65.eq.-99) stop !Silence compiler warning - if(first) then + if(first.or.cache_epoch/=jt65_ap_epoch) then + mycall0='' + hiscall0='' + hisgrid0='' + cache_epoch=jt65_ap_epoch ! aptype !------------------------ @@ -68,6 +73,7 @@ subroutine extract(s3,nadd,mode65,ntrials,naggressive,ndepth,nflip, & apsymbols=-1 mycall0=mycall hiscall0=hiscall + hisgrid0=hisgrid ap=-1 apsymbols(1,1:4)=(/62,32,32,49/) ! CQ if(len_trim(mycall).gt.0) then @@ -108,6 +114,10 @@ subroutine extract(s3,nadd,mode65,ntrials,naggressive,ndepth,nflip, & nfail=0 decoded=' ' call pctile(s3,4032,npct,base) + ncount=-1 + nhist=0 + ltext=.false. + if(base<=0.) return s3=s3/base s3a=s3 !### diff --git a/lib/fchisq.f90 b/lib/fchisq.f90 index f84898ba..03168f8c 100644 --- a/lib/fchisq.f90 +++ b/lib/fchisq.f90 @@ -5,21 +5,13 @@ real function fchisq(c3,npts,fsample,a) complex c4(NMAX) real a(3) complex z - data a1,a2,a3/99.,99.,99./ include 'jt9sync.f90' - save - if(a(1).ne.a1 .or. a(2).ne.a2 .or. a(3).ne.a3) then - a1=a(1) - a2=a(2) - a3=a(3) - call twkfreq(c3,c4,npts,fsample,a) - endif + call twkfreq(c3,c4,npts,fsample,a) ! Get sync power. nspsd=16 sum1=0. - sum0=0. k=-1 do i=1,85 z=0. @@ -30,15 +22,9 @@ real function fchisq(c3,npts,fsample,a) pp=real(z)**2 + aimag(z)**2 if(isync(i).eq.1) then sum1=sum1+pp - else - sum0=sum0+pp endif enddo - sync_4992=(sum1/16.0)/(sum0/69.0) - 1.0 !r4992 - sync_4993=sum1/10000.0 !r4993+ -! write(80,3001) 1.e-5*sum1,1.e-5*sum0,sync_4992,sync_4993,sync -!3001 format(5f11.4) - fchisq=-sync_4993 + fchisq=-sum1/10000.0 return end function fchisq diff --git a/lib/fchisq65.f90 b/lib/fchisq65.f90 index ad5aeb04..de43d75a 100644 --- a/lib/fchisq65.f90 +++ b/lib/fchisq65.f90 @@ -1,5 +1,6 @@ real function fchisq65(cx,npts,fsample,nflip,a,ccfmax,dtmax) + use jt65_mod, only: jt65_work,ensure_jt65_workspace use timer_module, only: timer parameter (NMAX=60*12000) !Samples per 60 s @@ -7,10 +8,12 @@ real function fchisq65(cx,npts,fsample,nflip,a,ccfmax,dtmax) real a(5) complex w,wstep,z real ss(3000) - complex csx(0:NMAX/8) - data twopi/6.283185307/a1,a2,a3/99.,99.,99./ + data twopi/6.283185307/ save + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%integral)) allocate(jt65_work%integral(0:NMAX/8)) + associate(csx=>jt65_work%integral) call timer('fchisq65',0) baud=11025.0/4096.0 nsps=nint(fsample/baud) !Samples per symbol @@ -19,10 +22,9 @@ real function fchisq65(cx,npts,fsample,nflip,a,ccfmax,dtmax) nout=ndiv*npts/nsps dtstep=1.0/(ndiv*baud) !Time per output step - if(a(1).ne.a1 .or. a(2).ne.a2 .or. a(3).ne.a3) then - a1=a(1) - a2=a(2) - a3=a(3) + if(.not.jt65_work%afc_valid.or.any(a(1:3)/=jt65_work%afc_parameters)) then + jt65_work%afc_parameters=a(1:3) + jt65_work%afc_valid=.true. ! Mix and integrate the complex signal csx(0)=0. @@ -54,6 +56,7 @@ real function fchisq65(cx,npts,fsample,nflip,a,ccfmax,dtmax) enddo ccfmax=0. + dtmax=0. call timer('ccf2 ',0) call ccf2(ss,nout,nflip,ccf,xlagpk) call timer('ccf2 ',1) @@ -64,5 +67,6 @@ real function fchisq65(cx,npts,fsample,nflip,a,ccfmax,dtmax) fchisq65=-ccfmax call timer('fchisq65',1) + end associate return end function fchisq65 diff --git a/lib/filbig.f90 b/lib/filbig.f90 index 42119930..b36e1fad 100644 --- a/lib/filbig.f90 +++ b/lib/filbig.f90 @@ -5,33 +5,40 @@ subroutine filbig(dd,npts,f0,newdat,c4a,n4,sq0) use, intrinsic :: iso_c_binding use FFTW3 + use jt65_mod, only: jt65_work,ensure_jt65_workspace use timer_module, only: timer parameter (NSZ=3413) parameter (NFFT1=672000,NFFT2=77175,NH2=38587) parameter (NZ2=1000) + complex, pointer :: ca(:) real*4 dd(npts) !Input data - real*4 rca(NFFT1) - complex ca(NFFT1/2+1) !FFT of input complex c4a(NFFT2) !Output data real*4 s(NZ2) real*8 df real halfpulse(8) !Impulse response of filter (one sided) - complex cfilt(NFFT2) !Filter (complex; imag = 0) - real rfilt(NFFT2) !Filter (real) - type(C_PTR) :: plan1,plan2,plan3 !Pointers to FFTW plans - logical first - equivalence (rfilt,cfilt),(rca,ca) - data first/.true./ data halfpulse/114.97547150,36.57879257,-20.93789101, & 5.89886379,1.59355187,-2.49138308,0.60910773,-0.04248129/ common/refspec/dfref,ref(NSZ) common/patience/npatience,nthreads - save first,plan1,plan2,plan3,rfilt,cfilt,df,ca - - if(npts.lt.0) go to 900 !Clean up at end of program - - if(first) then + call ensure_jt65_workspace() + if(npts.lt.0) return + if(.not.allocated(jt65_work%big_input)) then + allocate(jt65_work%big_input(NFFT1+2)) + allocate(jt65_work%filter(NFFT2),jt65_work%filter_fft(NFFT2),jt65_work%filtered(NFFT2)) + endif + ! The real and complex views share FFTW's NFFT1+2 in-place storage. + call c_f_pointer(c_loc(jt65_work%big_input),ca,[NFFT1/2+1]) + associate(rca=>jt65_work%big_input,rfilt=>jt65_work%filter, & + cfilt=>jt65_work%filter_fft,filtered=>jt65_work%filtered, & + plan1=>jt65_work%big_plan,plan2=>jt65_work%short_plan,plan3=>jt65_work%filter_plan) + df=12000.d0/nfft1 + if(jt65_work%patience/=npatience.or.jt65_work%threads/=nthreads.or..not.c_associated(plan1)) then + !$omp critical(fftw) + if(c_associated(plan1)) call fftwf_destroy_plan(plan1) + if(c_associated(plan2)) call fftwf_destroy_plan(plan2) + if(c_associated(plan3)) call fftwf_destroy_plan(plan3) + !$omp end critical(fftw) nflags=FFTW_ESTIMATE if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT if(npatience.eq.2) nflags=FFTW_MEASURE @@ -43,7 +50,7 @@ subroutine filbig(dd,npts,f0,newdat,c4a,n4,sq0) call fftwf_plan_with_nthreads(nthreads) plan1=fftwf_plan_dft_r2c_1d(nfft1,rca,ca,nflags) call fftwf_plan_with_nthreads(1) - plan2=fftwf_plan_dft_1d(nfft2,c4a,c4a,-1,nflags) + plan2=fftwf_plan_dft_1d(nfft2,filtered,filtered,-1,nflags) plan3=fftwf_plan_dft_1d(nfft2,cfilt,cfilt,+1,nflags) !$omp end critical(fftw) @@ -65,7 +72,9 @@ subroutine filbig(dd,npts,f0,newdat,c4a,n4,sq0) enddo df=12000.d0/nfft1 - first=.false. + jt65_work%patience=npatience + jt65_work%threads=nthreads + newdat=1 endif ! When new data comes along, we need to compute a new "big FFT" @@ -83,7 +92,7 @@ subroutine filbig(dd,npts,f0,newdat,c4a,n4,sq0) do j=1,NSZ ia=ib+1 ib=nint(j*dfref/df) - fac=sqrt(min(30.0,1.0/ref(j))) + fac=sqrt(min(30.0,1.0/max(ref(j),tiny(1.0)))) ca(ia:ib)=fac*conjg(ca(ia:ib)) enddo newdat=0 @@ -93,21 +102,21 @@ subroutine filbig(dd,npts,f0,newdat,c4a,n4,sq0) ! i0 is the bin number in ca closest to f0. call timer('loops ',0) i0=nint(f0/df) + 1 - do i=1,NH2 !Copy data into c4a and apply + do i=1,NH2 !Select input bins and apply j=i0+i-1 !the filter function if(j.ge.1 .and. j.le.nfft1/2+1) then - c4a(i)=rfilt(i)*ca(j) + filtered(i)=rfilt(i)*ca(j) else - c4a(i)=0. + filtered(i)=0. endif enddo do i=NH2+1,nfft2 j=i0+i-1-nfft2 ! if(j.lt.1) j=j+nfft1 !nfft1 was nfft2 if(j.ge.1) then - c4a(i)=rfilt(i)*ca(j) + filtered(i)=rfilt(i)*ca(j) else - c4a(i)=rfilt(i)*conjg(ca(2-j)) + filtered(i)=rfilt(i)*conjg(ca(2-j)) endif enddo @@ -117,7 +126,7 @@ subroutine filbig(dd,npts,f0,newdat,c4a,n4,sq0) s(j)=0. do n=1,nadd i=i+1 - s(j)=s(j) + real(c4a(i))**2 + aimag(c4a(i))**2 + s(j)=s(j) + real(filtered(i))**2 + aimag(filtered(i))**2 enddo enddo call pctile(s,NZ2,30,sq0) @@ -125,18 +134,10 @@ subroutine filbig(dd,npts,f0,newdat,c4a,n4,sq0) ! Do the short reverse transform, to go back to time domain. call timer('FFTsmall',0) - call fftwf_execute_dft(plan2,c4a,c4a) + call fftwf_execute_dft(plan2,filtered,filtered) + c4a=filtered call timer('FFTsmall',1) n4=min(npts/8,nfft2) - return - -900 continue - - !$omp critical(fftw) ! serialize non thread-safe FFTW3 calls - call fftwf_destroy_plan(plan1) - call fftwf_destroy_plan(plan2) - call fftwf_destroy_plan(plan3) - !$omp end critical(fftw) - + end associate return end subroutine filbig diff --git a/lib/fst4/decode240_101.f90 b/lib/fst4/decode240_101.f90 index 4271a464..8e5ac504 100644 --- a/lib/fst4/decode240_101.f90 +++ b/lib/fst4/decode240_101.f90 @@ -1,4 +1,10 @@ -subroutine decode240_101(llr,Keff,maxosd,norder,apmask,message101,cw,ntype,nharderror,dmin) +module fst4_ldpc_101 + use fst4_osd_workspace, only: fst4_osd_workspace_type + use osd240_101_module, only: osd240_101_owned + private + public :: decode240_101_owned +contains +subroutine decode240_101_owned(work,llr,Keff,maxosd,norder,apmask,message101,cw,ntype,nharderror,dmin) ! ! A hybrid bp/osd decoder for the (240,101) code. ! @@ -7,6 +13,7 @@ subroutine decode240_101(llr,Keff,maxosd,norder,apmask,message101,cw,ntype,nhard ! maxosd>1: do bp and then call osd maxosd times with saved bp outputs ! norder : osd decoding depth ! + type(fst4_osd_workspace_type), intent(inout), target :: work integer, parameter:: N=240, K=101, M=N-K integer*1 cw(N),apmask(N) integer*1 nxor(N),hdec(N) @@ -135,7 +142,7 @@ subroutine decode240_101(llr,Keff,maxosd,norder,apmask,message101,cw,ntype,nhard do i=1,nosd zn=zsave(:,i) - call osd240_101(zn,Keff,apmask,norder,message101,cw,nharderror,dminosd) + call osd240_101_owned(work,zn,Keff,apmask,norder,message101,cw,nharderror,dminosd) if(nharderror.gt.0) then hdec=0 where(llr .ge. 0) hdec=1 @@ -152,4 +159,15 @@ subroutine decode240_101(llr,Keff,maxosd,norder,apmask,message101,cw,ntype,nhard dminosd=0.0 return -end subroutine decode240_101 +end subroutine decode240_101_owned + +end module fst4_ldpc_101 + +subroutine decode240_101(llr,Keff,maxosd,norder,apmask,message101,cw,ntype,nharderror,dmin) + use fst4_ldpc_101, only: decode240_101_owned + use fst4_osd_workspace, only: fst4_osd_workspace_type + type(fst4_osd_workspace_type), save :: legacy + real llr(240),dmin + integer*1 apmask(240),message101(101),cw(240) + call decode240_101_owned(legacy,llr,Keff,maxosd,norder,apmask,message101,cw,ntype,nharderror,dmin) +end subroutine diff --git a/lib/fst4/decode240_74.f90 b/lib/fst4/decode240_74.f90 index f5aac2e1..a4bf3ea7 100644 --- a/lib/fst4/decode240_74.f90 +++ b/lib/fst4/decode240_74.f90 @@ -1,4 +1,10 @@ -subroutine decode240_74(llr,Keff,maxosd,norder,apmask,message74,cw,ntype,nharderror,dmin) +module fst4_ldpc_74 + use fst4_osd_workspace, only: fst4_osd_workspace_type + use fastosd240_74_module, only: fastosd240_74_owned + private + public :: decode240_74_owned +contains +subroutine decode240_74_owned(work,llr,Keff,maxosd,norder,apmask,message74,cw,ntype,nharderror,dmin) ! ! A hybrid bp/osd decoder for the (240,74) code. ! @@ -7,6 +13,7 @@ subroutine decode240_74(llr,Keff,maxosd,norder,apmask,message74,cw,ntype,nharder ! maxosd>1: do bp and then call osd maxosd times with saved bp outputs ! norder : osd decoding depth ! + type(fst4_osd_workspace_type), intent(inout), target :: work integer, parameter:: N=240, K=74, M=N-K integer*1 cw(N),apmask(N) integer*1 nxor(N),hdec(N) @@ -141,7 +148,7 @@ subroutine decode240_74(llr,Keff,maxosd,norder,apmask,message74,cw,ntype,nharder do i=1,nosd zn=zsave(:,i) ! call osd240_74(zn,Keff,apmask,norder,message74,cw,nharderror,dminosd) - call fastosd240_74(zn,Keff,apmask,norder,message74,cw,nharderror,dminosd) + call fastosd240_74_owned(work,zn,Keff,apmask,norder,message74,cw,nharderror,dminosd) if(nharderror.gt.0) then hdec=0 where(llr .ge. 0) hdec=1 @@ -158,4 +165,15 @@ subroutine decode240_74(llr,Keff,maxosd,norder,apmask,message74,cw,ntype,nharder dminosd=0.0 return -end subroutine decode240_74 +end subroutine decode240_74_owned + +end module fst4_ldpc_74 + +subroutine decode240_74(llr,Keff,maxosd,norder,apmask,message74,cw,ntype,nharderror,dmin) + use fst4_ldpc_74, only: decode240_74_owned + use fst4_osd_workspace, only: fst4_osd_workspace_type + type(fst4_osd_workspace_type), save :: legacy + real llr(240),dmin + integer*1 apmask(240),message74(74),cw(240) + call decode240_74_owned(legacy,llr,Keff,maxosd,norder,apmask,message74,cw,ntype,nharderror,dmin) +end subroutine diff --git a/lib/fst4/fastosd240_74.f90 b/lib/fst4/fastosd240_74.f90 index 9af0f4e9..50843a0f 100644 --- a/lib/fst4/fastosd240_74.f90 +++ b/lib/fst4/fastosd240_74.f90 @@ -1,4 +1,9 @@ -subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) +module fastosd240_74_module + use fst4_osd_workspace, only: fst4_osd_workspace_type + private + public :: fastosd240_74_owned +contains +subroutine fastosd240_74_owned(work,llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! ! An ordered-statistics decoder for the (240,74) code. ! Message payload is 50 bits. Any or all of a 24-bit CRC can be @@ -12,29 +17,35 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! ! Valid values for k are in the range [50,74]. ! + type(fst4_osd_workspace_type), intent(inout), target :: work + integer :: iscratch,jscratch character*24 c24 integer, parameter:: N=240 integer*1 apmask(N),apmaskr(N) - integer*1, allocatable, save :: gen(:,:) - integer*1, allocatable :: genmrb(:,:),g2(:,:) - integer*1, allocatable :: temp(:),temprow(:),m0(:),me(:),mi(:) + integer*1, pointer, contiguous :: gen(:,:) + integer*1, pointer, contiguous :: genmrb(:,:),g2(:,:) + integer*1, pointer, contiguous :: temp(:),temprow(:),m0(:),me(:),mi(:) integer indices(N),indices2(N),nxor(N) integer*1 cw(N),ce(N),c0(N),hdec(N) - integer*1, allocatable :: decoded(:) + integer*1, pointer, contiguous :: decoded(:) integer*1 message74(74) - integer*1, allocatable :: sp(:) - integer indx(N),ksave + integer*1, pointer, contiguous :: sp(:) + integer indx(N) real llr(N),rx(N),absrx(N) - logical first - data first/.true./,ksave/64/ - save first,ksave - allocate( genmrb(k,N), g2(N,k) ) - allocate( temp(k), temprow(n), m0(k), me(k), mi(k) ) - allocate( decoded(k) ) - if( first .or. k.ne.ksave) then ! fill the generator matrix + call work%ensure() + genmrb(1:k,1:N)=>work%matrix(1:k*N) + g2(1:N,1:k)=>work%transpose_matrix(1:k*N) + temp=>work%vectors(1:k,1) + temprow=>work%vectors(1:N,2) + m0=>work%vectors(1:k,3) + me=>work%vectors(1:k,4) + mi=>work%vectors(1:k,5) + decoded=>work%vectors(1:k,6) + sp=>work%vectors(1:32,7) + if(.not.allocated(work%generator(k)%matrix)) then ! fill the generator matrix ! ! Create generator matrix for partial CRC cascaded with LDPC code. ! @@ -44,8 +55,8 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! ! The first p1=k-50 CRC24 bits will be used for error detection. ! - if( allocated(gen) ) deallocate(gen) - allocate( gen(k,N) ) + allocate(work%generator(k)%matrix(k,N)) + gen=>work%generator(k)%matrix gen=0 do i=1,k message74=0 @@ -60,10 +71,10 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) gen(i,:)=cw enddo - first=.false. - ksave=k endif + gen=>work%generator(k)%matrix + ! Use best k elements from the sorted list for the first basis. For the 2nd basis replace ! the nswap lowest quality symbols with the best nswap elements from the parity symbols. nswap=20 @@ -82,15 +93,19 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! Re-order the columns of the generator matrix in order of decreasing reliability. do i=1,N - genmrb(1:k,i)=gen(1:k,indx(N+1-i)) + do jscratch=1,k + genmrb(jscratch,i)=gen(jscratch,indx(N+1-i)) + enddo indices(i)=indx(N+1-i) enddo if(ibasis.eq.2) then do i=k-nswap+1,k - temp(1:k)=genmrb(1:k,i) - genmrb(1:k,i)=genmrb(1:k,i+nswap) - genmrb(1:k,i+nswap)=temp(1:k) + do jscratch=1,k + temp(jscratch)=genmrb(jscratch,i) + genmrb(jscratch,i)=genmrb(jscratch,i+nswap) + genmrb(jscratch,i+nswap)=temp(jscratch) + enddo itmp=indices(i) indices(i)=indices(i+nswap) indices(i+nswap)=itmp @@ -109,9 +124,11 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) if(genmrb(id,icol).ne.1) then do j=id+1,k if(genmrb(j,icol).eq.1) then - temprow=genmrb(id,:) - genmrb(id,:)=genmrb(j,:) - genmrb(j,:)=temprow + do jscratch=1,N + temprow(jscratch)=genmrb(id,jscratch) + genmrb(id,jscratch)=genmrb(j,jscratch) + genmrb(j,jscratch)=temprow(jscratch) + enddo iflag=1 endif enddo @@ -127,7 +144,9 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) indices2(id)=icol do j=1,k if(id.ne.j .and. genmrb(j,icol).eq.1) then - genmrb(j,:)=ieor(genmrb(id,:),genmrb(j,:)) + do jscratch=1,N + genmrb(j,jscratch)=ieor(genmrb(id,jscratch),genmrb(j,jscratch)) + enddo endif enddo icol=icol+1 @@ -135,11 +154,22 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) do i=k+nskipped+1,240 indices2(i)=i enddo - genmrb(1:k,:)=genmrb(1:k,indices2) + do iscratch=1,k + do jscratch=1,N + temprow(jscratch)=genmrb(iscratch,jscratch) + enddo + do jscratch=1,N + genmrb(iscratch,jscratch)=temprow(indices2(jscratch)) + enddo + enddo indices=indices(indices2) !************************************ - g2=transpose(genmrb) + do iscratch=1,k + do jscratch=1,N + g2(jscratch,iscratch)=genmrb(iscratch,jscratch) + enddo + enddo ! The hard decisions for the k MRB bits define the order 0 message, m0. ! Encode m0 using the modified generator matrix to find the "order 0" codeword. @@ -159,7 +189,6 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) nhardmin=sum(nxor) dmin=sum(nxor*absrx) np=32 - if(ibasis.eq.1) allocate(sp(np)) cw=c0 ntotal=0 @@ -202,7 +231,9 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) iflag=k-iorder+1 do while(iflag .ge.0) ntotal=ntotal+1 - me=ieor(m0,mi) + do iscratch=1,k + me(iscratch)=ieor(m0(iscratch),mi(iscratch)) + enddo d1=sum(mi(1:k)*absrx(1:k)) if(d1.gt.rhodmin) exit call partial_syndrome(me,sp,np,g2,N,K) @@ -234,7 +265,7 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) nhardmin=-nhardmin enddo ! basis loop return -end subroutine fastosd240_74 +end subroutine fastosd240_74_owned subroutine mrbencode74(me,codeword,g2,N,K) integer*1 me(K),codeword(N),g2(N,K) @@ -261,7 +292,7 @@ subroutine partial_syndrome(me,sp,np,g2,N,K) end subroutine partial_syndrome subroutine nextpat74(mi,k,iorder,iflag) - integer*1 mi(k),ms(k) + integer*1 mi(k),ms(101) ! generate the next test error pattern ind=-1 do i=1,k-1 @@ -279,7 +310,7 @@ subroutine nextpat74(mi,k,iorder,iflag) nz=iorder-sum(ms) ms(k-nz+1:k)=1 endif - mi=ms + mi=ms(1:k) do i=1,k ! iflag will point to the lowest-index 1 in mi if(mi(i).eq.1) then iflag=i @@ -289,3 +320,14 @@ subroutine nextpat74(mi,k,iorder,iflag) return end subroutine nextpat74 + +end module fastosd240_74_module + +subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) + use fastosd240_74_module, only: fastosd240_74_owned + use fst4_osd_workspace, only: fst4_osd_workspace_type + type(fst4_osd_workspace_type), save :: legacy + real llr(240),dmin + integer*1 apmask(240),message74(74),cw(240) + call fastosd240_74_owned(legacy,llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) +end subroutine diff --git a/lib/fst4/fst4_baseline.f90 b/lib/fst4/fst4_baseline.f90 index 0000fa65..5c3ed1ed 100644 --- a/lib/fst4/fst4_baseline.f90 +++ b/lib/fst4/fst4_baseline.f90 @@ -1,11 +1,14 @@ -subroutine fst4_baseline(s,np,ia,ib,npct,sbase) +module fst4_baseline_workspace +contains +subroutine fst4_baseline_owned(s,np,ia,ib,npct,sbase,sw) ! Fit baseline to spectrum (for FST4) ! Input: s(npts) Linear scale in power ! Output: sbase(npts) Baseline implicit real*8 (a-h,o-z) - real*4 s(np),sw(np) + real*4 s(np) + real*4 :: sw(np) real*4 sbase(np) real*4 base real*8 x(1000),y(1000),a(5) @@ -45,4 +48,13 @@ subroutine fst4_baseline(s,np,ia,ib,npct,sbase) sbase=10**(sbase/10.0) return -end subroutine fst4_baseline +end subroutine fst4_baseline_owned +end module fst4_baseline_workspace + +subroutine fst4_baseline(s,np,ia,ib,npct,sbase) + use fst4_baseline_workspace, only: fst4_baseline_owned + real s(np),sbase(np) + real, allocatable :: scratch(:) + allocate(scratch(np)) + call fst4_baseline_owned(s,np,ia,ib,npct,sbase,scratch) +end subroutine diff --git a/lib/fst4/fst4_osd_workspace.f90 b/lib/fst4/fst4_osd_workspace.f90 new file mode 100644 index 00000000..137fc05c --- /dev/null +++ b/lib/fst4/fst4_osd_workspace.f90 @@ -0,0 +1,40 @@ +module fst4_osd_workspace + implicit none + private + public :: fst4_osd_workspace_type + type generator_cache + integer(kind=1), allocatable :: matrix(:,:) + end type + type fst4_osd_workspace_type + type(generator_cache) :: generator(0:101) + integer(kind=1), allocatable :: matrix(:),transpose_matrix(:),vectors(:,:) + integer, allocatable :: box_indices(:,:),box_first(:),box_next(:) + integer :: last_pattern=-1,next_index=-1 + contains + procedure :: ensure + procedure :: ensure_boxes + procedure :: destroy + end type +contains + subroutine ensure(this) + class(fst4_osd_workspace_type), intent(inout) :: this + if(allocated(this%matrix)) return + allocate(this%matrix(240*101),this%transpose_matrix(240*101),this%vectors(240,12)) + end subroutine + subroutine ensure_boxes(this) + class(fst4_osd_workspace_type), intent(inout) :: this + if(allocated(this%box_indices)) return + allocate(this%box_indices(5000,2),this%box_first(0:525000),this%box_next(5000)) + end subroutine + subroutine destroy(this) + class(fst4_osd_workspace_type), intent(inout) :: this + integer i + do i=lbound(this%generator,1),ubound(this%generator,1) + if(allocated(this%generator(i)%matrix)) deallocate(this%generator(i)%matrix) + enddo + if(allocated(this%matrix)) deallocate(this%matrix,this%transpose_matrix,this%vectors) + if(allocated(this%box_indices)) deallocate(this%box_indices,this%box_first,this%box_next) + this%last_pattern=-1 + this%next_index=-1 + end subroutine +end module diff --git a/lib/fst4/gen_fst4wave.f90 b/lib/fst4/gen_fst4wave.f90 index 516bf722..5f55ca9b 100644 --- a/lib/fst4/gen_fst4wave.f90 +++ b/lib/fst4/gen_fst4wave.f90 @@ -1,95 +1,113 @@ -subroutine gen_fst4wave(itone,nsym,nsps,nwave,fsample,hmod,f0, & +module fst4_wavegen + private + public :: fst4_wavegen_workspace,gen_fst4wave_owned + type fst4_wavegen_workspace + complex, allocatable :: ctab(:) + real, allocatable :: pulse(:),dphi(:),scaled_pulse(:) + integer :: nsps=0 + real :: twopi=0,dt=0,tsym=0 + logical :: first=.true.,shape=.true. + end type +contains +subroutine gen_fst4wave_owned(work,itone,nsym,nsps,nwave,fsample,hmod,f0, & icmplx,cwave,wave) - use prog_args + type(fst4_wavegen_workspace), intent(inout) :: work parameter(NTAB=65536) - real wave(nwave) - complex cwave(nwave),ctab(0:NTAB-1) + real wave(*) + complex cwave(*) character(len=1) :: cvalue - real, allocatable, save :: pulse(:) - real, allocatable :: dphi(:), scaled_pulse(:) integer hmod integer itone(nsym) - logical first, lshape - data first/.true./ - data nsps0/-99/ - data lshape/.true./ - save first,twopi,dt,tsym,nsps0,ctab,lshape - if(first) then - twopi=8.0*atan(1.0) + if(work%first) then + allocate(work%ctab(0:NTAB-1)) + work%twopi=8.0*atan(1.0) do i=0,NTAB-1 - phi=i*twopi/NTAB - ctab(i)=cmplx(cos(phi),sin(phi)) + phi=i*work%twopi/NTAB + work%ctab(i)=cmplx(cos(phi),sin(phi)) enddo call get_environment_variable("FST4_NOSHAPING",cvalue,nlen) - if(nlen.eq.1 .and. cvalue.eq."1") lshape=.false. + if(nlen.eq.1 .and. cvalue.eq."1") work%shape=.false. endif - if(first.or.nsps.ne.nsps0) then - if(allocated(pulse)) deallocate(pulse) - allocate(pulse(1:3*nsps)) - dt=1.0/fsample - tsym=nsps/fsample + if(work%first.or.nsps.ne.work%nsps) then + if(allocated(work%pulse)) then + if(size(work%pulse)<3*nsps) deallocate(work%pulse,work%dphi,work%scaled_pulse) + endif + if(.not.allocated(work%pulse)) & + allocate(work%pulse(1:3*nsps),work%dphi(0:nsps-1),work%scaled_pulse(3*nsps)) + work%dt=1.0/fsample + work%tsym=nsps/fsample ! Compute the smoothed frequency-deviation pulse do i=1,3*nsps tt=(i-1.5*nsps)/real(nsps) - pulse(i)=gfsk_pulse(2.0,tt) + work%pulse(i)=gfsk_pulse(2.0,tt) enddo - first=.false. - nsps0=nsps + work%first=.false. + work%nsps=nsps endif ! Generate one symbol at a time, retaining phase across symbol boundaries. - allocate(dphi(0:nsps-1)) - dphi_peak=twopi*hmod/real(nsps) - allocate(scaled_pulse(3*nsps)) - scaled_pulse=dphi_peak*pulse - carrier=twopi*(f0-1.5*hmod/tsym)*dt + dphi_peak=work%twopi*hmod/real(nsps) + work%scaled_pulse(1:3*nsps)=dphi_peak*work%pulse(1:3*nsps) + carrier=work%twopi*(f0-1.5*hmod/work%tsym)*work%dt if(icmplx.eq.0) wave(nsym*nsps+1:nwave)=0. if(icmplx.eq.1) cwave(nsym*nsps+1:nwave)=0. phi=0.0 k=0 do iblock=1,nsym - dphi=0.0 + work%dphi(0:nsps-1)=0.0 ! Accumulate overlapping pulses in tone order to preserve phase rounding. do j=max(1,iblock-1),min(nsym,iblock+1) ip=(iblock-j+1)*nsps+1 - dphi=dphi+scaled_pulse(ip:ip+nsps-1)*itone(j) + work%dphi(0:nsps-1)=work%dphi(0:nsps-1)+work%scaled_pulse(ip:ip+nsps-1)*itone(j) enddo - dphi=dphi+carrier + work%dphi(0:nsps-1)=work%dphi(0:nsps-1)+carrier do j=0,nsps-1 k=k+1 - i=phi*float(NTAB)/twopi + i=phi*float(NTAB)/work%twopi i=iand(i,NTAB-1) if(icmplx.eq.0) then - wave(k)=aimag(ctab(i)) + wave(k)=aimag(work%ctab(i)) else - cwave(k)=ctab(i) + cwave(k)=work%ctab(i) endif - phi=phi+dphi(j) - if(phi.gt.twopi) phi=phi-twopi + phi=phi+work%dphi(j) + if(phi.gt.work%twopi) phi=phi-work%twopi enddo enddo -! Compute the ramp-up and ramp-down symbols - if(icmplx.eq.0) then - if(lshape) then - wave(1:nsps/4)=wave(1:nsps/4) * & - (1.0-cos(twopi*(/(i,i=0,nsps/4-1)/)/real(nsps/2)))/2.0 - k1=(nsym-1)*nsps+3*nsps/4+1 - wave(k1:k1+nsps/4)=wave(k1:k1+nsps/4) * & - (1.0+cos(twopi*(/(i,i=0,nsps/4)/)/real(nsps/2)))/2.0 - endif - else - if(lshape) then - cwave(1:nsps/4)=cwave(1:nsps/4) * & - (1.0-cos(twopi*(/(i,i=0,nsps/4-1)/)/real(nsps/2)))/2.0 - k1=(nsym-1)*nsps+3*nsps/4+1 - cwave(k1:k1+nsps/4)=cwave(k1:k1+nsps/4) * & - (1.0+cos(twopi*(/(i,i=0,nsps/4)/)/real(nsps/2)))/2.0 - endif +! Apply the symbol amplitude envelope. + if(work%shape) then + k1=(nsym-1)*nsps+3*nsps/4+1 + do i=0,nsps/4-1 + envelope=(1.0-cos(work%twopi*i/real(nsps/2)))/2.0 + if(icmplx.eq.0) then + wave(i+1)=wave(i+1)*envelope + else + cwave(i+1)=cwave(i+1)*envelope + endif + enddo + do i=0,nsps/4 + envelope=(1.0+cos(work%twopi*i/real(nsps/2)))/2.0 + if(icmplx.eq.0) then + wave(k1+i)=wave(k1+i)*envelope + else + cwave(k1+i)=cwave(k1+i)*envelope + endif + enddo endif return -end subroutine gen_fst4wave +end subroutine gen_fst4wave_owned +end module fst4_wavegen + +subroutine gen_fst4wave(itone,nsym,nsps,nwave,fsample,hmod,f0,icmplx,cwave,wave) + use fst4_wavegen, only: fst4_wavegen_workspace,gen_fst4wave_owned + type(fst4_wavegen_workspace), save :: legacy + integer itone(nsym),hmod + real wave(*),fsample,f0 + complex cwave(*) + call gen_fst4wave_owned(legacy,itone,nsym,nsps,nwave,fsample,hmod,f0,icmplx,cwave,wave) +end subroutine diff --git a/lib/fst4/get_fst4_bitmetrics.f90 b/lib/fst4/get_fst4_bitmetrics.f90 index 762daa25..0d5be313 100644 --- a/lib/fst4/get_fst4_bitmetrics.f90 +++ b/lib/fst4/get_fst4_bitmetrics.f90 @@ -1,56 +1,63 @@ -subroutine get_fst4_bitmetrics(cd,nss,bitmetrics,s4,nsync_qual,badsync) +module fst4_bitmetrics + implicit none + type fst4_bitmetrics_workspace + complex, allocatable :: ci(:,:) + logical, allocatable :: one(:,:),zero(:,:) + real, allocatable :: s2(:) + integer :: nss=0 + end type +contains +subroutine get_fst4_bitmetrics_owned(work,cd,nss,bitmetrics,s4,nsync_qual,badsync) use timer_module, only: timer + implicit real(a-h,o-z) + implicit integer(i-n) include 'fst4_params.f90' complex cd(0:NN*nss-1) complex cs(0:3,NN) - complex csymb(nss) - complex, allocatable, save :: ci(:,:) ! ideal waveforms, 20 samples per symbol, 4 tones + type(fst4_bitmetrics_workspace), intent(inout), target :: work complex c1(4,8),c2(16,4),c4(256,2) integer isyncword1(0:7),isyncword2(0:7) integer graymap(0:3) integer ip(1) integer hbits(2*NN) - logical one(0:65535,0:15) ! 65536 8-symbol sequences, 16 bits - logical first logical badsync real bitmetrics(2*NN,4) - real, save :: s2(0:65535) real s4(0:3,NN) data isyncword1/0,1,3,2,1,0,2,3/ data isyncword2/2,3,1,0,3,2,0,1/ data graymap/0,1,3,2/ - data first/.true./,nss0/-1/ - save first,one,nss0 - - if(nss.ne.nss0 .and. allocated(ci)) deallocate(ci) - - if(first .or. nss.ne.nss0) then - allocate(ci(nss,0:3)) - one=.false. + if(.not.allocated(work%one)) then + allocate(work%one(0:65535,0:15),work%zero(0:65535,0:15),work%s2(0:65535)) do i=0,65535 do j=0,15 - if(iand(i,2**j).ne.0) one(i,j)=.true. + work%one(i,j)=btest(i,j) + work%zero(i,j)=.not.work%one(i,j) enddo enddo + endif + if(nss.ne.work%nss) then + if(allocated(work%ci)) then + if(size(work%ci,1)<nss) deallocate(work%ci) + endif + if(.not.allocated(work%ci)) allocate(work%ci(nss,0:3)) twopi=8.0*atan(1.0) dphi=twopi/nss do itone=0,3 dp=(itone-1.5)*dphi phi=0.0 do j=1,nss - ci(j,itone)=cmplx(cos(phi),sin(phi)) + work%ci(j,itone)=cmplx(cos(phi),sin(phi)) phi=mod(phi+dp,twopi) enddo enddo - first=.false. + work%nss=nss endif do k=1,NN i1=(k-1)*NSS - csymb=cd(i1:i1+NSS-1) do itone=0,3 - cs(itone,k)=sum(csymb*conjg(ci(:,itone))) + cs(itone,k)=sum(cd(i1:i1+nss-1)*conjg(work%ci(1:nss,itone))) enddo s4(0:3,k)=abs(cs(0:3,k))**2 enddo @@ -94,67 +101,64 @@ subroutine get_fst4_bitmetrics(cd,nss,bitmetrics,s4,nsync_qual,badsync) do k=1,NN,8 do m=1,8 ! do 4 1-symbol correlations for each of 8 symbs - s2=0 do n=1,4 c1(n,m)=cs(graymap(n-1),k+m-1) - s2(n-1)=abs(c1(n,m)) + work%s2(n-1)=abs(c1(n,m)) enddo ipt=(k-1)*2+2*(m-1)+1 do ib=0,1 - bm=maxval(s2(0:3),one(0:3,1-ib)) - & - maxval(s2(0:3),.not.one(0:3,1-ib)) + bm=maxval(work%s2(0:3),work%one(0:3,1-ib)) - & + maxval(work%s2(0:3),work%zero(0:3,1-ib)) if(ipt+ib.gt.2*NN) cycle bitmetrics(ipt+ib,1)=bm enddo enddo do m=1,4 ! do 16 2-symbol correlations for each of 4 2-symbol groups - s2=0 do i=1,4 do j=1,4 is=(i-1)*4+j c2(is,m)=c1(i,2*m-1)-c1(j,2*m) - s2(is-1)=abs(c2(is,m)) + work%s2(is-1)=abs(c2(is,m)) enddo enddo ipt=(k-1)*2+4*(m-1)+1 do ib=0,3 - bm=maxval(s2(0:15),one(0:15,3-ib)) - & - maxval(s2(0:15),.not.one(0:15,3-ib)) + bm=maxval(work%s2(0:15),work%one(0:15,3-ib)) - & + maxval(work%s2(0:15),work%zero(0:15,3-ib)) if(ipt+ib.gt.2*NN) cycle bitmetrics(ipt+ib,2)=bm enddo enddo do m=1,2 ! do 256 4-symbol corrs for each of 2 4-symbol groups - s2=0 do i=1,16 do j=1,16 is=(i-1)*16+j c4(is,m)=c2(i,2*m-1)+c2(j,2*m) - s2(is-1)=abs(c4(is,m)) + work%s2(is-1)=abs(c4(is,m)) enddo enddo ipt=(k-1)*2+8*(m-1)+1 do ib=0,7 - bm=maxval(s2(0:255),one(0:255,7-ib)) - & - maxval(s2(0:255),.not.one(0:255,7-ib)) + bm=maxval(work%s2(0:255),work%one(0:255,7-ib)) - & + maxval(work%s2(0:255),work%zero(0:255,7-ib)) if(ipt+ib.gt.2*NN) cycle bitmetrics(ipt+ib,3)=bm enddo enddo - s2=0 ! do 65536 8-symbol correlations for the entire group + ! Combine the two four-symbol groups into eight-symbol correlations. do i=1,256 do j=1,256 is=(i-1)*256+j - s2(is-1)=abs(c4(i,1)+c4(j,2)) + work%s2(is-1)=abs(c4(i,1)+c4(j,2)) enddo enddo ipt=(k-1)*2+1 do ib=0,15 - bm=maxval(s2(0:65535),one(0:65535,15-ib)) - & - maxval(s2(0:65535),.not.one(0:65535,15-ib)) + bm=maxval(work%s2(0:65535),work%one(0:65535,15-ib)) - & + maxval(work%s2(0:65535),work%zero(0:65535,15-ib)) if(ipt+ib.gt.2*NN) cycle bitmetrics(ipt+ib,4)=bm enddo @@ -187,4 +191,15 @@ subroutine get_fst4_bitmetrics(cd,nss,bitmetrics,s4,nsync_qual,badsync) return -end subroutine get_fst4_bitmetrics +end subroutine get_fst4_bitmetrics_owned + +end module fst4_bitmetrics + +subroutine get_fst4_bitmetrics(cd,nss,bitmetrics,s4,nsync_qual,badsync) + use fst4_bitmetrics + type(fst4_bitmetrics_workspace), save :: legacy + complex cd(0:160*nss-1) + real bitmetrics(320,4),s4(0:3,160) + logical badsync + call get_fst4_bitmetrics_owned(legacy,cd,nss,bitmetrics,s4,nsync_qual,badsync) +end subroutine diff --git a/lib/fst4/osd240_101.f90 b/lib/fst4/osd240_101.f90 index 199b27a8..7ca50fca 100644 --- a/lib/fst4/osd240_101.f90 +++ b/lib/fst4/osd240_101.f90 @@ -1,4 +1,9 @@ -subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) +module osd240_101_module + use fst4_osd_workspace, only: fst4_osd_workspace_type + private + public :: osd240_101_owned +contains +subroutine osd240_101_owned(work,llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) ! ! An ordered-statistics decoder for the (240,101) code. ! Message payload is 77 bits. Any or all of a 24-bit CRC can be @@ -12,29 +17,38 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) ! ! Valid values for k are in the range [77,101]. ! + type(fst4_osd_workspace_type), intent(inout), target :: work + integer :: iscratch,jscratch character*24 c24 integer, parameter:: N=240 integer*1 apmask(N),apmaskr(N) - integer*1, allocatable, save :: gen(:,:) - integer*1, allocatable :: genmrb(:,:),g2(:,:) - integer*1, allocatable :: temp(:),m0(:),me(:),mi(:),misub(:),e2sub(:),e2(:),ui(:) - integer*1, allocatable :: r2pat(:) + integer*1, pointer, contiguous :: gen(:,:) + integer*1, pointer, contiguous :: genmrb(:,:),g2(:,:) + integer*1, pointer, contiguous :: temp(:),m0(:),me(:),mi(:),misub(:),e2sub(:),e2(:),ui(:) + integer*1, pointer, contiguous :: r2pat(:) integer indices(N),nxor(N) integer*1 cw(N),ce(N),c0(N),hdec(N) - integer*1, allocatable :: decoded(:) + integer*1, pointer, contiguous :: decoded(:) integer*1 message101(101) integer indx(N) real llr(N),rx(N),absrx(N) - logical first,reset - data first/.true./ - save first - - allocate( genmrb(k,N), g2(N,k) ) - allocate( temp(k), m0(k), me(k), mi(k), misub(k), e2sub(N-k), e2(N-k), ui(N-k) ) - allocate( r2pat(N-k), decoded(k) ) + logical reset - if( first ) then ! fill the generator matrix + call work%ensure() + genmrb(1:k,1:N)=>work%matrix(1:k*N) + g2(1:N,1:k)=>work%transpose_matrix(1:k*N) + temp=>work%vectors(1:k,1) + m0=>work%vectors(1:k,2) + me=>work%vectors(1:k,3) + mi=>work%vectors(1:k,4) + misub=>work%vectors(1:k,5) + e2sub=>work%vectors(1:N-k,6) + e2=>work%vectors(1:N-k,7) + ui=>work%vectors(1:N-k,8) + r2pat=>work%vectors(1:N-k,9) + decoded=>work%vectors(1:k,10) + if(.not.allocated(work%generator(k)%matrix)) then ! fill the generator matrix ! ! Create generator matrix for partial CRC cascaded with LDPC code. ! @@ -44,7 +58,8 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) ! ! The first p1=k-77 CRC24 bits will be used for error detection. ! - allocate( gen(k,N) ) + allocate(work%generator(k)%matrix(k,N)) + gen=>work%generator(k)%matrix gen=0 do i=1,k message101=0 @@ -59,9 +74,10 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) gen(i,:)=cw enddo - first=.false. endif + gen=>work%generator(k)%matrix + rx=llr apmaskr=apmask @@ -75,7 +91,9 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) ! Re-order the columns of the generator matrix in order of decreasing reliability. do i=1,N - genmrb(1:k,i)=gen(1:k,indx(N+1-i)) + do jscratch=1,k + genmrb(jscratch,i)=gen(jscratch,indx(N+1-i)) + enddo indices(i)=indx(N+1-i) enddo @@ -87,16 +105,20 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) if( genmrb(id,icol) .eq. 1 ) then iflag=1 if( icol .ne. id ) then ! reorder column - temp(1:k)=genmrb(1:k,id) - genmrb(1:k,id)=genmrb(1:k,icol) - genmrb(1:k,icol)=temp(1:k) + do jscratch=1,k + temp(jscratch)=genmrb(jscratch,id) + genmrb(jscratch,id)=genmrb(jscratch,icol) + genmrb(jscratch,icol)=temp(jscratch) + enddo itmp=indices(id) indices(id)=indices(icol) indices(icol)=itmp endif do ii=1,k if( ii .ne. id .and. genmrb(ii,id) .eq. 1 ) then - genmrb(ii,1:N)=ieor(genmrb(ii,1:N),genmrb(id,1:N)) + do jscratch=1,N + genmrb(ii,jscratch)=ieor(genmrb(ii,jscratch),genmrb(id,jscratch)) + enddo endif enddo exit @@ -104,7 +126,11 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) enddo enddo - g2=transpose(genmrb) + do iscratch=1,k + do jscratch=1,N + g2(jscratch,iscratch)=genmrb(iscratch,jscratch) + enddo + enddo ! The hard decisions for the k MRB bits define the order 0 message, m0. ! Encode m0 using the modified generator matrix to find the "order 0" codeword. @@ -187,19 +213,27 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) endif d1=0. do n1=iflag,iend,-1 - mi=misub + do iscratch=1,k + mi(iscratch)=misub(iscratch) + enddo mi(n1)=1 if(any(iand(apmaskr(1:k),mi).eq.1)) cycle ntotal=ntotal+1 - me=ieor(m0,mi) + do iscratch=1,k + me(iscratch)=ieor(m0(iscratch),mi(iscratch)) + enddo if(n1.eq.iflag) then call mrbencode101(me,ce,g2,N,k) e2sub=ieor(ce(k+1:N),hdec(k+1:N)) - e2=e2sub + do iscratch=1,N-k + e2(iscratch)=e2sub(iscratch) + enddo nd1kpt=sum(e2sub(1:nt))+1 d1=sum(ieor(me(1:k),hdec(1:k))*absrx(1:k)) else - e2=ieor(e2sub,g2(k+1:N,n1)) + do iscratch=1,N-k + e2(iscratch)=ieor(e2sub(iscratch),g2(k+iscratch,n1)) + enddo nd1kpt=sum(e2(1:nt))+2 endif if(nd1kpt .le. ntheta) then @@ -232,8 +266,10 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) do i1=k,1,-1 do i2=i1-1,1,-1 ntotal=ntotal+1 - mi(1:ntau)=ieor(g2(k+1:k+ntau,i1),g2(k+1:k+ntau,i2)) - call boxit101(reset,mi(1:ntau),ntau,ntotal,i1,i2) + do iscratch=1,ntau + mi(iscratch)=ieor(g2(k+iscratch,i1),g2(k+iscratch,i2)) + enddo + call boxit101(work,reset,mi(1:ntau),ntau,ntotal,i1,i2) enddo enddo @@ -245,23 +281,31 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) misub(k-nord+1:k)=1 iflag=k-nord+1 do while(iflag .ge.0) - me=ieor(m0,misub) + do iscratch=1,k + me(iscratch)=ieor(m0(iscratch),misub(iscratch)) + enddo call mrbencode101(me,ce,g2,N,k) e2sub=ieor(ce(k+1:N),hdec(k+1:N)) do i2=0,ntau ntotal2=ntotal2+1 ui=0 if(i2.gt.0) ui(i2)=1 - r2pat=ieor(e2sub,ui) + do iscratch=1,N-k + r2pat(iscratch)=ieor(e2sub(iscratch),ui(iscratch)) + enddo 778 continue - call fetchit101(reset,r2pat(1:ntau),ntau,in1,in2) + call fetchit101(work,reset,r2pat(1:ntau),ntau,in1,in2) if(in1.gt.0.and.in2.gt.0) then ncount2=ncount2+1 - mi=misub + do iscratch=1,k + mi(iscratch)=misub(iscratch) + enddo mi(in1)=1 mi(in2)=1 if(sum(mi).lt.nord+npre1+npre2.or.any(iand(apmaskr(1:k),mi).eq.1)) cycle - me=ieor(m0,mi) + do iscratch=1,k + me(iscratch)=ieor(m0(iscratch),mi(iscratch)) + enddo call mrbencode101(me,ce,g2,N,k) nxor=ieor(ce,hdec) dd=sum(nxor*absrx) @@ -286,7 +330,7 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) if(nbadcrc.ne.0) nhardmin=-nhardmin return -end subroutine osd240_101 +end subroutine osd240_101_owned subroutine mrbencode101(me,codeword,g2,N,K) integer*1 me(K),codeword(N),g2(N,K) @@ -301,7 +345,7 @@ subroutine mrbencode101(me,codeword,g2,N,K) end subroutine mrbencode101 subroutine nextpat101(mi,k,iorder,iflag) - integer*1 mi(k),ms(k) + integer*1 mi(k),ms(101) ! generate the next test error pattern ind=-1 do i=1,k-1 @@ -319,7 +363,7 @@ subroutine nextpat101(mi,k,iorder,iflag) nz=iorder-sum(ms) ms(k-nz+1:k)=1 endif - mi=ms + mi=ms(1:k) do i=1,k ! iflag will point to the lowest-index 1 in mi if(mi(i).eq.1) then iflag=i @@ -329,23 +373,21 @@ subroutine nextpat101(mi,k,iorder,iflag) return end subroutine nextpat101 -subroutine boxit101(reset,e2,ntau,npindex,i1,i2) +subroutine boxit101(work,reset,e2,ntau,npindex,i1,i2) + type(fst4_osd_workspace_type), intent(inout) :: work integer*1 e2(1:ntau) - integer indexes(5000,2),fp(0:525000),np(5000) logical reset - common/boxes/indexes,fp,np + call work%ensure_boxes() if(reset) then - patterns=-1 - fp=-1 - np=-1 - sc=-1 - indexes=-1 + work%box_first=-1 + work%box_next=-1 + work%box_indices=-1 reset=.false. endif - indexes(npindex,1)=i1 - indexes(npindex,2)=i2 + work%box_indices(npindex,1)=i1 + work%box_indices(npindex,2)=i2 ipat=0 do i=1,ntau if(e2(i).eq.1) then @@ -353,28 +395,25 @@ subroutine boxit101(reset,e2,ntau,npindex,i1,i2) endif enddo - ip=fp(ipat) ! see what's currently stored in fp(ipat) + ip=work%box_first(ipat) ! see what's currently stored in work%box_first(ipat) if(ip.eq.-1) then - fp(ipat)=npindex + work%box_first(ipat)=npindex else - do while (np(ip).ne.-1) - ip=np(ip) + do while (work%box_next(ip).ne.-1) + ip=work%box_next(ip) enddo - np(ip)=npindex + work%box_next(ip)=npindex endif return end subroutine boxit101 -subroutine fetchit101(reset,e2,ntau,i1,i2) - integer indexes(5000,2),fp(0:525000),np(5000) - integer lastpat +subroutine fetchit101(work,reset,e2,ntau,i1,i2) + type(fst4_osd_workspace_type), intent(inout) :: work integer*1 e2(ntau) logical reset - common/boxes/indexes,fp,np - save lastpat,inext if(reset) then - lastpat=-1 + work%last_pattern=-1 reset=.false. endif @@ -384,21 +423,32 @@ subroutine fetchit101(reset,e2,ntau,i1,i2) ipat=ipat+ishft(1,ntau-i) endif enddo - index=fp(ipat) - - if(lastpat.ne.ipat .and. index.gt.0) then ! return first set of indices - i1=indexes(index,1) - i2=indexes(index,2) - inext=np(index) - elseif(lastpat.eq.ipat .and. inext.gt.0) then - i1=indexes(inext,1) - i2=indexes(inext,2) - inext=np(inext) + index=work%box_first(ipat) + + if(work%last_pattern.ne.ipat .and. index.gt.0) then ! return first set of indices + i1=work%box_indices(index,1) + i2=work%box_indices(index,2) + work%next_index=work%box_next(index) + elseif(work%last_pattern.eq.ipat .and. work%next_index.gt.0) then + i1=work%box_indices(work%next_index,1) + i2=work%box_indices(work%next_index,2) + work%next_index=work%box_next(work%next_index) else i1=-1 i2=-1 - inext=-1 + work%next_index=-1 endif - lastpat=ipat + work%last_pattern=ipat return end subroutine fetchit101 + +end module osd240_101_module + +subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) + use osd240_101_module, only: osd240_101_owned + use fst4_osd_workspace, only: fst4_osd_workspace_type + type(fst4_osd_workspace_type), save :: legacy + real llr(240),dmin + integer*1 apmask(240),message101(101),cw(240) + call osd240_101_owned(legacy,llr,k,apmask,ndeep,message101,cw,nhardmin,dmin) +end subroutine diff --git a/lib/fst4/osd240_74.f90 b/lib/fst4/osd240_74.f90 index 74cb1a0e..4c4817da 100644 --- a/lib/fst4/osd240_74.f90 +++ b/lib/fst4/osd240_74.f90 @@ -1,4 +1,9 @@ -subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) +module osd240_74_module + use fst4_osd_workspace, only: fst4_osd_workspace_type + private + public :: osd240_74_owned +contains +subroutine osd240_74_owned(work,llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! ! An ordered-statistics decoder for the (240,74) code. ! Message payload is 50 bits. Any or all of a 24-bit CRC can be @@ -12,29 +17,38 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! ! Valid values for k are in the range [50,74]. ! + type(fst4_osd_workspace_type), intent(inout), target :: work + integer :: iscratch,jscratch character*24 c24 integer, parameter:: N=240 integer*1 apmask(N),apmaskr(N) - integer*1, allocatable, save :: gen(:,:) - integer*1, allocatable :: genmrb(:,:),g2(:,:) - integer*1, allocatable :: temp(:),m0(:),me(:),mi(:),misub(:),e2sub(:),e2(:),ui(:) - integer*1, allocatable :: r2pat(:) + integer*1, pointer, contiguous :: gen(:,:) + integer*1, pointer, contiguous :: genmrb(:,:),g2(:,:) + integer*1, pointer, contiguous :: temp(:),m0(:),me(:),mi(:),misub(:),e2sub(:),e2(:),ui(:) + integer*1, pointer, contiguous :: r2pat(:) integer indices(N),nxor(N) integer*1 cw(N),ce(N),c0(N),hdec(N) - integer*1, allocatable :: decoded(:) + integer*1, pointer, contiguous :: decoded(:) integer*1 message74(74) integer indx(N) real llr(N),rx(N),absrx(N) - logical first,reset - data first/.true./ - save first - - allocate( genmrb(k,N), g2(N,k) ) - allocate( temp(k), m0(k), me(k), mi(k), misub(k), e2sub(N-k), e2(N-k), ui(N-k) ) - allocate( r2pat(N-k), decoded(k) ) + logical reset - if( first ) then ! fill the generator matrix + call work%ensure() + genmrb(1:k,1:N)=>work%matrix(1:k*N) + g2(1:N,1:k)=>work%transpose_matrix(1:k*N) + temp=>work%vectors(1:k,1) + m0=>work%vectors(1:k,2) + me=>work%vectors(1:k,3) + mi=>work%vectors(1:k,4) + misub=>work%vectors(1:k,5) + e2sub=>work%vectors(1:N-k,6) + e2=>work%vectors(1:N-k,7) + ui=>work%vectors(1:N-k,8) + r2pat=>work%vectors(1:N-k,9) + decoded=>work%vectors(1:k,10) + if(.not.allocated(work%generator(k)%matrix)) then ! fill the generator matrix ! ! Create generator matrix for partial CRC cascaded with LDPC code. ! @@ -44,7 +58,8 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! ! The first p1=k-50 CRC24 bits will be used for error detection. ! - allocate( gen(k,N) ) + allocate(work%generator(k)%matrix(k,N)) + gen=>work%generator(k)%matrix gen=0 do i=1,k message74=0 @@ -59,9 +74,10 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) gen(i,:)=cw enddo - first=.false. endif + gen=>work%generator(k)%matrix + rx=llr apmaskr=apmask @@ -75,7 +91,9 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) ! Re-order the columns of the generator matrix in order of decreasing reliability. do i=1,N - genmrb(1:k,i)=gen(1:k,indx(N+1-i)) + do jscratch=1,k + genmrb(jscratch,i)=gen(jscratch,indx(N+1-i)) + enddo indices(i)=indx(N+1-i) enddo @@ -87,16 +105,20 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) if( genmrb(id,icol) .eq. 1 ) then iflag=1 if( icol .ne. id ) then ! reorder column - temp(1:k)=genmrb(1:k,id) - genmrb(1:k,id)=genmrb(1:k,icol) - genmrb(1:k,icol)=temp(1:k) + do jscratch=1,k + temp(jscratch)=genmrb(jscratch,id) + genmrb(jscratch,id)=genmrb(jscratch,icol) + genmrb(jscratch,icol)=temp(jscratch) + enddo itmp=indices(id) indices(id)=indices(icol) indices(icol)=itmp endif do ii=1,k if( ii .ne. id .and. genmrb(ii,id) .eq. 1 ) then - genmrb(ii,1:N)=ieor(genmrb(ii,1:N),genmrb(id,1:N)) + do jscratch=1,N + genmrb(ii,jscratch)=ieor(genmrb(ii,jscratch),genmrb(id,jscratch)) + enddo endif enddo exit @@ -104,7 +126,11 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) enddo enddo - g2=transpose(genmrb) + do iscratch=1,k + do jscratch=1,N + g2(jscratch,iscratch)=genmrb(iscratch,jscratch) + enddo + enddo ! The hard decisions for the k MRB bits define the order 0 message, m0. ! Encode m0 using the modified generator matrix to find the "order 0" codeword. @@ -187,19 +213,27 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) endif d1=0. do n1=iflag,iend,-1 - mi=misub + do iscratch=1,k + mi(iscratch)=misub(iscratch) + enddo mi(n1)=1 if(any(iand(apmaskr(1:k),mi).eq.1)) cycle ntotal=ntotal+1 - me=ieor(m0,mi) + do iscratch=1,k + me(iscratch)=ieor(m0(iscratch),mi(iscratch)) + enddo if(n1.eq.iflag) then call mrbencode74(me,ce,g2,N,k) e2sub=ieor(ce(k+1:N),hdec(k+1:N)) - e2=e2sub + do iscratch=1,N-k + e2(iscratch)=e2sub(iscratch) + enddo nd1kpt=sum(e2sub(1:nt))+1 d1=sum(ieor(me(1:k),hdec(1:k))*absrx(1:k)) else - e2=ieor(e2sub,g2(k+1:N,n1)) + do iscratch=1,N-k + e2(iscratch)=ieor(e2sub(iscratch),g2(k+iscratch,n1)) + enddo nd1kpt=sum(e2(1:nt))+2 endif if(nd1kpt .le. ntheta) then @@ -232,8 +266,10 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) do i1=k,1,-1 do i2=i1-1,1,-1 ntotal=ntotal+1 - mi(1:ntau)=ieor(g2(k+1:k+ntau,i1),g2(k+1:k+ntau,i2)) - call boxit74(reset,mi(1:ntau),ntau,ntotal,i1,i2) + do iscratch=1,ntau + mi(iscratch)=ieor(g2(k+iscratch,i1),g2(k+iscratch,i2)) + enddo + call boxit74(work,reset,mi(1:ntau),ntau,ntotal,i1,i2) enddo enddo @@ -245,23 +281,31 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) misub(k-nord+1:k)=1 iflag=k-nord+1 do while(iflag .ge.0) - me=ieor(m0,misub) + do iscratch=1,k + me(iscratch)=ieor(m0(iscratch),misub(iscratch)) + enddo call mrbencode74(me,ce,g2,N,k) e2sub=ieor(ce(k+1:N),hdec(k+1:N)) do i2=0,ntau ntotal2=ntotal2+1 ui=0 if(i2.gt.0) ui(i2)=1 - r2pat=ieor(e2sub,ui) + do iscratch=1,N-k + r2pat(iscratch)=ieor(e2sub(iscratch),ui(iscratch)) + enddo 778 continue - call fetchit74(reset,r2pat(1:ntau),ntau,in1,in2) + call fetchit74(work,reset,r2pat(1:ntau),ntau,in1,in2) if(in1.gt.0.and.in2.gt.0) then ncount2=ncount2+1 - mi=misub + do iscratch=1,k + mi(iscratch)=misub(iscratch) + enddo mi(in1)=1 mi(in2)=1 if(sum(mi).lt.nord+npre1+npre2.or.any(iand(apmaskr(1:k),mi).eq.1)) cycle - me=ieor(m0,mi) + do iscratch=1,k + me(iscratch)=ieor(m0(iscratch),mi(iscratch)) + enddo call mrbencode74(me,ce,g2,N,k) nxor=ieor(ce,hdec) dd=sum(nxor*absrx) @@ -286,7 +330,7 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) if(nbadcrc.ne.0) nhardmin=-nhardmin return -end subroutine osd240_74 +end subroutine osd240_74_owned subroutine mrbencode74(me,codeword,g2,N,K) integer*1 me(K),codeword(N),g2(N,K) @@ -301,7 +345,7 @@ subroutine mrbencode74(me,codeword,g2,N,K) end subroutine mrbencode74 subroutine nextpat74(mi,k,iorder,iflag) - integer*1 mi(k),ms(k) + integer*1 mi(k),ms(101) ! generate the next test error pattern ind=-1 do i=1,k-1 @@ -319,7 +363,7 @@ subroutine nextpat74(mi,k,iorder,iflag) nz=iorder-sum(ms) ms(k-nz+1:k)=1 endif - mi=ms + mi=ms(1:k) do i=1,k ! iflag will point to the lowest-index 1 in mi if(mi(i).eq.1) then iflag=i @@ -329,23 +373,21 @@ subroutine nextpat74(mi,k,iorder,iflag) return end subroutine nextpat74 -subroutine boxit74(reset,e2,ntau,npindex,i1,i2) +subroutine boxit74(work,reset,e2,ntau,npindex,i1,i2) + type(fst4_osd_workspace_type), intent(inout) :: work integer*1 e2(1:ntau) - integer indexes(5000,2),fp(0:525000),np(5000) logical reset - common/boxes/indexes,fp,np + call work%ensure_boxes() if(reset) then - patterns=-1 - fp=-1 - np=-1 - sc=-1 - indexes=-1 + work%box_first=-1 + work%box_next=-1 + work%box_indices=-1 reset=.false. endif - indexes(npindex,1)=i1 - indexes(npindex,2)=i2 + work%box_indices(npindex,1)=i1 + work%box_indices(npindex,2)=i2 ipat=0 do i=1,ntau if(e2(i).eq.1) then @@ -353,28 +395,25 @@ subroutine boxit74(reset,e2,ntau,npindex,i1,i2) endif enddo - ip=fp(ipat) ! see what's currently stored in fp(ipat) + ip=work%box_first(ipat) ! see what's currently stored in work%box_first(ipat) if(ip.eq.-1) then - fp(ipat)=npindex + work%box_first(ipat)=npindex else - do while (np(ip).ne.-1) - ip=np(ip) + do while (work%box_next(ip).ne.-1) + ip=work%box_next(ip) enddo - np(ip)=npindex + work%box_next(ip)=npindex endif return end subroutine boxit74 -subroutine fetchit74(reset,e2,ntau,i1,i2) - integer indexes(5000,2),fp(0:525000),np(5000) - integer lastpat +subroutine fetchit74(work,reset,e2,ntau,i1,i2) + type(fst4_osd_workspace_type), intent(inout) :: work integer*1 e2(ntau) logical reset - common/boxes/indexes,fp,np - save lastpat,inext if(reset) then - lastpat=-1 + work%last_pattern=-1 reset=.false. endif @@ -384,21 +423,32 @@ subroutine fetchit74(reset,e2,ntau,i1,i2) ipat=ipat+ishft(1,ntau-i) endif enddo - index=fp(ipat) - - if(lastpat.ne.ipat .and. index.gt.0) then ! return first set of indices - i1=indexes(index,1) - i2=indexes(index,2) - inext=np(index) - elseif(lastpat.eq.ipat .and. inext.gt.0) then - i1=indexes(inext,1) - i2=indexes(inext,2) - inext=np(inext) + index=work%box_first(ipat) + + if(work%last_pattern.ne.ipat .and. index.gt.0) then ! return first set of indices + i1=work%box_indices(index,1) + i2=work%box_indices(index,2) + work%next_index=work%box_next(index) + elseif(work%last_pattern.eq.ipat .and. work%next_index.gt.0) then + i1=work%box_indices(work%next_index,1) + i2=work%box_indices(work%next_index,2) + work%next_index=work%box_next(work%next_index) else i1=-1 i2=-1 - inext=-1 + work%next_index=-1 endif - lastpat=ipat + work%last_pattern=ipat return end subroutine fetchit74 + +end module osd240_74_module + +subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) + use osd240_74_module, only: osd240_74_owned + use fst4_osd_workspace, only: fst4_osd_workspace_type + type(fst4_osd_workspace_type), save :: legacy + real llr(240),dmin + integer*1 apmask(240),message74(74),cw(240) + call osd240_74_owned(legacy,llr,k,apmask,ndeep,message74,cw,nhardmin,dmin) +end subroutine diff --git a/lib/fst4_decode.f90 b/lib/fst4_decode.f90 index 83cf11f9..ed613445 100644 --- a/lib/fst4_decode.f90 +++ b/lib/fst4_decode.f90 @@ -1,15 +1,78 @@ module fst4_decode + use fst4_osd_workspace, only: fst4_osd_workspace_type + use fst4_ldpc_74, only: decode240_74_owned + use fst4_ldpc_101, only: decode240_101_owned + use fst4_wavegen, only: fst4_wavegen_workspace,gen_fst4wave_owned + use fst4_baseline_workspace, only: fst4_baseline_owned + use fst4_bitmetrics, only: fst4_bitmetrics_workspace,get_fst4_bitmetrics_owned + use decoder_engine_types, only: fst4_result + use packjt77, only: pack77_state,initialize_pack77_state,reset_pack77_state, & + pack77_for_state,unpack77_for_state + use, intrinsic :: iso_c_binding + use fftw3, only: fftwf_alloc_complex,fftwf_free,fftwf_plan_dft_r2c_1d,fftwf_plan_dft_1d, & + fftwf_destroy_plan,fftwf_execute_dft_r2c,fftwf_execute_dft,FFTW_ESTIMATE,FFTW_FORWARD,FFTW_BACKWARD + private + public :: fst4_decoder,fst4_options,fst4_decode_callback,fst4_diagnostic_callback,fst4_spectrum_callback + + type fst4_options + integer :: utc=0,period=15,receive_frequency=1500,low_frequency=200,high_frequency=4000 + integer :: tolerance=100,effort=1,qso_progress=0,blanker_percent=0,blanker_step=0 + integer :: fft_flags=FFTW_ESTIMATE + real :: eme_delay=0 + logical :: wspr=.false.,single_decode=.false.,ap_cq_only=.false. + logical :: measure_doppler=.false. + character(len=12) :: mycall='',hiscall='' + end type + type :: fst4_decoder - procedure(fst4_decode_callback), pointer :: callback + type(fst4_bitmetrics_workspace) :: metrics + type(fst4_osd_workspace_type) :: fec + type(fst4_wavegen_workspace) :: wavegen + type(pack77_state), pointer :: knowledge=>null() + complex(c_float_complex), pointer, contiguous :: big(:)=>null(),baseband(:)=>null(),frame(:)=>null() + integer, allocatable :: blanker_hist(:) + type(c_ptr) :: big_plan=c_null_ptr,baseband_plan=c_null_ptr,big_storage=c_null_ptr + integer :: fft_length=0,down_length=0,nwcalls=0 + integer :: fft_flags=FFTW_ESTIMATE + character(len=20) :: wcalls(100)='' + character(len=12) :: mycall0='',hiscall0='' + integer :: apbits(240)=0,nappasses(0:5)=0,naptypes(0:5,4)=0 + logical :: first=.true.,measure_doppler=.false.,owns_knowledge=.false. + logical :: host_history_loaded=.false.,history_dirty=.false. + procedure(fst4_diagnostic_callback), pointer, nopass :: diagnostic=>null() + procedure(fst4_spectrum_callback), pointer, nopass :: spectrum_sink=>null() + complex, allocatable :: sync1(:),sync2(:),synct1(:),synct2(:),sync_tweak(:) + integer :: sync_nss=0,sync_period=0 + real :: sync_frequency=-1.e30,sync_dt=0,sync_fac=0 + complex, pointer :: dopwave(:)=>null() + complex(c_float_complex), pointer, contiguous :: dopgain(:)=>null() + real, pointer :: dopss(:)=>null() + real, allocatable :: candidate_s(:),candidate_s2(:),candidate_base(:),baseline_scratch(:) + type(c_ptr) :: dop_plan=c_null_ptr,dop_storage=c_null_ptr + integer :: dop_length=0 + real, allocatable :: spectrum(:) + procedure(fst4_decode_callback), pointer :: callback=>null() contains - procedure :: decode + procedure :: decode_pcm + procedure :: initialize + procedure :: reset + procedure :: destroy + procedure :: set_known_calls + procedure :: get_known_calls + final :: finalize end type fst4_decoder abstract interface + subroutine fst4_spectrum_callback(spectrum,df,first_frequency) + real, intent(in) :: spectrum(:),df,first_frequency + end subroutine + subroutine fst4_diagnostic_callback(line) + character(len=*), intent(in) :: line + end subroutine subroutine fst4_decode_callback (this,nutc,sync,nsnr,dt,freq, & - decoded,nap,qual,ntrperiod,fmid,w50) - import fst4_decoder + decoded,nap,qual,ntrperiod,fmid,w50,result) + import fst4_decoder,fst4_result implicit none class(fst4_decoder), intent(inout) :: this integer, intent(in) :: nutc @@ -23,16 +86,183 @@ module fst4_decode integer, intent(in) :: ntrperiod real, intent(in) :: fmid real, intent(in) :: w50 + type(fst4_result), optional, intent(in) :: result end subroutine fst4_decode_callback end interface contains - subroutine decode(this,callback,iwave,nutc,nQSOProgress,nfa,nfb,nfqso, & - ndepth,ntrperiod,nexp_decode,ntol,emedelay,lagain,lapcqonly,mycall, & - hiscall,iwspr,lprinthash22) + subroutine initialize(this) + class(fst4_decoder), intent(inout) :: this + if(.not.associated(this%knowledge)) then + allocate(this%knowledge) + this%owns_knowledge=.true. + call initialize_pack77_state(this%knowledge) + endif + end subroutine + + subroutine reset(this) + class(fst4_decoder), intent(inout) :: this + this%wcalls='' + this%nwcalls=0 + this%mycall0='' + this%hiscall0='' + this%first=.true. + this%host_history_loaded=.false. + this%history_dirty=.false. + this%sync_nss=0 + this%sync_period=0 + this%sync_frequency=-1.e30 + if(associated(this%knowledge)) call reset_pack77_state(this%knowledge) + end subroutine + + subroutine destroy(this) + class(fst4_decoder), intent(inout) :: this + call clear_fft_plans(this) + call release_large_workspace(this) + if(associated(this%baseband)) deallocate(this%baseband) + if(associated(this%frame)) deallocate(this%frame) + nullify(this%baseband,this%frame) + if(allocated(this%blanker_hist)) deallocate(this%blanker_hist) + if(allocated(this%metrics%ci)) deallocate(this%metrics%ci) + if(allocated(this%metrics%one)) deallocate(this%metrics%one,this%metrics%zero) + if(allocated(this%metrics%s2)) deallocate(this%metrics%s2) + this%metrics%nss=0 + if(allocated(this%wavegen%ctab)) deallocate(this%wavegen%ctab) + if(allocated(this%wavegen%pulse)) deallocate(this%wavegen%pulse) + if(allocated(this%wavegen%dphi)) deallocate(this%wavegen%dphi,this%wavegen%scaled_pulse) + this%wavegen%first=.true. + this%wavegen%nsps=0 + if(associated(this%knowledge).and.this%owns_knowledge) deallocate(this%knowledge) + this%owns_knowledge=.false. + nullify(this%knowledge,this%callback,this%diagnostic,this%spectrum_sink) + if(allocated(this%sync1)) deallocate(this%sync1,this%sync2,this%synct1,this%synct2,this%sync_tweak) + if(allocated(this%spectrum)) deallocate(this%spectrum) + if(associated(this%dopss)) deallocate(this%dopss) + nullify(this%dopss) + call this%fec%destroy() + call this%reset() + end subroutine + + subroutine clear_fft_plans(this) + class(fst4_decoder), intent(inout) :: this + !$omp critical(fftw) + if(c_associated(this%big_plan)) call fftwf_destroy_plan(this%big_plan) + if(c_associated(this%baseband_plan)) call fftwf_destroy_plan(this%baseband_plan) + if(c_associated(this%dop_plan)) call fftwf_destroy_plan(this%dop_plan) + !$omp end critical(fftw) + this%big_plan=c_null_ptr + this%baseband_plan=c_null_ptr + this%dop_plan=c_null_ptr + this%dop_length=0 + this%fft_length=0 + this%down_length=0 + end subroutine + + subroutine ensure_fft_buffer(storage,buffer,length,status) + type(c_ptr), intent(inout) :: storage + complex(c_float_complex), pointer, contiguous, intent(inout) :: buffer(:) + integer, intent(in) :: length + integer, intent(out) :: status + complex(c_float_complex), pointer, contiguous :: one_based(:) + status=0 + if(associated(buffer)) then + if(size(buffer)>=length) return + call fftwf_free(storage) + storage=c_null_ptr + nullify(buffer) + endif + storage=fftwf_alloc_complex(int(length,c_size_t)) + if(.not.c_associated(storage)) then + status=-1 + return + endif + call c_f_pointer(storage,one_based,[length]) + buffer(0:length-1)=>one_based + end subroutine + + subroutine release_candidate_workspace(this) + class(fst4_decoder), intent(inout) :: this + if(allocated(this%candidate_s)) deallocate(this%candidate_s) + if(allocated(this%candidate_s2)) deallocate(this%candidate_s2) + if(allocated(this%candidate_base)) deallocate(this%candidate_base) + if(allocated(this%baseline_scratch)) deallocate(this%baseline_scratch) + end subroutine + + subroutine release_large_workspace(this) + class(fst4_decoder), intent(inout) :: this + ! Aligned replacement buffers can reuse the retained plans through new-array execution. + if(c_associated(this%big_storage)) call fftwf_free(this%big_storage) + if(c_associated(this%dop_storage)) call fftwf_free(this%dop_storage) + this%big_storage=c_null_ptr + this%dop_storage=c_null_ptr + nullify(this%big,this%dopgain) + if(associated(this%dopwave)) deallocate(this%dopwave) + nullify(this%dopwave) + call release_candidate_workspace(this) + end subroutine + + subroutine finalize(this) + type(fst4_decoder), intent(inout) :: this + call this%destroy() + end subroutine + + subroutine set_known_calls(this,calls,status) + class(fst4_decoder), intent(inout) :: this + character(len=*), intent(in) :: calls(:) + integer, intent(out) :: status + status=-1 + if(size(calls)>100) return + this%wcalls='' + this%nwcalls=size(calls) + this%wcalls(1:size(calls))=calls + status=0 + end subroutine + + subroutine get_known_calls(this,calls,count) + class(fst4_decoder), intent(in) :: this + character(len=*), intent(out) :: calls(:) + integer, intent(out) :: count + count=this%nwcalls + calls='' + calls(1:min(size(calls),count))=this%wcalls(1:min(size(calls),count)) + end subroutine + + subroutine decode_pcm(this,callback,samples,sample_count,options,status) + class(fst4_decoder), intent(inout) :: this + procedure(fst4_decode_callback) :: callback + integer(c_int16_t), intent(in) :: samples(:) + integer, intent(in) :: sample_count + type(fst4_options), intent(in) :: options + integer, intent(out) :: status + integer :: nfa,nfb,period,n + character(len=12) :: mycall,hiscall + status=-1 + period=options%period + n=period*12000 + ! The engine validates options and supplies a zero-padded full period. + if(sample_count<1.or.sample_count/=n.or.sample_count>size(samples)) return + call this%initialize() + if(options%fft_flags/=this%fft_flags) then + call clear_fft_plans(this) + this%fft_flags=options%fft_flags + endif + this%measure_doppler=options%measure_doppler + nfa=options%low_frequency + nfb=options%high_frequency + mycall=options%mycall + hiscall=options%hiscall + call decode_kernel(this,callback,samples,options%utc,options%qso_progress,nfa,nfb, & + options%receive_frequency,options%effort,period,options%blanker_percent,options%blanker_step, & + options%single_decode,options%tolerance, & + options%eme_delay,options%ap_cq_only,mycall,hiscall,merge(1,0,options%wspr),status) + if(period>=300) call release_large_workspace(this) + end subroutine + + subroutine decode_kernel(this,callback,iwave,nutc,nQSOProgress,nfa,nfb,nfqso, & + ndepth,ntrperiod,blanker_percent,blanker_step,single_decode,ntol,emedelay,lapcqonly,mycall, & + hiscall,iwspr,status) - use prog_args use timer_module, only: timer use packjt77 use, intrinsic :: iso_c_binding @@ -40,85 +270,67 @@ contains parameter (MAXCAND=100,MAXWCALLS=100) class(fst4_decoder), intent(inout) :: this procedure(fst4_decode_callback) :: callback + integer, intent(in) :: blanker_percent,blanker_step + logical, intent(in) :: single_decode character*37 decodes(100) + integer decoded_hashes(100),unresolved_hash character*37 msg,msgsent - character*20 wcalls(MAXWCALLS), wpart + character*20 wpart character*77 c77 character*12 mycall,hiscall - character*12 mycall0,hiscall0 - complex, allocatable :: c2(:) - complex, allocatable :: cframe(:) - complex, allocatable :: c_bigfft(:) !Complex waveform + complex(c_float_complex), pointer, contiguous :: c2(:),cframe(:),c_bigfft(:) real llr(240),llrs(240,4) real candidates0(200,5),candidates(200,5) real bitmetrics(320,4) real s4(0:3,NN) real minsync - logical lagain,lapcqonly + logical lapcqonly integer itone(NN) integer hmod integer*1 apmask(240),cw(240),hdec(240) integer*1 message101(101),message74(74),message77(77) - integer*1 rvec(77) - integer apbits(240) - integer nappasses(0:5) ! # of decoding passes for QSO states 0-5 - integer naptypes(0:5,4) ! (nQSOProgress,decoding pass) - integer mcq(29),mrrr(19),m73(19),mrr73(19) - - logical badsync,unpk77_success,single_decode - logical first,nohiscall - logical new_callsign,plotspec_exists,wcalls_exists,do_k50_decode + + logical badsync,unpk77_success + logical nohiscall + logical new_callsign,plotspec_exists,do_k50_decode logical decdata_exists - logical lprinthash22 + character(len=256) :: diagnostic_line - integer*2 iwave(30*60*12000) + integer*2 iwave(*) + integer status + real(c_float), pointer, contiguous :: fft_input(:) + type(fst4_result) :: result - data mcq/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0/ - data mrrr/0,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,1/ - data m73/0,1,1,1,1,1,1,0,1,0,0,1,0,1,0,0,0,0,1/ - data mrr73/0,1,1,1,1,1,1,0,0,1,1,1,0,1,0,1,0,0,1/ - data rvec/0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, & + integer, parameter :: rvec(77)=[0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, & 1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,1, & - 0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1/ - data first/.true./,hmod/1/,fcbest/0.0/ + 0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1] + integer, parameter :: mcq(29)= & + 2*mod([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]+rvec(1:29),2)-1 + integer, parameter :: mrrr(19)=2*mod([0,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,1]+rvec(59:77),2)-1 + integer, parameter :: m73(19)=2*mod([0,1,1,1,1,1,1,0,1,0,0,1,0,1,0,0,0,0,1]+rvec(59:77),2)-1 + integer, parameter :: mrr73(19)=2*mod([0,1,1,1,1,1,1,0,0,1,1,1,0,1,0,1,0,0,1]+rvec(59:77),2)-1 + data hmod/1/ + - save first,apbits,nappasses,naptypes,mycall0,hiscall0 - save wcalls,nwcalls + status=0 this%callback => callback - dxcall13=hiscall ! initialize for use in packjt77 - mycall13=mycall + this%knowledge%dxcall13=hiscall + this%knowledge%mycall13=mycall if(iwspr.ne.0 .and. iwspr.ne.1) return - if(lagain) continue ! use lagain to keep compiler happy - - if(first) then -! read the fst4_calls.txt file - inquire(file=trim(data_dir)//'/fst4w_calls.txt',exist=wcalls_exists) - if( wcalls_exists ) then - open(42,file=trim(data_dir)//'/fst4w_calls.txt',status='unknown') - do i=1,MAXWCALLS - wcalls(i)='' - read(42,fmt='(a)',end=2867) wcalls(i) - wcalls(i)=adjustl(wcalls(i)) - if(len(trim(wcalls(i))).eq.0) exit - enddo -2867 nwcalls=i-1 - close(42) - endif - - mcq=2*mod(mcq+rvec(1:29),2)-1 - mrrr=2*mod(mrrr+rvec(59:77),2)-1 - m73=2*mod(m73+rvec(59:77),2)-1 - mrr73=2*mod(mrr73+rvec(59:77),2)-1 + if(this%first) then + this%apbits=0 + this%apbits(1)=99 + this%apbits(30)=99 - nappasses(0)=2 - nappasses(1)=2 - nappasses(2)=2 - nappasses(3)=2 - nappasses(4)=2 - nappasses(5)=3 + this%nappasses(0)=2 + this%nappasses(1)=2 + this%nappasses(2)=2 + this%nappasses(3)=2 + this%nappasses(4)=2 + this%nappasses(5)=3 ! iaptype !------------------------ @@ -130,49 +342,49 @@ contains ! 6 MyCall DxCall RR73 (77 ap bits) !******** - naptypes(0,1:4)=(/1,2,0,0/) ! Tx6 selected (CQ) - naptypes(1,1:4)=(/2,3,0,0/) ! Tx1 - naptypes(2,1:4)=(/2,3,0,0/) ! Tx2 - naptypes(3,1:4)=(/3,6,0,0/) ! Tx3 - naptypes(4,1:4)=(/3,6,0,0/) ! Tx4 - naptypes(5,1:4)=(/3,1,2,0/) ! Tx5 + this%naptypes(0,1:4)=(/1,2,0,0/) ! Tx6 selected (CQ) + this%naptypes(1,1:4)=(/2,3,0,0/) ! Tx1 + this%naptypes(2,1:4)=(/2,3,0,0/) ! Tx2 + this%naptypes(3,1:4)=(/3,6,0,0/) ! Tx3 + this%naptypes(4,1:4)=(/3,6,0,0/) ! Tx4 + this%naptypes(5,1:4)=(/3,1,2,0/) ! Tx5 - mycall0='' - hiscall0='' - first=.false. + this%mycall0='' + this%hiscall0='' + this%first=.false. endif l1=index(mycall,char(0)) if(l1.ne.0) mycall(l1:)=" " l1=index(hiscall,char(0)) if(l1.ne.0) hiscall(l1:)=" " - if(mycall.ne.mycall0 .or. hiscall.ne.hiscall0) then - apbits=0 - apbits(1)=99 - apbits(30)=99 + if(mycall.ne.this%mycall0 .or. hiscall.ne.this%hiscall0) then + this%apbits=0 + this%apbits(1)=99 + this%apbits(30)=99 if(len(trim(mycall)) .lt. 3) go to 10 nohiscall=.false. - hiscall0=hiscall - if(len(trim(hiscall0)).lt.3) then - hiscall0=mycall ! use mycall for dummy hiscall - mycall won't be hashed. + this%hiscall0=hiscall + if(len(trim(this%hiscall0)).lt.3) then + this%hiscall0=mycall ! use mycall for dummy hiscall - mycall won't be hashed. nohiscall=.true. endif - msg=trim(mycall)//' '//trim(hiscall0)//' RR73' + msg=trim(mycall)//' '//trim(this%hiscall0)//' RR73' i3=-1 n3=-1 - call pack77(msg,i3,n3,c77) - call unpack77(c77,1,msgsent,unpk77_success) + call pack77_for_state(this%knowledge,msg,i3,n3,c77) + call unpack77_for_state(this%knowledge,c77,1,msgsent,unpk77_success) if(i3.ne.1 .or. (msg.ne.msgsent) .or. .not.unpk77_success) go to 10 read(c77,'(77i1)') message77 message77=mod(message77+rvec,2) - apbits(1:77)=2*message77-1 - if(nohiscall) apbits(30)=99 + this%apbits(1:77)=2*message77-1 + if(nohiscall) this%apbits(30)=99 10 continue - mycall0=mycall - hiscall0=hiscall + this%mycall0=mycall + this%hiscall0=hiscall endif !************************************ @@ -228,9 +440,47 @@ contains nfft1=nfft2*ndown nh1=nfft1/2 - allocate( c_bigfft(0:nfft1/2) ) - allocate( c2(0:nfft2-1) ) - allocate( cframe(0:160*nss-1) ) + call ensure_fft_buffer(this%big_storage,this%big,nfft1/2+1,status) + if(status/=0) return + call c_f_pointer(this%big_storage,fft_input,[nfft1+2]) + if(this%fft_length/=nfft1.or..not.c_associated(this%big_plan)) then + !$omp critical(fftw) + if(c_associated(this%big_plan)) call fftwf_destroy_plan(this%big_plan) + this%big_plan=fftwf_plan_dft_r2c_1d(nfft1,fft_input,this%big,this%fft_flags) + !$omp end critical(fftw) + this%fft_length=nfft1 + endif + if(this%down_length/=nfft2.or..not.c_associated(this%baseband_plan)) then + !$omp critical(fftw) + if(c_associated(this%baseband_plan)) call fftwf_destroy_plan(this%baseband_plan) + !$omp end critical(fftw) + this%baseband_plan=c_null_ptr + if(associated(this%baseband)) then + if(size(this%baseband)<nfft2) then + deallocate(this%baseband) + nullify(this%baseband) + endif + endif + if(.not.associated(this%baseband)) allocate(this%baseband(0:nfft2-1)) + !$omp critical(fftw) + this%baseband_plan=fftwf_plan_dft_1d(nfft2,this%baseband,this%baseband,FFTW_BACKWARD,this%fft_flags) + !$omp end critical(fftw) + this%down_length=nfft2 + endif + if(.not.c_associated(this%big_plan).or..not.c_associated(this%baseband_plan)) then + status=-1 + return + endif + if(associated(this%frame)) then + if(size(this%frame)<160*nss) then + deallocate(this%frame) + nullify(this%frame) + endif + endif + if(.not.associated(this%frame)) allocate(this%frame(0:160*nss-1)) + c_bigfft(0:)=>this%big(0:nfft1/2) + c2(0:)=>this%baseband(0:nfft2-1) + cframe(0:)=>this%frame(0:160*nss-1) jittermax=2 do_k50_decode=.false. @@ -250,20 +500,12 @@ contains ! Noise blanker setup ndropmax=1 - single_decode=iand(nexp_decode,32).ne.0 - npct=0 - nb=nexp_decode/256 - 3 - if(nb.ge.0) npct=nb - inb1=20 - inb2=5 - if(nb.eq.-1) then - inb2=5 !Try NB = 0, 5, 10, 15, 20% - else if(nb.eq.-2) then - inb2=2 !Try NB = 0, 2, 4,... 20% - else if(nb.eq.-3) then - inb2=1 !Try NB = 0, 1, 2,... 20% - else - inb1=0 !Fixed NB value, 0 to 25% + npct=blanker_percent + inb1=0 + inb2=1 + if(blanker_step>0) then + inb1=20 + inb2=blanker_step endif @@ -295,27 +537,29 @@ contains ndecodes=0 decodes=' ' + decoded_hashes=-1 new_callsign=.false. + if(.not.allocated(this%blanker_hist)) allocate(this%blanker_hist(0:32768)) do inb=0,inb1,inb2 - if(nb.lt.0) npct=inb ! we are looping over blanker settings - call blanker(iwave,nfft1,ndropmax,npct,c_bigfft) + if(blanker_step>0) npct=inb + call blanker(iwave,nfft1,ndropmax,npct,c_bigfft,this%blanker_hist) ! The big fft is done once and is used for calculating the smoothed spectrum ! and also for downconverting/downsampling each candidate. - call four2a(c_bigfft,nfft1,1,-1,0) !r2c + call fftwf_execute_dft_r2c(this%big_plan,fft_input,this%big) nhicoh=1 nsyncoh=8 minsync=1.20 if(ntrperiod.eq.15) minsync=1.15 -! Get first approximation of candidate frequencies - call get_candidates_fst4(c_bigfft,nfft1,nsps,hmod,fs,fa,fb,nfa,nfb, & - minsync,ncand,candidates0) + call get_candidates_fst4(this,c_bigfft,nfft1,nsps,hmod,fs,fa,fb,nfa,nfb, & + minsync,ncand,candidates0,status) + if(status/=0) return isbest=0 fc2=0. do icand=1,ncand fc0=candidates0(icand,1) - if(iwspr.eq.0 .and. nb.lt.0 .and. npct.ne.0 .and. & + if(iwspr.eq.0 .and. blanker_step>0 .and. npct.ne.0 .and. & abs(fc0-(nfqso+1.5*baud)).gt.ntol) cycle ! blanker loop only near nfqso detmet=candidates0(icand,2) @@ -324,13 +568,17 @@ contains ! Output array c2 is complex baseband sampled at 12000/ndown Sa/sec. ! The size of the downsampled c2 array is nfft2=nfft1/ndown call timer('dwnsmpl ',0) - call fst4_downsample(c_bigfft,nfft1,ndown,fc0,sigbw,c2) + call fst4_downsample(this,c_bigfft,nfft1,ndown,fc0,sigbw,c2) call timer('dwnsmpl ',1) call timer('sync240 ',0) - call fst4_sync_search(c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh, & + call fst4_sync_search(this,c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh, & emedelay,sbest,fcbest,isbest) call timer('sync240 ',1) + if(isbest<0) then + candidates0(icand,3)=-1 + cycle + endif fc_synced = fc0 + fcbest dt_synced = (isbest-fs2)*dt2 !nominal dt is 1 second so frame starts at sample fs2 @@ -392,7 +640,7 @@ contains xdt=(isbest-nspsec)/fs2 if(ntrperiod.eq.15) xdt=(isbest-real(nspsec)/2.0)/fs2 call timer('dwnsmpl ',0) - call fst4_downsample(c_bigfft,nfft1,ndown,fc_synced,sigbw,c2) + call fst4_downsample(this,c_bigfft,nfft1,ndown,fc_synced,sigbw,c2) call timer('dwnsmpl ',1) do ijitter=0,jittermax @@ -405,7 +653,7 @@ contains cframe=c2(is0:iend) bitmetrics=0 call timer('bitmetrc',0) - call get_fst4_bitmetrics(cframe,nss,bitmetrics, & + call get_fst4_bitmetrics_owned(this%metrics,cframe,nss,bitmetrics, & s4,nsync_qual,badsync) call timer('bitmetrc',1) if(badsync) cycle @@ -418,7 +666,7 @@ contains enddo apmag=maxval(abs(llrs(:,4)))*1.1 - ntmax=nblock+nappasses(nQSOProgress) + ntmax=nblock+this%nappasses(nQSOProgress) if(lapcqonly) ntmax=nblock+1 if(ndepth.eq.1) ntmax=nblock ! no ap for ndepth=1 apmask=0 @@ -440,10 +688,10 @@ contains if(itry.gt.nblock .and. iwspr.eq.0) then ! do ap passes llr=llrs(:,nblock) ! Use largest blocksize as the basis for AP passes - iaptype=naptypes(nQSOProgress,itry-nblock) + iaptype=this%naptypes(nQSOProgress,itry-nblock) if(lapcqonly) iaptype=1 - if(iaptype.ge.2 .and. apbits(1).gt.1) cycle ! No, or nonstandard, mycall - if(iaptype.ge.3 .and. apbits(30).gt.1) cycle ! No, or nonstandard, dxcall + if(iaptype.ge.2 .and. this%apbits(1).gt.1) cycle ! No, or nonstandard, mycall + if(iaptype.ge.3 .and. this%apbits(30).gt.1) cycle ! No, or nonstandard, dxcall if(iaptype.eq.1) then ! CQ apmask=0 apmask(1:29)=1 @@ -453,19 +701,19 @@ contains if(iaptype.eq.2) then ! MyCall ??? ??? apmask=0 apmask(1:29)=1 - llr(1:29)=apmag*apbits(1:29) + llr(1:29)=apmag*this%apbits(1:29) endif if(iaptype.eq.3) then ! MyCall DxCall ??? apmask=0 apmask(1:58)=1 - llr(1:58)=apmag*apbits(1:58) + llr(1:58)=apmag*this%apbits(1:58) endif if(iaptype.eq.4 .or. iaptype.eq.5 .or. iaptype .eq.6) then apmask=0 apmask(1:77)=1 - llr(1:58)=apmag*apbits(1:58) + llr(1:58)=apmag*this%apbits(1:58) if(iaptype.eq.4) llr(59:77)=apmag*mrrr(1:19) if(iaptype.eq.5) llr(59:77)=apmag*m73(1:19) if(iaptype.eq.6) llr(59:77)=apmag*mrr73(1:19) @@ -480,7 +728,7 @@ contains Keff=91 norder=3 call timer('d240_101',0) - call decode240_101(llr,Keff,maxosd,norder,apmask,message101, & + call decode240_101_owned(this%fec,llr,Keff,maxosd,norder,apmask,message101, & cw,ntype,nharderrors,dmin) call timer('d240_101',1) if(count(cw.eq.1).eq.0) then @@ -488,14 +736,14 @@ contains cycle endif write(c77,'(77i1)') mod(message101(1:77)+rvec,2) - call unpack77(c77,1,msg,unpk77_success) + call unpack77_for_state(this%knowledge,c77,1,msg,unpk77_success) elseif(iwspr.eq.1) then ! Try decoding with Keff=66 maxosd=2 call timer('d240_74 ',0) Keff=66 norder=3 - call decode240_74(llr,Keff,maxosd,norder,apmask,message74,cw, & + call decode240_74_owned(this%fec,llr,Keff,maxosd,norder,apmask,message74,cw, & ntype,nharderrors,dmin) call timer('d240_74 ',1) if(nharderrors.lt.0) goto 3465 @@ -505,14 +753,7 @@ contains endif write(c77,'(50i1)') message74(1:50) c77(51:77)='000000000000000000000110000' - call unpack77(c77,1,msg,unpk77_success) - if(lprinthash22 .and. unpk77_success .and. index(msg,'<...>').gt.0) then - read(c77,'(b22.22)') n22tmp - i1=index(msg,' ') - wpart=trim(msg(i1+1:)) - write(msg,'(a1,i7.7,a1)') '<',n22tmp,'>' - msg=trim(msg)//' '//trim(wpart) - endif + call unpack77_for_state(this%knowledge,c77,1,msg,unpk77_success) if(unpk77_success .and. do_k50_decode) then ! If decode was obtained with Keff=66, save call/grid in fst4w_calls.txt if not there already. i1=index(msg,' ') @@ -521,18 +762,18 @@ contains ! Only save callsigns/grids from type 1 messages if(index(wpart,'/').eq.0 .and. index(wpart,'<').eq.0) then ifound=0 - do i=1,nwcalls - if(index(wcalls(i),wpart).ne.0) ifound=1 + do i=1,this%nwcalls + if(index(this%wcalls(i),wpart).ne.0) ifound=1 enddo if(ifound.eq.0) then ! This is a new callsign new_callsign=.true. - if(nwcalls.lt.MAXWCALLS) then - nwcalls=nwcalls+1 - wcalls(nwcalls)=wpart + if(this%nwcalls.lt.MAXWCALLS) then + this%nwcalls=this%nwcalls+1 + this%wcalls(this%nwcalls)=wpart else - wcalls(1:nwcalls-1)=wcalls(2:nwcalls) - wcalls(nwcalls)=wpart + this%wcalls(1:this%nwcalls-1)=this%wcalls(2:this%nwcalls) + this%wcalls(this%nwcalls)=wpart endif endif endif @@ -546,7 +787,7 @@ contains call timer('d240_74 ',0) Keff=50 norder=4 - call decode240_74(llr,Keff,maxosd,norder,apmask,message74,cw, & + call decode240_74_owned(this%fec,llr,Keff,maxosd,norder,apmask,message74,cw, & ntype,nharderrors,dmin) call timer('d240_74 ',1) if(count(cw.eq.1).eq.0) then @@ -555,12 +796,12 @@ contains endif write(c77,'(50i1)') message74(1:50) c77(51:77)='000000000000000000000110000' - call unpack77(c77,1,msg,unpk77_success) + call unpack77_for_state(this%knowledge,c77,1,msg,unpk77_success) ! No CRC in this mode, so only accept the decode if call/grid have been seen before if(unpk77_success) then unpk77_success=.false. - do i=1,nwcalls - if(index(msg,trim(wcalls(i))).gt.0) then + do i=1,this%nwcalls + if(len_trim(this%wcalls(i))>0.and.index(msg,trim(this%wcalls(i))).gt.0) then unpk77_success=.true. endif enddo @@ -570,25 +811,31 @@ contains endif if(nharderrors .ge.0 .and. unpk77_success) then + unresolved_hash=-1 + if(iwspr==1.and.index(msg,'<...>')>0) read(c77,'(b22.22)') unresolved_hash idupe=0 do i=1,ndecodes - if(decodes(i).eq.msg) idupe=1 + if(decodes(i)==msg.and.decoded_hashes(i)==unresolved_hash) idupe=1 enddo if(idupe.eq.1) goto 800 ndecodes=ndecodes+1 decodes(ndecodes)=msg + decoded_hashes(ndecodes)=unresolved_hash if(iwspr.eq.0) then call get_fst4_tones_from_bits(message101,itone,0) else call get_fst4_tones_from_bits(message74,itone,1) endif - inquire(file='plotspec',exist=plotspec_exists) + plotspec_exists=this%measure_doppler + fmid=-999.0 + w50=0.0 call timer('dopsprd ',0) if(plotspec_exists) then - call dopspread(itone,iwave,nsps,nmax,ndown,hmod, & - isbest,fc_synced,fmid,w50) + call dopspread(this,itone,iwave,nsps,nmax,ndown,hmod, & + isbest,fc_synced,fmid,w50,status) + if(status/=0) return endif call timer('dopsprd ',1) xsig=0 @@ -623,21 +870,33 @@ contains nsnr=nint(xsnr) qual=0.0 fsig=fc_synced - 1.5*baud - inquire(file=trim(data_dir)//'/decdata',exist=decdata_exists) + decdata_exists=associated(this%diagnostic) if(decdata_exists) then hdec=0 where(llrs(:,1).ge.0.0) hdec=1 nhp=count(hdec.ne.cw) ! # hard errors wrt N=1 soft symbols hd=sum(ieor(hdec,cw)*abs(llrs(:,1))) ! weighted distance wrt N=1 symbols - open(21,file=trim(data_dir)//'/fst4_decodes.dat',status='unknown',position='append') - write(21,3021) nutc,icand,itry,nsyncoh,iaptype, & + write(diagnostic_line,3021) nutc,icand,itry,nsyncoh,iaptype, & ijitter,npct,ntype,Keff,nsync_qual,nharderrors,dmin,nhp,hd, & sync,xsnr,xdt,fsig,w50,trim(msg) 3021 format(i6.6,i4,6i3,3i4,f6.1,i4,f6.1,f9.2,f6.1,f6.2,f7.1,f7.3,1x,a) - close(21) + call this%diagnostic(trim(diagnostic_line)) endif - call this%callback(nutc,smax1,nsnr,xdt,fsig,msg, & - iaptype,qual,ntrperiod,fmid,w50) + result=fst4_result() + result%period_seconds=ntrperiod + result%effective_bits=Keff + result%blanker_percent=npct + if(unresolved_hash>=0) then + result%has_hash22=1 + result%hash22=unresolved_hash + endif + result%has_doppler=merge(1,0,plotspec_exists) + if(plotspec_exists) then + result%fmid_hz=fmid + result%width_hz=w50 + endif + call this%callback(nutc,sync,nsnr,xdt,fsig,msg, & + iaptype,qual,ntrperiod,fmid,w50,result) goto 800 endif enddo ! metrics @@ -645,42 +904,39 @@ contains 800 enddo !candidate list enddo ! noise blanker loop - if(new_callsign .and. do_k50_decode) then ! re-write the fst4w_calls.txt file - open(42,file=trim(data_dir)//'/fst4w_calls.txt',status='unknown') - do i=1,nwcalls - write(42,'(a20)') trim(wcalls(i)) - enddo - close(42) - endif + if(new_callsign) this%history_dirty=.true. return - end subroutine decode + end subroutine decode_kernel - subroutine sync_fst4(cd0,i0,f0,hmod,ncoh,np,nss,ntr,fs,sync) + subroutine sync_fst4(this,cd0,i0,f0,hmod,ncoh,np,nss,ntr,fs,sync) ! Compute sync power for a complex, downsampled FST4 signal. use timer_module, only: timer include 'fst4/fst4_params.f90' + class(fst4_decoder), intent(inout) :: this complex cd0(0:np-1) - complex csync1,csync2,csynct1,csynct2 - complex ctwk(3200) + complex z1,z2,z3,z4,z5 integer hmod,isyncword1(0:7),isyncword2(0:7) - real f0save - common/sync240com/csync1(3200),csync2(3200),csynct1(3200),csynct2(3200) + + data isyncword1/0,1,3,2,1,0,2,3/ data isyncword2/2,3,1,0,3,2,0,1/ - data f0save/-99.9/,nss0/-1/,ntr0/-1/ - save twopi,dt,fac,f0save,nss0,ntr0 - p(z1)=(real(z1*fac)**2 + aimag(z1*fac)**2)**0.5 !Compute power + + p(z1)=(real(z1*this%sync_fac)**2 + aimag(z1*this%sync_fac)**2)**0.5 !Compute power + + if(.not.allocated(this%sync1)) allocate(this%sync1(3200),this%sync2(3200), & + this%synct1(3200),this%synct2(3200),this%sync_tweak(3200)) + twopi=8.0*atan(1.0) nz=8*nss call timer('sync240a',0) - if(nss.ne.nss0 .or. ntr.ne.ntr0) then + if(nss.ne.this%sync_nss .or. ntr.ne.this%sync_period) then twopi=8.0*atan(1.0) - dt=1/fs + this%sync_dt=1/fs k=1 phi1=0.0 phi2=0.0 @@ -688,30 +944,30 @@ contains dphi1=twopi*hmod*(isyncword1(i)-1.5)/real(nss) dphi2=twopi*hmod*(isyncword2(i)-1.5)/real(nss) do j=1,nss - csync1(k)=cmplx(cos(phi1),sin(phi1)) - csync2(k)=cmplx(cos(phi2),sin(phi2)) + this%sync1(k)=cmplx(cos(phi1),sin(phi1)) + this%sync2(k)=cmplx(cos(phi2),sin(phi2)) phi1=mod(phi1+dphi1,twopi) phi2=mod(phi2+dphi2,twopi) k=k+1 enddo enddo - fac=1.0/(8.0*nss) - nss0=nss - ntr0=ntr - f0save=-1.e30 + this%sync_fac=1.0/(8.0*nss) + this%sync_nss=nss + this%sync_period=ntr + this%sync_frequency=-1.e30 endif - if(f0.ne.f0save) then - dphi=twopi*f0*dt + if(f0.ne.this%sync_frequency) then + dphi=twopi*f0*this%sync_dt phi=0.0 do i=1,nz - ctwk(i)=cmplx(cos(phi),sin(phi)) + this%sync_tweak(i)=cmplx(cos(phi),sin(phi)) phi=mod(phi+dphi,twopi) enddo - csynct1(1:nz)=ctwk(1:nz)*csync1(1:nz) - csynct2(1:nz)=ctwk(1:nz)*csync2(1:nz) - f0save=f0 - nss0=nss + this%synct1(1:nz)=this%sync_tweak(1:nz)*this%sync1(1:nz) + this%synct2(1:nz)=this%sync_tweak(1:nz)*this%sync2(1:nz) + this%sync_frequency=f0 + this%sync_nss=nss endif call timer('sync240a',1) @@ -733,14 +989,14 @@ contains is=(i-1)*ncoh*nss z1=0 if(i1+is.ge.1) then - z1=sum(cd0(i1+is:i1+is+ncoh*nss-1)*conjg(csynct1(is+1:is+ncoh*nss))) + z1=sum(cd0(i1+is:i1+is+ncoh*nss-1)*conjg(this%synct1(is+1:is+ncoh*nss))) endif - z2=sum(cd0(i2+is:i2+is+ncoh*nss-1)*conjg(csynct2(is+1:is+ncoh*nss))) - z3=sum(cd0(i3+is:i3+is+ncoh*nss-1)*conjg(csynct1(is+1:is+ncoh*nss))) - z4=sum(cd0(i4+is:i4+is+ncoh*nss-1)*conjg(csynct2(is+1:is+ncoh*nss))) + z2=sum(cd0(i2+is:i2+is+ncoh*nss-1)*conjg(this%synct2(is+1:is+ncoh*nss))) + z3=sum(cd0(i3+is:i3+is+ncoh*nss-1)*conjg(this%synct1(is+1:is+ncoh*nss))) + z4=sum(cd0(i4+is:i4+is+ncoh*nss-1)*conjg(this%synct2(is+1:is+ncoh*nss))) z5=0 - if(i5+is+ncoh*nss-1.le.np) then - z5=sum(cd0(i5+is:i5+is+ncoh*nss-1)*conjg(csynct1(is+1:is+ncoh*nss))) + if(i5+is+ncoh*nss-1.lt.np) then + z5=sum(cd0(i5+is:i5+is+ncoh*nss-1)*conjg(this%synct1(is+1:is+ncoh*nss))) endif s1=s1+abs(z1)/nz s2=s2+abs(z2)/nz @@ -756,14 +1012,14 @@ contains is=(i-1)*nss+(isub-1)*nps z1=0.0 if(i1+is.ge.1) then - z1=sum(cd0(i1+is:i1+is+nps-1)*conjg(csynct1(is+1:is+nps))) + z1=sum(cd0(i1+is:i1+is+nps-1)*conjg(this%synct1(is+1:is+nps))) endif - z2=sum(cd0(i2+is:i2+is+nps-1)*conjg(csynct2(is+1:is+nps))) - z3=sum(cd0(i3+is:i3+is+nps-1)*conjg(csynct1(is+1:is+nps))) - z4=sum(cd0(i4+is:i4+is+nps-1)*conjg(csynct2(is+1:is+nps))) + z2=sum(cd0(i2+is:i2+is+nps-1)*conjg(this%synct2(is+1:is+nps))) + z3=sum(cd0(i3+is:i3+is+nps-1)*conjg(this%synct1(is+1:is+nps))) + z4=sum(cd0(i4+is:i4+is+nps-1)*conjg(this%synct2(is+1:is+nps))) z5=0.0 - if(i5+is+ncoh*nss-1.le.np) then - z5=sum(cd0(i5+is:i5+is+nps-1)*conjg(csynct1(is+1:is+nps))) + if(i5+is+ncoh*nss-1.lt.np) then + z5=sum(cd0(i5+is:i5+is+nps-1)*conjg(this%synct1(is+1:is+nps))) endif s1=s1+abs(z1)/(8*nss) s2=s2+abs(z2)/(8*nss) @@ -777,10 +1033,11 @@ contains return end subroutine sync_fst4 - subroutine fst4_downsample(c_bigfft,nfft1,ndown,f0,sigbw,c1) + subroutine fst4_downsample(this,c_bigfft,nfft1,ndown,f0,sigbw,c1) ! Output: Complex data in c(), sampled at 12000/ndown Hz + class(fst4_decoder), intent(inout) :: this complex c_bigfft(0:nfft1/2) complex c1(0:nfft1/ndown-1) @@ -796,25 +1053,28 @@ contains if(i0-i.ge.0) c1(nfft2-i)=c_bigfft(i0-i) enddo c1=c1/nfft2 - call four2a(c1,nfft2,1,1,1) !c2c FFT back to time domain + call fftwf_execute_dft(this%baseband_plan,c1,c1) return end subroutine fst4_downsample - subroutine get_candidates_fst4(c_bigfft,nfft1,nsps,hmod,fs,fa,fb,nfa,nfb, & - minsync,ncand,candidates) + subroutine get_candidates_fst4(this,c_bigfft,nfft1,nsps,hmod,fs,fa,fb,nfa,nfb, & + minsync,ncand,candidates,status) + class(fst4_decoder), intent(inout) :: this complex c_bigfft(0:nfft1/2) !Full length FFT of raw data integer hmod !Modulation index (submode) integer im(1) !For maxloc real candidates(200,5) !Candidate list - real, allocatable :: s(:) !Low resolution power spectrum - real, allocatable :: s2(:) !CCF of s() with 4 tones - real, allocatable :: sbase(:) !noise baseline estimate real xdb(-3:3) !Model 4-tone CCF peaks real minsync + integer, intent(out) :: status + integer allocation_status data xdb/0.25,0.50,0.75,1.0,0.75,0.50,0.25/ + status=0 + ncand=0 + candidates=0 nh1=nfft1/2 df1=fs/nfft1 baud=fs/nsps !Keying rate @@ -827,9 +1087,22 @@ contains inb=nint(min(4800.0,real(nfb))/df2) !High freq limit for noise fit if(ia.lt.ina) ia=ina if(ib.gt.inb) ib=inb + if(ib<ia.or.inb-ina<8) return nnw=nint(48000.*nsps*2./fs) - allocate (s(nnw)) + if(allocated(this%candidate_s)) then + if(size(this%candidate_s)<nnw) call release_candidate_workspace(this) + endif + if(.not.allocated(this%candidate_s)) then + allocate(this%candidate_s(nnw),this%candidate_s2(nnw),this%candidate_base(nnw), & + this%baseline_scratch(nnw),stat=allocation_status) + if(allocation_status/=0) then + call release_candidate_workspace(this) + status=-1 + return + endif + endif + associate(s=>this%candidate_s(1:nnw),s2=>this%candidate_s2(1:nnw),sbase=>this%candidate_base(1:nnw)) s=0. !Compute low-resolution power spectrum do i=ina,inb ! noise analysis window includes signal analysis window j0=nint(i*df2/df1) @@ -840,14 +1113,12 @@ contains ina=max(ina,1+3*hmod) !Don't run off the ends inb=min(inb,nnw-3*hmod) - allocate (s2(nnw)) - allocate (sbase(nnw)) s2=0. do i=ina,inb !Compute CCF of s() and 4 tones s2(i)=s(i-hmod*3) + s(i-hmod) +s(i+hmod) +s(i+hmod*3) enddo npctile=30 - call fst4_baseline(s2,nnw,ina+hmod*3,inb-hmod*3,npctile,sbase) + call fst4_baseline_owned(s2,nnw,ina+hmod*3,inb-hmod*3,npctile,sbase,this%baseline_scratch(1:nnw)) if(any(sbase(ina:inb).le.0.0)) return s2(ina:inb)=s2(ina:inb)/sbase(ina:inb) !Normalize wrt noise level @@ -875,14 +1146,20 @@ contains candidates(ncand,2)=pval !Rough estimate of SNR candidates(ncand,5)=sbase(iploc) enddo + end associate return end subroutine get_candidates_fst4 - subroutine fst4_sync_search(c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh, & + subroutine fst4_sync_search(this,c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh, & emedelay,sbest,fcbest,isbest) + class(fst4_decoder), intent(inout) :: this complex c2(0:nfft2-1) integer hmod + isbest=-1 + fcbest=0. + sbest=0. + last_start=nfft2-160*nss nspsec=int(fs2) baud=fs2/real(nss) fc1=0.0 @@ -894,11 +1171,12 @@ contains ishw=1.5*nspsec endif + if(min(is0+ishw,last_start)<max(1,is0-ishw)) return sbest=-1.e30 do if=-12,12 fc=fc1 + 0.1*baud*if - do istart=max(1,is0-ishw),is0+ishw,4*hmod - call sync_fst4(c2,istart,fc,hmod,nsyncoh,nfft2,nss, & + do istart=max(1,is0-ishw),min(is0+ishw,last_start),4*hmod + call sync_fst4(this,c2,istart,fc,hmod,nsyncoh,nfft2,nss, & ntrperiod,fs2,sync) if(sync.gt.sbest) then fcbest=fc @@ -916,8 +1194,8 @@ contains sbest=0.0 do if=-7,7 fc=fc1 + 0.02*baud*if - do istart=max(1,is0-ishw),is0+ishw,isst - call sync_fst4(c2,istart,fc,hmod,nsyncoh,nfft2,nss, & + do istart=max(1,is0-ishw),min(is0+ishw,last_start),isst + call sync_fst4(this,c2,istart,fc,hmod,nsyncoh,nfft2,nss, & ntrperiod,fs2,sync) if(sync.gt.sbest) then fcbest=fc @@ -928,33 +1206,63 @@ contains enddo end subroutine fst4_sync_search - subroutine dopspread(itone,iwave,nsps,nmax,ndown,hmod,i0,fc,fmid,w50) + subroutine dopspread(this,itone,iwave,nsps,nmax,ndown,hmod,i0,fc,fmid,w50,status) ! On "plotspec" special request, compute Doppler spread for a decoded signal include 'fst4/fst4_params.f90' - complex, allocatable :: cwave(:) !Reconstructed complex signal - complex, allocatable :: g(:) !Channel gain, g(t) in QEX paper - real,allocatable :: ss(:) !Computed power spectrum of g(t) + class(fst4_decoder), intent(inout) :: this + complex, pointer :: cwave(:) !Reconstructed complex signal + complex(c_float_complex), pointer, contiguous :: g(:) + real, pointer :: ss(:) !Computed power spectrum of g(t) + real unused_wave(1) integer itone(160) !Tones for this message integer*2 iwave(nmax) !Raw Rx data integer hmod !Modulation index - data ncall/0/ - save ncall - - ncall=ncall+1 + integer, intent(out) :: status + integer allocation_status + fmid=-999. + w50=0. nfft=2*nmax nwave=max(nmax,(NN+2)*nsps) - allocate(cwave(0:nwave-1)) - allocate(g(0:nfft-1)) - wave=0 + call ensure_fft_buffer(this%dop_storage,this%dopgain,nfft,status) + if(status/=0) return + if(this%dop_length/=nfft.or..not.c_associated(this%dop_plan)) then + !$omp critical(fftw) + if(c_associated(this%dop_plan)) call fftwf_destroy_plan(this%dop_plan) + this%dop_plan=fftwf_plan_dft_1d(nfft,this%dopgain,this%dopgain,FFTW_FORWARD,this%fft_flags) + !$omp end critical(fftw) + this%dop_length=nfft + endif + if(.not.c_associated(this%dop_plan)) then + status=-1 + return + endif + if(associated(this%dopwave)) then + if(size(this%dopwave)<nwave) then + deallocate(this%dopwave) + nullify(this%dopwave) + endif + endif + if(.not.associated(this%dopwave)) then + allocate(this%dopwave(0:nwave-1),stat=allocation_status) + if(allocation_status/=0) then + status=-1 + return + endif + endif + cwave(0:)=>this%dopwave(0:nwave-1) + g(0:)=>this%dopgain(0:nfft-1) + unused_wave=0 fsample=12000.0 - call gen_fst4wave(itone,NN,nsps,nwave,fsample,hmod,fc,1,cwave,wave) - cwave=cshift(cwave,-i0*ndown) + call gen_fst4wave_owned(this%wavegen,itone,NN,nsps,nwave,fsample,hmod,fc,1,cwave,unused_wave) fac=1.0/32768 - g(0:nmax-1)=fac*float(iwave)*conjg(cwave(:nmax-1)) + do i=0,nmax-1 + j=modulo(i-i0*ndown,nwave) + g(i)=fac*real(iwave(i+1))*conjg(cwave(j)) + enddo g(nmax:)=0. - call four2a(g,nfft,1,-1,1) !Forward c2c FFT + call fftwf_execute_dft(this%dop_plan,g,g) df=12000.0/nfft ia=1.0/df @@ -967,7 +1275,14 @@ contains enddo ia=10.1/df - allocate(ss(-ia:ia)) !Allocate space for +/- 10 Hz + if(associated(this%dopss)) then + if(size(this%dopss)<2*ia+1) then + deallocate(this%dopss) + nullify(this%dopss) + endif + endif + if(.not.associated(this%dopss)) allocate(this%dopss(2*ia+1)) + ss(-ia:)=>this%dopss(1:2*ia+1) sum1=0. sum2=0. nns=0 @@ -1015,13 +1330,20 @@ contains w50=xdiff*df !Compute Doppler spread fmid=xi2*df !Frequency midpoint of signal powere - do i=-ia,ia !Save the spectrum for plotting - y=ncall-1 - j=i+nint(xi2) - if(abs(j*df).lt.10.0) y=0.99*ss(i+nint(xi2)) + ncall-1 - write(52,1010) i*df,y -1010 format(f12.6,f12.6) - enddo + if(associated(this%spectrum_sink)) then + nspectrum=2*ia+1 + if(allocated(this%spectrum)) then + if(size(this%spectrum)<nspectrum) deallocate(this%spectrum) + endif + if(.not.allocated(this%spectrum)) allocate(this%spectrum(nspectrum)) + do i=-ia,ia + y=0 + j=i+nint(xi2) + if(abs(j*df).lt.10.0) y=0.99*ss(j) + this%spectrum(i+ia+1)=y + enddo + call this%spectrum_sink(this%spectrum(1:nspectrum),df,-ia*df) + endif return end subroutine dopspread diff --git a/lib/fst4_host_support.f90 b/lib/fst4_host_support.f90 new file mode 100644 index 00000000..b5a61d45 --- /dev/null +++ b/lib/fst4_host_support.f90 @@ -0,0 +1,81 @@ +module fst4_host_support + use fst4_decode, only: fst4_decoder,fst4_options + use prog_args, only: data_dir + use fftw3, only: FFTW_ESTIMATE,FFTW_ESTIMATE_PATIENT,FFTW_MEASURE,FFTW_PATIENT,FFTW_EXHAUSTIVE + implicit none +contains + subroutine prepare_fst4_host(decoder,options) + class(fst4_decoder), intent(inout) :: decoder + type(fst4_options), intent(inout) :: options + logical exists + integer unit,ios,i + integer npatience,nthreads + common/patience/npatience,nthreads + options%fft_flags=FFTW_ESTIMATE + select case(npatience) + case(1) + options%fft_flags=FFTW_ESTIMATE_PATIENT + case(2) + options%fft_flags=FFTW_MEASURE + case(3) + options%fft_flags=FFTW_PATIENT + case(4) + options%fft_flags=FFTW_EXHAUSTIVE + end select + inquire(file='plotspec',exist=options%measure_doppler) + inquire(file=trim(data_dir)//'/decdata',exist=exists) + nullify(decoder%diagnostic,decoder%spectrum_sink) + if(exists) decoder%diagnostic=>write_fst4_diagnostic + if(options%measure_doppler) decoder%spectrum_sink=>write_fst4_spectrum + if(decoder%host_history_loaded) return + decoder%host_history_loaded=.true. + inquire(file=trim(data_dir)//'/fst4w_calls.txt',exist=exists) + if(.not.exists) return + open(newunit=unit,file=trim(data_dir)//'/fst4w_calls.txt',status='old',iostat=ios) + if(ios/=0) return + decoder%nwcalls=0 + do i=1,100 + read(unit,'(a)',iostat=ios) decoder%wcalls(i) + if(ios/=0) exit + decoder%wcalls(i)=adjustl(decoder%wcalls(i)) + if(len_trim(decoder%wcalls(i))==0) exit + decoder%nwcalls=i + enddo + close(unit) + end subroutine + + subroutine finish_fst4_host(decoder) + class(fst4_decoder), intent(inout) :: decoder + integer unit,ios,i + if(decoder%history_dirty) then + open(newunit=unit,file=trim(data_dir)//'/fst4w_calls.txt',status='replace',iostat=ios) + if(ios==0) then + do i=1,decoder%nwcalls + write(unit,'(a20)') trim(decoder%wcalls(i)) + enddo + close(unit) + decoder%history_dirty=.false. + endif + endif + nullify(decoder%diagnostic,decoder%spectrum_sink) + end subroutine + + subroutine write_fst4_spectrum(spectrum,df,first_frequency) + real, intent(in) :: spectrum(:),df,first_frequency + integer :: i + integer, save :: spectrum_number=0 + do i=1,size(spectrum) + write(52,'(f12.6,f12.6)') first_frequency+(i-1)*df,spectrum(i)+spectrum_number + enddo + spectrum_number=spectrum_number+1 + end subroutine + + subroutine write_fst4_diagnostic(line) + character(len=*), intent(in) :: line + integer unit,ios + open(newunit=unit,file=trim(data_dir)//'/fst4_decodes.dat',status='unknown',position='append',iostat=ios) + if(ios/=0) return + write(unit,'(a)') trim(line) + close(unit) + end subroutine +end module diff --git a/lib/ft4/genft4.f90 b/lib/ft4/genft4.f90 index 2fdd478a..73910e98 100644 --- a/lib/ft4/genft4.f90 +++ b/lib/ft4/genft4.f90 @@ -1,93 +1,99 @@ -subroutine genft4(msg0,ichk,msgsent,msgbits,i4tone) - -! Encode an FT4 message -! Input: -! - msg0 requested message to be transmitted -! - ichk if ichk=1, return only msgsent -! - msgsent message as it will be decoded -! - i4tone array of audio tone values, {0,1,2,3} - -! Frame structure: -! s16 + 87symbols + 2 ramp up/down = 105 total channel symbols -! r1 + s4 + d29 + s4 + d29 + s4 + d29 + s4 + r1 +module ft4_codec + use packjt77, only: pack77_state,pack77_legacy_truncating_fallback_for_state,unpack77_for_state + implicit none + private + public :: genft4_for_state,ft4_tones_from_77bits,ft4_scramble -! Message duration: TxT = 105*576/12000 = 5.04 s - -! use iso_c_binding, only: c_loc,c_size_t + integer(kind=1), parameter :: rvec(77)=[ & + 0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, & + 1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,1, & + 0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1] - use packjt77 - include 'ft4_params.f90' - character*37 msg0 - character*37 message !Message to be generated - character*37 msgsent !Message as it will be received - character*77 c77 - integer*4 i4tone(NN),itmp(ND) - integer*1 codeword(2*ND) - integer*1 msgbits(77),rvec(77) - integer icos4a(4),icos4b(4),icos4c(4),icos4d(4) - logical unpk77_success - data icos4a/0,1,3,2/ - data icos4b/1,0,2,3/ - data icos4c/2,3,1,0/ - data icos4d/3,2,0,1/ - data rvec/0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, & - 1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,1, & - 0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1/ - message=msg0 +contains - do i=1, 37 - if(ichar(message(i:i)).eq.0) then - message(i:37)=' ' - exit - endif - enddo - do i=1,37 !Strip leading blanks - if(message(1:1).ne.' ') exit - message=message(i+1:) - enddo + subroutine genft4_for_state(state,msg0,ichk,msgsent,msgbits,i4tone) + type(pack77_state), target, intent(inout) :: state + character(len=37), intent(in) :: msg0 + integer, intent(in) :: ichk + character(len=37), intent(out) :: msgsent + integer(kind=1), intent(inout) :: msgbits(77) + integer, intent(inout) :: i4tone(103) + character(len=37) :: message + character(len=77) :: c77 + integer :: i,i3,n3 + logical :: unpacked - i3=-1 - n3=-1 - c77=' ' - unpk77_success=.false. - call pack77_legacy_truncating_fallback(message,i3,n3,c77) - if(i3.lt.0 .or. n3.lt.0) go to 1 - call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent + message=msg0 + i=index(message,char(0)) + if(i>0) message(i:)=' ' + message=adjustl(message) + i3=-1 + n3=-1 + c77=' ' + unpacked=.false. + call pack77_legacy_truncating_fallback_for_state(state,message,i3,n3,c77) + if(i3<0.or.n3<0) go to 10 + call unpack77_for_state(state,c77,0,msgsent,unpacked) + if(ichk==1) return + read(c77,'(77i1)',err=10) msgbits + if(.not.unpacked) go to 10 + call ft4_tones_from_77bits(msgbits,i4tone) + return +10 msgbits=0 + i4tone=0 + msgsent='*** bad message ***' + end subroutine - if(ichk.eq.1) go to 999 - read(c77,'(77i1)',err=1) msgbits - if(unpk77_success) go to 2 -1 msgbits=0 - i4tone=0 - msgsent='*** bad message *** ' - go to 999 + subroutine ft4_scramble(bits) + integer(kind=1), intent(inout) :: bits(77) + bits=mod(bits+rvec,2) + end subroutine -entry get_ft4_tones_from_77bits(msgbits,i4tone) + subroutine ft4_tones_from_77bits(msgbits,i4tone) + integer(kind=1), intent(in) :: msgbits(77) + integer, intent(out) :: i4tone(103) + integer(kind=1) :: scrambled(77),codeword(174) + integer :: i,is,itmp(87) + integer, parameter :: graymap(0:3)=[0,1,3,2] -2 msgbits=mod(msgbits+rvec,2) - call encode174_91(msgbits,codeword) + scrambled=msgbits + call ft4_scramble(scrambled) + call encode174_91(scrambled,codeword) + do i=1,87 + is=codeword(2*i)+2*codeword(2*i-1) + itmp(i)=graymap(is) + enddo + i4tone(1:4)=[0,1,3,2] + i4tone(5:33)=itmp(1:29) + i4tone(34:37)=[1,0,2,3] + i4tone(38:66)=itmp(30:58) + i4tone(67:70)=[2,3,1,0] + i4tone(71:99)=itmp(59:87) + i4tone(100:103)=[3,2,0,1] + end subroutine +end module ft4_codec -! Grayscale mapping: -! bits tone -! 00 0 -! 01 1 -! 11 2 -! 10 3 +subroutine genft4(msg0,ichk,msgsent,msgbits,i4tone) + use decoder_codec_context, only: get_decoder_codec_state + use ft4_codec, only: genft4_for_state,ft4_scramble + implicit none + character(len=37), intent(in) :: msg0 + integer, intent(in) :: ichk + character(len=37), intent(out) :: msgsent + integer(kind=1), intent(inout) :: msgbits(77) + integer, intent(inout) :: i4tone(103) - do i=1,ND - is=codeword(2*i)+2*codeword(2*i-1) - if(is.le.1) itmp(i)=is - if(is.eq.2) itmp(i)=3 - if(is.eq.3) itmp(i)=2 - enddo + call genft4_for_state(get_decoder_codec_state(),msg0,ichk,msgsent,msgbits,i4tone) + ! The legacy encoder returns scrambled bits; engine evidence uses canonical bits. + if(ichk/=1.and.msgsent/='*** bad message ***') call ft4_scramble(msgbits) +end subroutine genft4 - i4tone(1:4)=icos4a - i4tone(5:33)=itmp(1:29) - i4tone(34:37)=icos4b - i4tone(38:66)=itmp(30:58) - i4tone(67:70)=icos4c - i4tone(71:99)=itmp(59:87) - i4tone(100:103)=icos4d +subroutine get_ft4_tones_from_77bits(msgbits,i4tone) + use ft4_codec, only: ft4_tones_from_77bits,ft4_scramble + implicit none + integer(kind=1), intent(inout) :: msgbits(77) + integer, intent(out) :: i4tone(103) -999 return -end subroutine genft4 + call ft4_tones_from_77bits(msgbits,i4tone) + call ft4_scramble(msgbits) +end subroutine get_ft4_tones_from_77bits diff --git a/lib/ft4_decode.f90 b/lib/ft4_decode.f90 index 540c3911..d6dca1ac 100644 --- a/lib/ft4_decode.f90 +++ b/lib/ft4_decode.f90 @@ -1,14 +1,21 @@ module ft4_decode + use packjt77, only: pack77_state,pack77_for_state,unpack77_for_state + use decoder_engine_types, only: ft4_signal_evidence,engine_payload_decoded + use ft4_codec, only: ft4_tones_from_77bits type :: ft4_decoder - procedure(ft4_decode_callback), pointer :: callback + procedure(ft4_decode_callback), pointer :: callback => null() + character(len=12) :: mycall0='',hiscall0='' + integer :: apbits(174)=99,apmy_ru(28)=0,aphis_fd(28)=0 + logical :: ap_ready=.false. contains procedure :: decode + procedure :: reset end type ft4_decoder abstract interface - subroutine ft4_decode_callback (this,sync,snr,dt,freq,decoded,nap,qual) - import ft4_decoder + subroutine ft4_decode_callback (this,sync,snr,dt,freq,decoded,nap,qual,evidence) + import ft4_decoder,ft4_signal_evidence implicit none class(ft4_decoder), intent(inout) :: this real, intent(in) :: sync @@ -18,25 +25,37 @@ module ft4_decode character(len=37), intent(in) :: decoded integer, intent(in) :: nap real, intent(in) :: qual + type(ft4_signal_evidence), intent(in) :: evidence end subroutine ft4_decode_callback end interface contains + subroutine reset(this) + class(ft4_decoder), intent(inout) :: this + this%mycall0='' + this%hiscall0='' + this%apbits=99 + this%apmy_ru=0 + this%aphis_fd=0 + this%ap_ready=.false. + nullify(this%callback) + end subroutine reset + subroutine decode(this,callback,iwave,nQSOProgress,nfqso, & - nfa,nfb,ndepth,lapcqonly,ncontest,mycall,hiscall) + nfa,nfb,ndepth,lapcqonly,ncontest,mycall,hiscall,knowledge) use timer_module, only: timer - use packjt77 include 'ft4/ft4_params.f90' parameter (MAXCAND=200) class(ft4_decoder), intent(inout) :: this + type(pack77_state), target, intent(inout) :: knowledge + type(ft4_signal_evidence) :: evidence procedure(ft4_decode_callback) :: callback parameter (NSS=NSPS/NDOWN,NDMAX=NMAX/NDOWN) character message*37,msgsent*37 character c77*77 character*37 decodes(100) character*12 mycall,hiscall - character*12 mycall0,hiscall0 complex cd2(0:NDMAX-1) !Complex waveform complex cb(0:NDMAX-1) @@ -50,8 +69,6 @@ contains real candidate(2,MAXCAND) real savg(NH1),sbase(NH1) - integer apbits(2*ND) - integer apmy_ru(28),aphis_fd(28) integer*2 iwave(NMAX) !Raw received data integer*1 message77(77),rvec(77),apmask(2*ND),cw(2*ND) integer*1 message91(91) @@ -80,12 +97,11 @@ contains data rvec/0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, & 1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,1, & 0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1/ - save dd,fs,dt,tt,txt,twopi,h,first,apbits,nappasses,naptypes, & - mycall0,hiscall0,ctwk2 + save dd,fs,dt,tt,txt,twopi,h,first,nappasses,naptypes,ctwk2 + associate(mycall0=>this%mycall0,hiscall0=>this%hiscall0,apbits=>this%apbits, & + apmy_ru=>this%apmy_ru,aphis_fd=>this%aphis_fd) this%callback => callback - dxcall13=hiscall ! initialize for use in packjt77 - mycall13=mycall smax1=0. nd1=0 @@ -136,8 +152,6 @@ contains naptypes(4,1:4)=(/3,6,0,0/) ! Tx4 naptypes(5,1:4)=(/3,1,2,0/) ! Tx5 - mycall0='' - hiscall0='' first=.false. endif @@ -145,7 +159,9 @@ contains if(l1.ne.0) mycall(l1:)=" " l1=index(hiscall,char(0)) if(l1.ne.0) hiscall(l1:)=" " - if(mycall.ne.mycall0 .or. hiscall.ne.hiscall0) then + knowledge%dxcall13=hiscall + knowledge%mycall13=mycall + if(.not.this%ap_ready .or. mycall.ne.mycall0 .or. hiscall.ne.hiscall0) then apbits=0 apbits(1)=99 apbits(30)=99 @@ -163,8 +179,8 @@ contains message=trim(mycall)//' '//trim(hiscall0)//' RR73' i3=-1 n3=-1 - call pack77(message,i3,n3,c77) - call unpack77(c77,1,msgsent,unpk77_success) + call pack77_for_state(knowledge,message,i3,n3,c77) + call unpack77_for_state(knowledge,c77,1,msgsent,unpk77_success) if(i3.ne.1 .or. (message.ne.msgsent) .or. .not.unpk77_success) go to 10 read(c77,'(77i1)') message77 apmy_ru=2*mod(message77(1:28)+rvec(2:29),2)-1 @@ -177,6 +193,7 @@ contains 10 continue mycall0=mycall hiscall0=hiscall + this%ap_ready=.true. endif ndecodes=0 decodes=' ' @@ -189,6 +206,7 @@ contains ! ndepth=1: 1 pass, no subtraction max_iterations=40 + napwid=50 syncmin=1.18 dosubtract=.true. doosd=.true. @@ -426,10 +444,17 @@ contains if( nharderror.ge.0 ) then message77=mod(message77+rvec,2) ! remove rvec scrambling write(c77,'(77i1)') message77(1:77) - call unpack77(c77,1,message,unpk77_success) + call unpack77_for_state(knowledge,c77,1,message,unpk77_success) if(.not.unpk77_success) exit + evidence=ft4_signal_evidence() + evidence%payload77=message77 + evidence%payload_origin=engine_payload_decoded + call ft4_tones_from_77bits(message77,i4tone) + evidence%tones=int(i4tone,kind(evidence%tones)) + evidence%has_tones=1 + evidence%waveform_start_seconds=real(ibest)/666.67-real(NSPS)/12000.0 + evidence%has_waveform_start=1 if(dosubtract) then - call get_ft4_tones_from_77bits(message77,i4tone) dt=real(ibest)/666.67 call timer('subtract',0) call subtractft4(dd,i4tone,f1,dt) @@ -450,7 +475,7 @@ contains nsnr=nint(max(-21.0,xsnr)) xdt=ibest/666.67 - 0.5 qual=1.0-(nharderror+dmin)/60.0 - call this%callback(smax,nsnr,xdt,f1,message,iaptype,qual) + call this%callback(smax,nsnr,xdt,f1,message,iaptype,qual,evidence) exit endif enddo !Sequence estimation @@ -458,6 +483,7 @@ contains enddo !3 DT segments enddo !Candidate list enddo !Subtraction loop + end associate return end subroutine decode diff --git a/lib/ft8/ft8_a7.f90 b/lib/ft8/ft8_a7.f90 index 09a3837f..aac13b1d 100644 --- a/lib/ft8/ft8_a7.f90 +++ b/lib/ft8/ft8_a7.f90 @@ -17,6 +17,15 @@ module ft8_a7 contains +subroutine reset_ft8_a7() + dt0=0. + f0=0. + msg0='' + itone_a7=0 + jseq=0 + ndec=0 +end subroutine reset_ft8_a7 + subroutine ft8_a7_save(jseq,dt,f,msg) use packjt77 @@ -40,9 +49,9 @@ subroutine ft8_a7_save(jseq,dt,f,msg) j=jseq ! Add this decode to current table for this sequence - ndec(j,1)=ndec(j,1)+1 !Number of decodes in this sequence - i=ndec(j,1) !i is index of a new table entry - if(i.gt.MAXDEC) return !Prevent table overflow (indexes start at 1) + if(ndec(j,1).ge.MAXDEC) return + ndec(j,1)=ndec(j,1)+1 + i=ndec(j,1) dt0(i,j,1)=dt !Save dt in table f0(i,j,1)=f !Save f in table @@ -72,13 +81,15 @@ subroutine ft8_a7_save(jseq,dt,f,msg) end subroutine ft8_a7_save subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin, & - msg37,xsnr) + msg37,xsnr,knowledge,evidence) ! Examine the raw data in dd0() for possible "a7" decodes. use crc use timer_module, only: timer use packjt77 + use ft8_codec_context, only: get_ft8_codec_state,genft8_for_state + use decoder_engine_types, only: ft8_signal_evidence,engine_payload_hypothesis include 'ft8_params.f90' parameter(NP2=2812) character*37 msg37,msg,msgsent,msgbest @@ -95,8 +106,10 @@ subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin, real rcw(174) integer*1 cw(174) integer*1 msgbits(77) + integer*1 msgbits_best(77) integer*1 nxor(174),hdec(174) integer itone(NN) + integer itone_best(NN) integer icos7(0:6),ip(1) logical one(0:511,0:8) integer graymap(0:7) @@ -106,12 +119,19 @@ subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin, complex csymb(32) complex cs(0:7,NN) logical std_1,std_2 + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + type(ft8_signal_evidence), optional, intent(out) :: evidence logical first,newdat data icos7/3,1,4,0,6,5,2/ !Sync array data first/.true./ data graymap/0,1,3,2,5,6,4,7/ save one + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge + if(present(evidence)) evidence=ft8_signal_evidence() + if(first) then one=.false. do i=0,511 @@ -313,7 +333,7 @@ subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin, i3=-1 n3=-1 - call genft8(msg,i3,n3,msgsent,msgbits,itone) !Source-encode this message + call genft8_for_state(codec,msg,i3,n3,msgsent,msgbits,itone) call encode174_91(msgbits,cw) !Get codeword for this message rcw=2*cw-1 pow=0.0 @@ -346,6 +366,8 @@ subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin, if(dm.lt.dmin) then dmin=dm msgbest=msgsent + msgbits_best=msgbits + itone_best=itone pbest=pow if(dm.eq.da) then nharderrors=count((2*cw-1)*llra.lt.0.0) @@ -374,6 +396,16 @@ subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin, if(msg37(1:3).eq.'CQ ' .and. std_2 .and. grid4.eq.' ') nharderrors=-1 if(msg37(1:6).eq.'QU1RK ') nharderrors=-1 + if(present(evidence) .and. nharderrors.ge.0) then + evidence%payload77=msgbits_best + evidence%tones=int(itone_best,kind=1) + evidence%payload_origin=engine_payload_hypothesis + evidence%has_tones=1 + evidence%has_waveform_start=1 + evidence%waveform_start_seconds=xdt+0.5 + evidence%method=7 + endif + return end subroutine ft8_a7d diff --git a/lib/ft8/ft8_a8_test.f90 b/lib/ft8/ft8_a8_test.f90 index 33d5b91a..1553d367 100644 --- a/lib/ft8/ft8_a8_test.f90 +++ b/lib/ft8/ft8_a8_test.f90 @@ -4,6 +4,7 @@ program ft8_a8_test use wavhdr use ft8_a7 + use ft8_decode, only: ft8_a8d include 'ft8_params.f90' !Set various constants type(hdr) h !Header for .wav file character arg*12,fname*120 diff --git a/lib/ft8/ft8_a8d.f90 b/lib/ft8/ft8_a8d.f90 index 5d05fef1..ba3800e7 100644 --- a/lib/ft8/ft8_a8d.f90 +++ b/lib/ft8/ft8_a8d.f90 @@ -1,10 +1,12 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & - progress_generation) + progress_generation,knowledge,evidence) ! List decoding for FT8, activated only at nfqso (Rx Freq) +/- 10 Hz and when ! DxCall and DxGrid are populated. Returns xdt, fbest, and msgbest. use packjt77 + use ft8_codec_context, only: get_ft8_codec_state,genft8_for_state + use decoder_engine_types, only: ft8_signal_evidence,engine_payload_hypothesis use ft8_a7 use timer_module, only: timer use decode_completion_module, only: write_decode_progress @@ -18,6 +20,7 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & character*37 msg,msgsent,msgbest character*77 c77 integer*1 msgbits(77) + integer*1 msgbits_best(77) real xjunk(NZZ) real s(-NH:NH) !Power spectrum of cd0 ! real s00(-NH:NH) !Raw spectrum of downsampled data @@ -33,9 +36,15 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & integer itone(NN) integer itone_best(NN) integer, intent(in) :: progress_generation + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + type(ft8_signal_evidence), optional, intent(out) :: evidence integer ipk(1) logical newdat + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge + if(present(evidence)) evidence=ft8_signal_evidence() f1=f1a newdat=.true. ! Mix from f1 to baseband and downsample from dd into cd (complex, 200 Hz sampling) @@ -56,6 +65,7 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & fbest=0. msgbest='' itone_best=0 + msgbits_best=0 do imsg=1,NMSGS call write_decode_progress(progress_generation) call getmsg(imsg,mycall,dxcall,dxgrid,msg) @@ -63,8 +73,8 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & ! Source-encode the message, get itone(), and generate complex FT8 waveform. i3=-1 n3=-1 - call pack77(msg,i3,n3,c77) - call genft8(msg,i3,n3,msgsent,msgbits,itone) + call pack77_for_state(codec,msg,i3,n3,c77) + call genft8_for_state(codec,msg,i3,n3,msgsent,msgbits,itone) call gen_ft8wave(itone,NN,32,bt,fsd,0.0,cwave,xjunk,1,NWAVE) cwave(NWAVE:)=0. @@ -120,6 +130,7 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & tbest=tpk msgbest=msg itone_best=itone + msgbits_best=msgbits s1=s0 !Save overall best-fit spectrum endif enddo ! imsg @@ -187,6 +198,15 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & !3060 format(i2,f8.3,3f8.1,i5,2f7.2,1x,a) if(nhard.gt.54 .or. plog.lt.-159.0 .or. sigobig.lt.0.71) msgbest='' endif + if(present(evidence) .and. msgbest.ne.'') then + evidence%payload77=msgbits_best + evidence%tones=int(itone_best,kind=1) + evidence%payload_origin=engine_payload_hypothesis + evidence%has_tones=1 + evidence%has_waveform_start=1 + evidence%waveform_start_seconds=xdt+0.5 + evidence%method=8 + endif return end subroutine ft8_a8d diff --git a/lib/ft8/ft8apset.f90 b/lib/ft8/ft8apset.f90 index 73a224ec..4e395c87 100644 --- a/lib/ft8/ft8apset.f90 +++ b/lib/ft8/ft8apset.f90 @@ -1,4 +1,4 @@ -subroutine ft8apset(mycall12,hiscall12,ncontest,apsym,aph10) +subroutine ft8apset(mycall12,hiscall12,ncontest,apsym,aph10,knowledge) use packjt77 character*77 c77 character*37 msg,msgchk @@ -7,6 +7,10 @@ subroutine ft8apset(mycall12,hiscall12,ncontest,apsym,aph10) character*10 c10 integer apsym(58),aph10(10) logical nohiscall,unpk77_success,std + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + + if(present(knowledge)) codec => knowledge apsym=0 apsym(1)=99 @@ -25,7 +29,11 @@ subroutine ft8apset(mycall12,hiscall12,ncontest,apsym,aph10) n10=0 n12=0 n22=0 - call save_hash_call(hc13,n10,n12,n22) + if(present(knowledge)) then + call save_hash_call_for_state(codec,hc13,n10,n12,n22) + else + call save_hash_call(hc13,n10,n12,n22) + endif write(c10,'(b10.10)') iand(n10,Z'3FF') read(c10,'(10i1.1)',err=1) aph10 aph10=2*aph10-1 @@ -38,8 +46,13 @@ subroutine ft8apset(mycall12,hiscall12,ncontest,apsym,aph10) if(.not.std) msg='<'//trim(mycall12)//'> '//trim(hiscall)//' RRR' i3=0 n3=0 - call pack77(msg,i3,n3,c77) - call unpack77(c77,1,msgchk,unpk77_success) + if(present(knowledge)) then + call pack77_for_state(codec,msg,i3,n3,c77) + call unpack77_for_state(codec,c77,1,msgchk,unpk77_success) + else + call pack77(msg,i3,n3,c77) + call unpack77(c77,1,msgchk,unpk77_success) + endif if(ncontest.eq.7.and. (i3.ne.1 .or. .not.unpk77_success)) return if(ncontest.le.5.and. (i3.ne.1 .or. msg.ne.msgchk .or. .not.unpk77_success)) return diff --git a/lib/ft8/ft8b.f90 b/lib/ft8/ft8b.f90 index 8934e399..e2792ddb 100644 --- a/lib/ft8/ft8b.f90 +++ b/lib/ft8/ft8b.f90 @@ -1,11 +1,13 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, & lapcqonly,napwid,lsubtract,nagain,ncontest,imetric,iaptype,mycall12,hiscall12, & f1,xdt,xbase,apsym,aph10,nharderrors,dmin,nbadcrc,ipass, & - msg37,xsnr,itone) + msg37,xsnr,itone,knowledge,evidence) use crc use timer_module, only: timer use packjt77 + use ft8_codec_context, only: get_ft8_codec_state + use decoder_engine_types, only: ft8_signal_evidence,engine_payload_decoded include 'ft8_params.f90' parameter(NP2=2812) character*37 msg37 @@ -24,6 +26,9 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, & integer mcq(29),mcqru(29),mcqfd(29),mcqtest(29),mcqww(29) integer mrrr(19),m73(19),mrr73(19) integer itone(NN) + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + type(ft8_signal_evidence), optional, intent(out) :: evidence integer icos7(0:6),ip(1) integer nappasses(0:5) !Number of decoding passes to use for each QSO state integer naptypes(0:5,4) ! (nQSOProgress, decoding pass) maximum of 4 passes for now @@ -46,18 +51,25 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, & data m73/0,1,1,1,1,1,1,0,1,0,0,1,0,1,0,0,0,0,1/ data mrr73/0,1,1,1,1,1,1,0,0,1,1,1,0,1,0,1,0,0,1/ data first/.true./ + data ncontest0/-1/ data graymap/0,1,3,2,5,6,4,7/ save nappasses,naptypes,ncontest0,one + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge + if(present(evidence)) evidence=ft8_signal_evidence() + if(first.or.(ncontest.ne.ncontest0)) then - mcq=2*mcq-1 - mcqfd=2*mcqfd-1 - mcqru=2*mcqru-1 - mcqtest=2*mcqtest-1 - mcqww=2*mcqww-1 - mrrr=2*mrrr-1 - m73=2*m73-1 - mrr73=2*mrr73-1 + if(first) then + mcq=2*mcq-1 + mcqfd=2*mcqfd-1 + mcqru=2*mcqru-1 + mcqtest=2*mcqtest-1 + mcqww=2*mcqww-1 + mrrr=2*mrrr-1 + m73=2*m73-1 + mrr73=2*mrr73-1 + endif nappasses(0)=2 nappasses(1)=2 nappasses(2)=2 @@ -91,8 +103,8 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, & ncontest0=ncontest endif - dxcall13=hiscall12 ! initialize for use in packjt77 - mycall13=mycall12 + codec%dxcall13=hiscall12 + codec%mycall13=mycall12 max_iterations=30 nharderrors=-1 @@ -451,7 +463,7 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, & read(c77(75:77),'(b3)') i3 if(i3.gt.5 .or. (i3.eq.0.and.n3.gt.6)) cycle if(i3.eq.0 .and. n3.eq.2) cycle - call unpack77(c77,1,msg37,unpk77_success) + call unpack77_for_state(codec,c77,1,msg37,unpk77_success) if(.not.unpk77_success .or. index(msg37,'/R').gt.0 .or. & msg37(1:4).eq.'TU; ') then if(i3.ge.1 .and. i3.le.3 .and. ncontest.eq.0) cycle @@ -488,6 +500,15 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, & return endif if(xsnr .lt. -25.0) xsnr=-25.0 + if(present(evidence)) then + evidence%payload77=message77 + evidence%tones=int(itone,kind(evidence%tones)) + evidence%payload_origin=engine_payload_decoded + evidence%has_tones=1 + evidence%has_waveform_start=1 + evidence%waveform_start_seconds=xdt + evidence%method=iaptype + endif return enddo return diff --git a/lib/ft8/genft8.f90 b/lib/ft8/genft8.f90 index ce866451..39d0f508 100644 --- a/lib/ft8/genft8.f90 +++ b/lib/ft8/genft8.f90 @@ -1,48 +1,81 @@ +module ft8_codec_context + use decoder_codec_context, only: get_ft8_codec_state => get_decoder_codec_state + use packjt77, only: pack77_state,pack77_legacy_truncating_fallback_for_state, & + unpack77_for_state + implicit none + private + public :: get_ft8_codec_state,genft8_for_state,ft8_tones_from_77bits + +contains + + subroutine genft8_for_state(state,msg,i3,n3,msgsent,msgbits,itone) + type(pack77_state), target, intent(inout) :: state + character(len=37), intent(in) :: msg + character(len=37), intent(out) :: msgsent + integer, intent(out) :: i3,n3,itone(79) + integer(kind=1), intent(out) :: msgbits(77) + character(len=77) :: c77 + logical :: unpacked + + i3=-1 + n3=-1 + c77=' ' + unpacked=.false. + call pack77_legacy_truncating_fallback_for_state(state,msg,i3,n3,c77) + if(i3.ge.0) call unpack77_for_state(state,c77,0,msgsent,unpacked) + read(c77,'(77i1)',err=10) msgbits + if(i3.ge.0 .and. unpacked) then + call ft8_tones_from_77bits(msgbits,itone) + return + endif +10 msgbits=0 + itone=0 + msgsent='*** bad message ***' + end subroutine genft8_for_state + + subroutine ft8_tones_from_77bits(msgbits,itone) + integer :: KK,ND,NS,NN,NSPS,NZ,NMAX,NFFT1,NH1,NSTEP,NHSYM,NDOWN + include 'ft8_params.f90' + integer(kind=1), intent(in) :: msgbits(77) + integer, intent(out) :: itone(79) + integer(kind=1) :: codeword(174) + integer :: i,j,k,indx + integer, parameter :: icos7(0:6)=[3,1,4,0,6,5,2] + integer, parameter :: graymap(0:7)=[0,1,3,2,5,6,4,7] + + call encode174_91(msgbits,codeword) + itone(1:7)=icos7 + itone(37:43)=icos7 + itone(NN-6:NN)=icos7 + k=7 + do j=1,ND + i=3*j-2 + k=k+1 + if(j.eq.30) k=k+7 + indx=codeword(i)*4+codeword(i+1)*2+codeword(i+2) + itone(k)=graymap(indx) + enddo + end subroutine ft8_tones_from_77bits +end module ft8_codec_context + subroutine genft8(msg,i3,n3,msgsent,msgbits,itone) + use ft8_codec_context, only: get_ft8_codec_state,genft8_for_state + use packjt77, only: pack77_state + implicit none + character(len=37), intent(in) :: msg + character(len=37), intent(out) :: msgsent + integer, intent(out) :: i3,n3,itone(79) + integer(kind=1), intent(out) :: msgbits(77) + type(pack77_state), pointer :: state -! Encode an FT8 message, producing array itone(). - - use packjt77 - include 'ft8_params.f90' - character msg*37,msgsent*37 - character*77 c77 - integer*1 msgbits(77),codeword(174) - integer itone(79) - integer icos7(0:6) - integer graymap(0:7) - logical unpk77_success - data icos7/3,1,4,0,6,5,2/ !Costas 7x7 tone pattern - data graymap/0,1,3,2,5,6,4,7/ - - i3=-1 - n3=-1 - c77=' ' - unpk77_success=.false. - call pack77_legacy_truncating_fallback(msg,i3,n3,c77) - if(i3.ge.0) call unpack77(c77,0,msgsent,unpk77_success) - read(c77,'(77i1)',err=1) msgbits - if(i3.ge.0 .and. unpk77_success) go to 2 -1 msgbits=0 - itone=0 - msgsent='*** bad message *** ' - go to 900 - -entry get_ft8_tones_from_77bits(msgbits,itone) - -2 call encode174_91(msgbits,codeword) !Encode the test message - -! Message structure: S7 D29 S7 D29 S7 - itone(1:7)=icos7 - itone(36+1:36+7)=icos7 - itone(NN-6:NN)=icos7 - k=7 - do j=1,ND - i=3*j -2 - k=k+1 - if(j.eq.30) k=k+7 - indx=codeword(i)*4 + codeword(i+1)*2 + codeword(i+2) - itone(k)=graymap(indx) - enddo - -900 return + state => get_ft8_codec_state() + call genft8_for_state(state,msg,i3,n3,msgsent,msgbits,itone) end subroutine genft8 + +subroutine get_ft8_tones_from_77bits(msgbits,itone) + use ft8_codec_context, only: ft8_tones_from_77bits + implicit none + integer(kind=1), intent(in) :: msgbits(77) + integer, intent(out) :: itone(79) + call ft8_tones_from_77bits(msgbits,itone) +end subroutine get_ft8_tones_from_77bits diff --git a/lib/ft8/subtractft8.f90 b/lib/ft8/subtractft8.f90 index 40657e7e..8345b1a0 100644 --- a/lib/ft8/subtractft8.f90 +++ b/lib/ft8/subtractft8.f90 @@ -9,7 +9,8 @@ subroutine subtractft8(dd0,itone,f0,dt,lrefinedt) parameter (NMAX=15*12000,NFRAME=1920*79) parameter (NFFT=NMAX,NFILT=4000) - real dd(NMAX),dd0(NMAX) + real dd0(NMAX) + real, allocatable, save :: dd(:) real window(-NFILT/2:NFILT/2) real x(NFFT+2) real endcorrection(NFILT/2+1) @@ -22,6 +23,8 @@ subroutine subtractft8(dd0,itone,f0,dt,lrefinedt) equivalence (x,cx) save first,/heap8/,endcorrection + if(.not.allocated(dd)) allocate(dd(NMAX)) + if(first) then ! Create and normalize the filter pi=4.0*atan(1.0) fac=1.0/float(nfft) @@ -31,8 +34,9 @@ subroutine subtractft8(dd0,itone,f0,dt,lrefinedt) sumw=sumw+window(j) enddo cw=0. - cw(1:NFILT+1)=window/sumw - cw=cshift(cw,NFILT/2+1) + do j=-NFILT/2,NFILT/2 + cw(modulo(j-1,NFFT)+1)=window(j)/sumw + enddo call four2a(cw,nfft,1,-1,1) cw=cw*fac first=.false. diff --git a/lib/ft8/sync8.f90 b/lib/ft8/sync8.f90 index b14300ab..4c90e20c 100644 --- a/lib/ft8/sync8.f90 +++ b/lib/ft8/sync8.f90 @@ -6,11 +6,11 @@ subroutine sync8(dd,npts,nfa,nfb,syncmin,nfqso,maxcand,candidate,ncand,sbase) ! 2.5s / 0.16s/symbol * 4 samples/symbol = 62.5 lag steps in 2.5s parameter (JZ=62) complex cx(0:NH1) - real s(NH1,NHSYM) + real, allocatable :: s(:,:) real savg(NH1) real sbase(NH1) real x(NFFT1+2) - real sync2d(NH1,-JZ:JZ) + real, allocatable :: sync2d(:,:) real red(NH1) real red2(NH1) real candidate0(3,MAXPRECAND) @@ -26,6 +26,8 @@ subroutine sync8(dd,npts,nfa,nfb,syncmin,nfqso,maxcand,candidate,ncand,sbase) data icos7/3,1,4,0,6,5,2/ !Costas 7x7 tone pattern equivalence (x,cx) + allocate(s(NH1,NHSYM),sync2d(NH1,-JZ:JZ)) + ! Compute symbol spectra, stepping by NSTEP steps. savg=0. tstep=NSTEP/12000.0 diff --git a/lib/ft8_decode.f90 b/lib/ft8_decode.f90 index e23df118..e40a7120 100644 --- a/lib/ft8_decode.f90 +++ b/lib/ft8_decode.f90 @@ -1,4 +1,8 @@ module ft8_decode + use packjt77, only: pack77_state + use decoder_engine_types, only: ft8_signal_evidence + + integer, parameter, private :: MAX_EARLY=200,NPTS=15*12000,NSAVED_TONES=79 parameter (MAXFOX=1000) character*12 c2fox(MAXFOX) @@ -11,13 +15,27 @@ module ft8_decode type :: ft8_decoder procedure(ft8_decode_callback), pointer :: callback + type(pack77_state), pointer :: knowledge => null() + real, allocatable :: dd(:),dd1(:) + integer :: nutc0=-1,ndec_early=0 + logical :: audio_ready=.false. + integer, allocatable :: itone_save(:,:) + real, allocatable :: f1_save(:),xdt_save(:) + logical, allocatable :: lsubtracted(:) + character(len=37), allocatable :: allmessages(:) + integer, allocatable :: allsnrs(:) contains + procedure :: initialize => initialize_ft8_decoder procedure :: decode + procedure :: reset => reset_ft8_decoder + procedure :: release_input => release_ft8_input end type ft8_decoder + private :: initialize_ft8_decoder + abstract interface - subroutine ft8_decode_callback (this,sync,snr,dt,freq,decoded,nap,qual) - import ft8_decoder + subroutine ft8_decode_callback (this,sync,snr,dt,freq,decoded,nap,qual,evidence) + import ft8_decoder,ft8_signal_evidence implicit none class(ft8_decoder), intent(inout) :: this real, intent(in) :: sync @@ -27,31 +45,98 @@ module ft8_decode character(len=37), intent(in) :: decoded integer, intent(in) :: nap real, intent(in) :: qual + type(ft8_signal_evidence), intent(in), optional :: evidence end subroutine ft8_decode_callback end interface + interface + subroutine ft8apset(mycall12,hiscall12,ncontest,apsym,aph10,knowledge) + import pack77_state + character(len=12) :: mycall12,hiscall12 + integer :: ncontest,apsym(58),aph10(10) + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, & + lapcqonly,napwid,lsubtract,nagain,ncontest,imetric,iaptype,mycall12,hiscall12, & + f1,xdt,xbase,apsym,aph10,nharderrors,dmin,nbadcrc,ipass, & + msg37,xsnr,itone,knowledge,evidence) + import pack77_state,ft8_signal_evidence + real :: dd0(15*12000),f1,xdt,xbase,dmin,xsnr + logical :: newdat,lapon,lapcqonly,lsubtract,nagain + integer :: nQSOProgress,nfqso,nftx,ndepth,nzhsym,napwid,ncontest,imetric + integer :: iaptype,apsym(58),aph10(10),nharderrors,nbadcrc,ipass,itone(79) + character(len=12) :: mycall12,hiscall12 + character(len=37) :: msg37 + type(pack77_state), target, optional, intent(inout) :: knowledge + type(ft8_signal_evidence), optional, intent(out) :: evidence + end subroutine + subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, & + progress_generation,knowledge,evidence) + import pack77_state,ft8_signal_evidence + real :: dd(15*12000),f1a,xdt,fbest,xsnr,plog + character(len=12) :: mycall,dxcall + character(len=6) :: dxgrid + character(len=37) :: msgbest + integer :: progress_generation + type(pack77_state), target, optional, intent(inout) :: knowledge + type(ft8_signal_evidence), optional, intent(out) :: evidence + end subroutine + end interface + contains + subroutine initialize_ft8_decoder(this) + class(ft8_decoder), intent(inout) :: this + if(.not.allocated(this%dd)) allocate(this%dd(NPTS),source=0.) + if(.not.allocated(this%dd1)) allocate(this%dd1(NPTS),source=0.) + if(.not.allocated(this%itone_save)) allocate(this%itone_save(NSAVED_TONES,MAX_EARLY),source=0) + if(.not.allocated(this%f1_save)) allocate(this%f1_save(MAX_EARLY),source=0.) + if(.not.allocated(this%xdt_save)) allocate(this%xdt_save(MAX_EARLY),source=0.) + if(.not.allocated(this%lsubtracted)) allocate(this%lsubtracted(MAX_EARLY),source=.false.) + if(.not.allocated(this%allmessages)) allocate(this%allmessages(MAX_EARLY),source=repeat(' ',37)) + if(.not.allocated(this%allsnrs)) allocate(this%allsnrs(MAX_EARLY),source=0) + end subroutine initialize_ft8_decoder + + subroutine reset_ft8_decoder(this) + class(ft8_decoder), intent(inout) :: this + call this%release_input() + this%nutc0=-1 + end subroutine reset_ft8_decoder + + subroutine release_ft8_input(this) + class(ft8_decoder), intent(inout) :: this + call this%initialize() + this%dd=0. + this%dd1=0. + this%ndec_early=0 + this%audio_ready=.false. + this%itone_save=0 + this%f1_save=0. + this%xdt_save=0. + this%lsubtracted=.false. + this%allmessages='' + this%allsnrs=0 + end subroutine release_ft8_input + subroutine decode(this,callback,iwave,nQSOProgress,nfqso,nftx,newdat, & nutc,nfa,nfb,nzhsym,ndepth,emedelay,ncontest,nagain,lft8apon, & ltry_a8,lapcqonly,napwid,mycall12,hiscall12,hisgrid,ldiskdat) use iso_c_binding, only: c_bool, c_int use timer_module, only: timer use ft8_a7 + use ft8_codec_context, only: get_ft8_codec_state include 'ft8/ft8_params.f90' class(ft8_decoder), intent(inout) :: this procedure(ft8_decode_callback) :: callback - parameter (MAXCAND=1000,MAX_EARLY=200,NPTS=15*12000) + parameter (MAXCAND=1000) real*8 tsec,tseq real sbase(NH1) real candidate(3,MAXCAND) - real dd(NPTS),dd1(NPTS) logical, intent(in) :: lft8apon,lapcqonly,nagain logical newdat,lsubtract,ldupe,lrefinedt,ltry_a8 logical*1 ldiskdat - logical lsubtracted(MAX_EARLY) logical la8 character*12 mycall12,hiscall12,call_1,call_2 character*6 hisgrid @@ -59,18 +144,19 @@ contains integer*2 iwave(NPTS) integer apsym2(58),aph10(10) character datetime*13,msg37*37 - character*37 allmessages(MAX_EARLY) character*12 ctime - integer allsnrs(MAX_EARLY) integer itone(NN) - integer itone_save(NN,MAX_EARLY) - real f1_save(MAX_EARLY) - real xdt_save(MAX_EARLY) - data nutc0/-1/ - - save dd,dd1,nutc0,ndec_early,itone_save,f1_save,xdt_save,lsubtracted, & - allmessages + type(ft8_signal_evidence) :: evidence + type(pack77_state), pointer :: codec + call this%initialize() + associate(dd=>this%dd,dd1=>this%dd1,nutc0=>this%nutc0, & + ndec_early=>this%ndec_early,itone_save=>this%itone_save, & + f1_save=>this%f1_save,xdt_save=>this%xdt_save, & + lsubtracted=>this%lsubtracted,allmessages=>this%allmessages, & + allsnrs=>this%allsnrs) this%callback => callback + codec => this%knowledge + if(.not.associated(codec)) codec => get_ft8_codec_state() write(datetime,1001) nutc !### TEMPORARY ### 1001 format("000000_",i6.6) @@ -104,12 +190,18 @@ contains endif if(ndepth.eq.1 .and. nzhsym.eq.50) then dd=iwave + this%audio_ready=.true. endif - call ft8apset(mycall12,hiscall12,ncontest,apsym2,aph10) + call ft8apset(mycall12,hiscall12,ncontest,apsym2,aph10,codec) if(nzhsym.le.47) then dd=iwave dd1=dd + this%audio_ready=.true. + endif + if(nzhsym.eq.50 .and. .not.this%audio_ready) then + dd=iwave + this%audio_ready=.true. endif if(nzhsym.eq.41) then @@ -208,7 +300,7 @@ contains call ft8b(dd,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lft8apon, & lapcqonly,napwid,lsubtract,nagain,ncontest,imetric,iaptype,mycall12, & hiscall12,f1,xdt,xbase,apsym2,aph10,nharderrors,dmin, & - nbadcrc,iappass,msg37,xsnr,itone) + nbadcrc,iappass,msg37,xsnr,itone,codec,evidence) call timer('ft8b ',1) nsnr=nint(xsnr) xdt=xdt-0.5 @@ -232,7 +324,7 @@ contains if(.not.ldupe .and. associated(this%callback)) then qual=1.0-(nharderrors+dmin)/60.0 ! scale qual to [0.0,1.0] if(emedelay.ne.0) xdt=xdt+2.0 - call this%callback(sync,nsnr,xdt,f1,msg37,iaptype,qual) + call this%callback(sync,nsnr,xdt,f1,msg37,iaptype,qual,evidence) call ft8_a7_save(jseq,xdt,f1,msg37) !Enter decode in table endif endif @@ -268,7 +360,7 @@ contains msg37=' ' call timer('ft8_a7d ',0) call ft8_a7d(dd,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors, & - dmin,msg37,xsnr) + dmin,msg37,xsnr,codec,evidence) call timer('ft8_a7d ',1) if(nharderrors.ge.0) then @@ -277,7 +369,7 @@ contains iaptype=7 qual=1.0 if(index(msg37,trim(hiscall12)).gt.0) la8=.false. - call this%callback(sync,nsnr,xdt,f1,msg37,iaptype,qual) + call this%callback(sync,nsnr,xdt,f1,msg37,iaptype,qual,evidence) call ft8_a7_save(jseq,xdt,f1,msg37) !Enter decode in table endif endif @@ -290,7 +382,7 @@ contains ! Try for an a8 decode at nfqso f1=nfqso call timer('ft8_a8d ',0) - call ft8_a8d(dd,mycall12,hiscall12,hisgrid,f1,xdt,fbest,xsnr,plog,msg37,0) + call ft8_a8d(dd,mycall12,hiscall12,hisgrid,f1,xdt,fbest,xsnr,plog,msg37,0,codec,evidence) call timer('ft8_a8d ',1) if(msg37(1:1).ne.' ') then @@ -300,12 +392,13 @@ contains iaptype=8 qual=1.0 if(plog.lt.-147.0) qual=0.16 - call this%callback(sync,nsnr,xdt,fbest,msg37,iaptype,qual) + call this%callback(sync,nsnr,xdt,fbest,msg37,iaptype,qual,evidence) call ft8_a7_save(jseq,xdt,f1,msg37) !Enter decode in the a7 table endif endif endif + end associate return end subroutine decode diff --git a/lib/ft8_engine_kernel.f90 b/lib/ft8_engine_kernel.f90 new file mode 100644 index 00000000..15f3f954 --- /dev/null +++ b/lib/ft8_engine_kernel.f90 @@ -0,0 +1,636 @@ +module ft8_engine_kernel +!$ use omp_lib + use prog_args, only: temp_dir + use timer_module, only: timer + use packjt77, only: pack77_state + use decoder_engine_types, only: ft8_signal_evidence + use ft8_decode, only: c2fox,g2fox,nsnrfox,nfreqfox,n30fox,n30z,nfox,ft8_a8d + use ft8_decodevar, only: ltry_a8 + use ft8_decode_ranges, only: max_ft8_decode_ranges, partition_ft8_decode_range + use ft8_mtd_residual, only: mtd_prepare,mtd_finish,mtd_worker_residual,mtd_worker_spectrum + use decoder_callbacks, only: decoder_callback_context,counting_ft8_decoder, & + counting_ft8_decodervar,ft8_decoded,ft8_decodedvar + use decode_completion_module, only: decode_completion_result,reset_decode_completion, & + set_decode_completion,write_decode_progress + use sfrx_engine, only: sfrx_decode + use ft8_mod1, only : ndecodes,allmessages,allsnrs,allfreq,mycall12_0, & + mycall12_00,hiscall12_0,nmsg,odd,even,oddcopy,evencopy,nlasttx, & + lqsomsgdcd,mycalllen1,msgroot,msgrootlen,lapmyc,sumxdtt,avexdt, & + nfawide,nfbwide,mycall,hiscall,lhound,mybcall,hisbcall,lenabledxcsearch, & + lwidedxcsearch,hisgrid4,lmultinst,dd8,nft8cycles,lskiptx1,ncandallthr, & + nincallthr,incall,msgincall,xdtincall,maskincallthr,ltxing,hisgrid, & + lastrxmsg,lasthcall + include 'jt9com.f90' + + private + public :: ft8_kernel_state,run_ft8_kernel,reset_ft8_kernel,release_ft8_input,params_block + + type :: ft8_kernel_state + type(counting_ft8_decoder) :: my_ft8 + type(counting_ft8_decodervar) :: my_ft8var + logical :: first=.true.,firstsd=.true. + logical :: mtd_residual_ready=.false. + logical(1) :: lhoundprev=.false. + integer :: nutc=0,ndelay=0,ntr0=-1,nintcount=0,nwrap=0 + integer :: ndec41=0,ndec46=0,ndec47=0,ndec48=0,ndec49=0 + end type + + interface + subroutine tone8(lmycallstd,lhiscallstd,knowledge) + import pack77_state + logical(1), intent(in) :: lmycallstd,lhiscallstd + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine tone8myc(knowledge) + import pack77_state + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine cwfilter(first,knowledge,render_legacy) + import pack77_state + logical, intent(in) :: first + type(pack77_state), target, optional, intent(inout) :: knowledge + logical, optional, intent(in) :: render_legacy + end subroutine + subroutine partintft8(ndelay,nutc,render_legacy) + integer :: ndelay,nutc + logical, optional, intent(in) :: render_legacy + end subroutine + subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads,knowledge) + import pack77_state + logical(1), intent(in) :: lmycallstd,lhiscallstd + integer :: numthreads + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine fillhashvar(numthreads,lfill,knowledge) + import pack77_state + integer, intent(in) :: numthreads + logical, intent(in) :: lfill + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + end interface + +contains + + subroutine reset_ft8_kernel(state) + use ft8_mod1, only: reset_ft8_mod1 + use ft8_a7, only: reset_ft8_a7 + type(ft8_kernel_state), intent(inout) :: state + call state%my_ft8%reset() + state%my_ft8%decoded=0 + state%my_ft8%first_result=.true. + state%my_ft8%day_wrap=0 + state%my_ft8var%decodedvar=0 + state%my_ft8var%first_result=.true. + state%my_ft8var%day_wrap=0 + state%my_ft8var%xdtt=0. + state%first=.true. + state%mtd_residual_ready=.false. + state%firstsd=.true. + state%lhoundprev=.false. + state%nutc=0 + state%ndelay=0 + state%ntr0=-1 + state%nintcount=0 + state%nwrap=0 + state%ndec41=0 + state%ndec46=0 + state%ndec47=0 + state%ndec48=0 + state%ndec49=0 + c2fox='' + g2fox='' + nsnrfox=-99 + nfreqfox=-99 + n30fox=0 + n30z=0 + nfox=0 + ltry_a8=.true. + call reset_ft8_mod1() + call reset_ft8_a7() + call reset_ft8apsetvar() + end subroutine + + subroutine release_ft8_input(state) + type(ft8_kernel_state), intent(inout) :: state + call state%my_ft8%release_input() + state%mtd_residual_ready=.false. + state%ndec41=0 + state%ndec46=0 + state%ndec47=0 + state%ndec48=0 + state%ndec49=0 + end subroutine release_ft8_input + + subroutine run_ft8_kernel(state,knowledge,id2,params,completion,progress_generation,callback_context) + type(ft8_kernel_state), intent(inout) :: state + type(pack77_state), target, intent(inout) :: knowledge + integer(c_short), intent(inout) :: id2(180000) + type(params_block), intent(inout) :: params + type(decode_completion_result), intent(out) :: completion + integer, intent(in) :: progress_generation + type(decoder_callback_context), intent(in) :: callback_context + type(decoder_callback_context) :: context + integer :: ft8_range_low(max_ft8_decode_ranges),ft8_range_high(max_ft8_decode_ranges) + integer :: ft8_range_count,requested_threads,nthr,active_progress_generation + integer :: ncontest,nfqso + logical :: newdat,ex + character(len=6) :: mygrid + character(len=60) :: line + + associate(my_ft8=>state%my_ft8,my_ft8var=>state%my_ft8var,first=>state%first, & + firstsd=>state%firstsd,lhoundprev=>state%lhoundprev,nutc=>state%nutc, & + ndelay=>state%ndelay,ntr0=>state%ntr0,nintcount=>state%nintcount, & + nwrap=>state%nwrap,ndec41=>state%ndec41,ndec46=>state%ndec46, & + ndec47=>state%ndec47,ndec48=>state%ndec48,ndec49=>state%ndec49) + call reset_decode_completion(completion) + active_progress_generation=progress_generation + context=callback_context + ncontest=iand(params%nexp_decode,7) + nsynced=0 + navg0=0 + my_ft8%decoded=0 + my_ft8var%decodedvar=0 + my_ft8var%xdtt=0. + my_ft8%knowledge=>knowledge + my_ft8var%knowledge=>knowledge + my_ft8var%callback=>ft8_decodedvar + + if(.not.params%newdat .and. params%ntr.gt.ntr0) go to 800 + ntr0=params%ntr + rms=sqrt(dot_product(real(id2),real(id2))/180000.0) + if(rms.lt.0.5) go to 800 + + mycall=transfer(params%mycall,mycall) + mybcall=transfer(params%mybcall,mybcall) + hiscall=transfer(params%hiscall,hiscall) + hisbcall=transfer(params%hisbcall,hisbcall) + mygrid=transfer(params%mygrid,mygrid) + hisgrid=transfer(params%hisgrid,hisgrid) + hisgrid4=hisgrid(1:4) + ncandallthr=0 + if(params%nzhsym.eq.41 .or. params%lmultift8) ltry_a8=.true. + + if(context%render_legacy) then + inquire(file='rx_messages.txt',exist=ex) + if(ex) then + if(params%nzhsym.eq.41) then + open(39,file='rx_messages.txt',status='old') + do i=1,9999 + read(39,'(a60)',end=5) line + if(line(1:1).eq.' ' .or. line(1:1).eq.'-') exit + write(*,'(a)') trim(line) + enddo +5 close(39) + endif + go to 800 + endif + nfail=0 +10 if(params%nagain) then + open(13,file=trim(temp_dir)//'/decoded.txt',status='unknown',position='append',iostat=ios13) + else + open(13,file=trim(temp_dir)//'/decoded.txt',status='unknown',iostat=ios13) + endif + if(ios13.ne.0) then + nfail=nfail+1 + if(nfail.le.3) then + call sleep_msec(10) + go to 10 + endif + endif + context%ios13=ios13 + endif + context%nutc=params%nutc + context%nfqso=params%nfqso + context%ncontest=ncontest + context%bVHF=iand(params%nexp_decode,64).ne.0 + context%b_superfox=params%b_superfox + context%mycall=mycall + my_ft8%context=context + my_ft8var%context=context + + if(ncontest.eq.6 .and. context%render_legacy) then + ! Fox mode: initialize and open houndcallers.txt + inquire(file=trim(temp_dir)//'/houndcallers.txt',exist=ex) + if(.not.ex) then + c2fox=' ' + g2fox=' ' + nsnrfox=-99 + nfreqfox=-99 + n30z=0 + nwrap=0 + nfox=0 + endif + open(19,file=trim(temp_dir)//'/houndcallers.txt',status='unknown') + endif + + if(ncontest.eq.7 .and. params%b_superfox .and. params%b_even_seq) then + if(params%nzhsym.lt.50) go to 800 + ! Call the superFox decoder + call sfrx_decode(knowledge,context%superfox_sink,context%sink_user, & + params%yymmdd,params%nutc,params%nfqso,params%ntol,id2) + else + call timer('decft8 ',0) + if(params%nfa.gt.params%nfb) then + call timer('decft8 ',1) + go to 800 + endif + newdat=params%newdat + if(params%emedelay.ne.0.0.and..not.params%lmultift8) then + id2(1:156000)=id2(24001:180000) ! Drop the first 2 seconds of data + id2(156001:180000)=0 + my_ft8%context%waveform_input_offset_seconds=2.0 + endif + +! ft8md below + if(params%lmultift8 .and. params%nmode.eq.8) then + ! Disk retries continue subtraction on this input; live attempts start with fresh audio. + if(.not.(params%ndiskdat.and.params%nagain.and.state%mtd_residual_ready)) dd8=real(id2) + if(params%lmodechanged) then + avexdt=0. + nintcount=3 + endif ! avexdt fast track in FT8 after mode change + + if(.not.params%nagain) ndelay=params%ndelay + lqsomsgdcd=.false. + if(ndelay.gt.0) then ! received incomplete interval + call partintft8(ndelay,params%nutc,context%render_legacy) + lqsomsgdcd=.true. + endif + ntrials=params%nranera + if(params%nsecbandchanged.gt.0) then + nsamplesdel=params%nsecbandchanged*12000 + if(params%nsecbandchanged.gt.14) then + dd8=0. ! protection + else + dd8(1:nsamplesdel)=0. + endif + endif + + if(.not.params%nagain) nutc=params%nutc + + if(first) then + call cwfilter(first,knowledge,context%render_legacy) + first=.false. + endif ! + ALLCALL to memory + lenabledxcsearch=params%lenabledxcsearch + lwidedxcsearch=params%lwidedxcsearch + + lmultinst=params%lmultinst + lskiptx1=params%lskiptx1 + ltxing=params%ltxing + + mycalllen1=len_trim(mycall)+1 + msgroot='' + msgroot=trim(mycall)//' '//trim(hiscall)//' ' + msgrootlen=len_trim(msgroot) + lhound=params%lhound + nft8cycles=params%nft8cycles + forcedt=0. + + if((hiscall.ne.hiscall12_0 .and. hiscall.ne.' ') & + .or. (mycall.ne.mycall12_0 .and. mycall.ne.' ') .or. & + (lhound.neqv.lhoundprev)) then + if(hiscall.ne.' ') then + call tone8(params%lmycallstd,params%lhiscallstd,knowledge) + hiscall12_0=hiscall + mycall12_0=mycall + endif + lhoundprev=lhound + endif + if(params%lmycallstd .and. mycall.ne.' ' .and. & + mycall12_00.ne.mycall) then + call tone8myc(knowledge) + mycall12_00=mycall + endif + + ndecodes=0 !Initialize arrays for multi-threaded decoding + allmessages="" + allsnrs=0 + allfreq=0. + numcores=1 +!$ numcores=omp_get_num_procs() + nuserthr=params%nmt + + numthreads=1 ! fallback + if(nuserthr.eq.0) then ! auto + if(numcores.eq.1) then + numthreads=1 + else if(numcores.gt.1 .and. numcores.lt.5) then + numthreads=numcores-1 + else if(numcores.gt.4 .and. numcores.lt.9) then + numthreads=numcores-2 + else if(numcores.gt.8 .and. numcores.lt.16) then + numthreads=numcores-3 + else + numthreads=12 + endif + else if(nuserthr.gt.0 .and. nuserthr.lt.13) then + ! number of threads shall not exceed number of logical cores + if(numcores.ge.nuserthr) then + numthreads=nuserthr + else + numthreads=numcores + endif + endif + +!$ call omp_set_dynamic(.false.) +!$ call omp_set_max_active_levels(omp_get_supported_active_levels()) + + nfa=params%nfa + nfb=params%nfb + nfqso=params%nfqso + nfawide=params%nfa + nfbwide=params%nfb + + if(params%nagainfil) then + if(nfqso.lt.nfa .or. nfqso.gt.nfb) then + if(context%render_legacy) write(*,64) nutc,'nfqso is out of bandwidth','d' +64 format(i6.6,2x,a25,16x,a1) + go to 800 + endif + nfa=max(nfa,nfqso-25) ! 50Hz bandwidth for decode via double click + nfb=min(nfb,nfqso+25) + numthreads=min(4,numthreads) +! To do: withdraw limitation when threads are in sync at main passes? + endif + + call partition_ft8_decode_range(nfa,nfb,numthreads,ft8_range_low, & + ft8_range_high,ft8_range_count) + if(ft8_range_count.eq.0) then + call timer('decft8 ',1) + go to 800 + endif + numthreads=ft8_range_count + requested_threads=numthreads + + nsec=mod(nutc,100) + nmsg=0 + if(nsec.ne.0 .and. nsec.ne.15 .and. nsec.ne.30 .and. nsec.ne.45) then +! Reading simulated wav file + odd%lstate=.false. + even%lstate=.false. + oddcopy%lstate=.false. + evencopy%lstate=.false. + endif + + if(firstsd) then + odd%lstate=.false. + even%lstate=.false. + firstsd=.false. + endif + + if(nsec.eq.0 .or. nsec.eq.30) then + evencopy%msg=even%msg + evencopy%freq=even%freq + evencopy%dt=even%dt + evencopy%lstate=even%lstate + even%lstate=.false. + endif + + if(nsec.eq.15 .or. nsec.eq.45) then + oddcopy%msg=odd%msg + oddcopy%freq=odd%freq + oddcopy%dt=odd%dt + oddcopy%lstate=odd%lstate + odd%lstate=.false. + endif + + nlasttx=params%nlasttx + lapmyc=params%lapmyc + nFT8decd=0 + sumxdt=0.0 + if(params%nmode.eq.4) sumxdtt=0.0 + + if(hiscall.eq.'') then + lastrxmsg(1)%lstate=.false. + else if(lastrxmsg(1)%lstate .and. lasthcall.ne.hiscall .and. & + index(lastrxmsg(1)%lastmsg,trim(hiscall)).le.0) then + lastrxmsg(1)%lstate=.false. + endif + +!$omp parallel num_threads(requested_threads) private(nthr) shared(numthreads) +!$omp single + numthreads=1 +!$ numthreads=omp_get_num_threads() +! Reduced teams cover wider frequency slices, so fixed per-worker candidate limits can lower crowded-band yield. + call partition_ft8_decode_range(nfa,nfb,numthreads,ft8_range_low, & + ft8_range_high,ft8_range_count) + numthreads=ft8_range_count + call mtd_prepare(dd8,numthreads) + call fillhashvar(numthreads,.false.,knowledge) + call ft8apsetvar(params%lmycallstd,params%lhiscallstd,numthreads,knowledge) +!$omp end single + + nthr=1 +!$ nthr=omp_get_thread_num()+1 + call my_ft8var%decodevar(params%nQSOProgress,nfqso, & + params%nft8rxfsens,params%nftx,ft8_range_low(nthr), & + ft8_range_high(nthr),params%ncandthin,params%ndtcenter,nsec, & + params%napwid,params%lmycallstd,params%lhiscallstd, & + params%nstophint,nthr,numthreads,logical(params%nagainfil), & + params%lft8lowth,params%lft8subpass,params%lhideft8dupes, & + active_progress_generation, & + mtd_worker_residual(:,nthr), & + mtd_worker_spectrum(:,nthr)) +!$omp end parallel + + call write_decode_progress(active_progress_generation) + call mtd_finish(dd8) + state%mtd_residual_ready=.true. + + call write_decode_progress(active_progress_generation) + call run_ft8_mtd_a8_decode() + call write_decode_progress(active_progress_generation) + + do i=1,numthreads + do m=1,nincallthr(i) + nindex=maskincallthr(i)+m + incall(30:2:-1)=incall(30-1:1:-1) + incall(1)%msg=msgincall(nindex) + incall(1)%xdt=xdtincall(nindex) + enddo + enddo + + if(nsec.eq.0 .or. nsec.eq.30) even(nmsg+1:130)%lstate=.false. + if(nsec.eq.15 .or. nsec.eq.45) odd(nmsg+1:130)%lstate=.false. + + if(params%ndelay.eq.0) then + nFT8decd=my_ft8var%decodedvar + dtmed=0. +! if(params%lforcesync) then; nintcount=3 ! fast track after Sync +! elseif(nintcount.gt.0) then; nintcount=nintcount-1 + if(nintcount.gt.0) then + nintcount=nintcount-1 + endif +! if(params%lforcesync .and. nFT8decd.eq.0) then + if(nFT8decd.eq.0) then + avexdt=forcedt + else + if(nFT8decd.gt.2) then + do i=1,nFT8decd + if(i.lt.nFT8decd-1) then + if((my_ft8var%xdtt(i).gt.my_ft8var%xdtt(i+1) .and. & + my_ft8var%xdtt(i).lt.my_ft8var%xdtt(i+2)) .or. & + (my_ft8var%xdtt(i).lt.my_ft8var%xdtt(i+1) .and. & + my_ft8var%xdtt(i).gt.my_ft8var%xdtt(i+2))) then + dtmed=my_ft8var%xdtt(i) + else if((my_ft8var%xdtt(i+1).gt.my_ft8var%xdtt(i) .and. & + my_ft8var%xdtt(i+1).lt.my_ft8var%xdtt(i+2)) .or. & + (my_ft8var%xdtt(i+1).lt.my_ft8var%xdtt(i) .and. & + my_ft8var%xdtt(i+1).gt.my_ft8var%xdtt(i+2))) then + dtmed=my_ft8var%xdtt(i+1) + else if((my_ft8var%xdtt(i+2).gt.my_ft8var%xdtt(i) .and. & + my_ft8var%xdtt(i+2).lt.my_ft8var%xdtt(i+1)) .or. & + (my_ft8var%xdtt(i+2).lt.my_ft8var%xdtt(i) .and. & + my_ft8var%xdtt(i+2).gt.my_ft8var%xdtt(i+1))) then + dtmed=my_ft8var%xdtt(i+2) + else + dtmed=my_ft8var%xdtt(i) + endif + sumxdt=sumxdt+dtmed + else + sumxdt=sumxdt+dtmed ! use last median value + endif + enddo + if(nFT8decd.gt.5) then + avexdt=(avexdt+sumxdt/nFT8decd)/2 + else if(nFT8decd.eq.5) then + avexdt=(1.1*avexdt+0.9*sumxdt/nFT8decd)/2 + else if(nFT8decd.eq.4) then + avexdt=(1.25*avexdt+0.75*sumxdt/nFT8decd)/2 + else if(nFT8decd.eq.3) then + avexdt=(1.35*avexdt+0.65*sumxdt/nFT8decd)/2 + endif + else if(nFT8decd.gt.0) then + sumxdt=sum(my_ft8var%xdtt(1:nFT8decd)) + if(nFT8decd.eq.2) then + avexdt=(1.5*avexdt+0.5*sumxdt/nFT8decd)/2 + else if(nFT8decd.eq.1) then + avexdt=(1.75*avexdt+0.25*sumxdt)/2 + endif + endif + endif + endif + + if(nFT8decd.gt.10 .and. nintcount.eq.1) avexdt=sumxdt/nFT8decd ! fast track after Sync or mode change on crowded bands + call fillhashvar(numthreads,.true.,knowledge) + call write_decode_progress(active_progress_generation) + ncandall=sum(ncandallthr(1:numthreads)) + if(nFT8decd.eq.0) avexdt=0. ! reset to let correct sliding in decoder + call timer('decft8 ',1) + else ! still FT8 but not ft8md + call my_ft8%decode(ft8_decoded,id2,params%nQSOProgress,params%nfqso, & + params%nftx,newdat,params%nutc,params%nfa,params%nfb, & + params%nzhsym,params%ndepth,params%emedelay,ncontest, & + logical(params%nagain),logical(params%lft8apon),ltry_a8, & + logical(params%lapcqonly),params%napwid,mycall,hiscall,hisgrid, & + params%ndiskdat) + call timer('decft8 ',1) + endif ! end of 'still FT8 but not ft8md' + endif ! end of 'if not in SuperFox mode' + + j=0 + if(ncontest.eq.6) then + ! Fox mode: save decoded Hound calls for possible selection by FoxOp + n=params%nutc + n30=(3600*(n/10000) + 60*mod((n/100),100) + mod(n,100))/30 + if(n30.lt.n30z) nwrap=nwrap+2880 !New UTC day, handle the wrap + n30z=n30 + n30=n30+nwrap + + if(context%render_legacy) rewind 19 + if(nfox.eq.0) then + if(context%render_legacy) endfile 19 + if(context%render_legacy) rewind 19 + else + do i=1,nfox + n=n30fox(i) + nage=min(99,mod(n30-n+288000,2880)) + if(nage.le.4) then + j=j+1 + c2fox(j)=c2fox(i) + g2fox(j)=g2fox(i) + nsnrfox(j)=nsnrfox(i) + nfreqfox(j)=nfreqfox(i) + n30fox(j)=n + ! nage=min(99,mod(n30-n+288000,2880)) + if(len(trim(g2fox(j))).eq.4) then + call azdist(mygrid,g2fox(j)//' ',0.d0,nAz,nEl,nDmiles, & + nDkm,nHotAz,nHotABetter) + else + nDkm=9999 + endif + if(context%render_legacy) write(19,1004) c2fox(j),g2fox(j),nsnrfox(j),nfreqfox(j), & + nDkm,nage +1004 format(a12,1x,a4,i5,i6,i7,i3) + endif + enddo + nfox=j + if(context%render_legacy) flush(19) + endif + endif + + +800 ndecoded=my_ft8%decoded+my_ft8var%decodedvar + if(params%lmultift8 .and. params%nmode.eq.8) then + if(params%nzhsym.eq.41) ndec41=0 + if(params%nzhsym.eq.46) ndec46=ndecoded + if(params%nzhsym.eq.47) ndec47=ndecoded + if(params%nzhsym.eq.48) ndec48=ndecoded + if(params%nzhsym.eq.49) ndec49=ndecoded + if(params%nzhsym.eq.50) then + ndecoded=ndec41+ndec46+ndec47+ndec48+ndec49+ndecoded + endif + elseif(params%nmode.eq.8 .and. params%nzhsym.eq.41) then + ndec41=ndecoded + elseif(params%nmode.eq.8 .and. params%nzhsym.eq.47) then + ndec47=ndecoded + elseif(params%nmode.eq.8 .and. params%nzhsym.eq.50) then + ndecoded=ndec41+ndec47+ndecoded + endif + if(params%nmode.ne.8 .or. params%nzhsym.eq.50 .or. & + (params%lmultift8 .and. params%nmode.eq.8 .and. params%nzhsym.gt.45) .or. & + .not.params%ndiskdat) then !ft8md + call set_decode_completion(completion,nsynced,ndecoded,navg0) + call write_decode_progress(active_progress_generation) + endif + if(context%render_legacy) close(13) + if(ncontest.eq.6 .and. context%render_legacy) close(19) + end associate + + + contains + subroutine run_ft8_mtd_a8_decode() + implicit none + + real f1,xdt,fbest,xsnr,plog,qual + integer nsnr,iaptype + character(len=6) dxgrid + character(len=37) msg37 + type(ft8_signal_evidence) :: evidence + + if(.not.params%lft8apon) return + if(ncontest.eq.6 .or. ncontest.eq.7) return + if(len(trim(hiscall)).lt.3 .or. len(trim(hisgrid4)).lt.4) return + if(.not.ltry_a8) return + + f1=nfqso + dxgrid=hisgrid4 + call timer('ft8_a8d ',0) + call ft8_a8d(dd8,mycall,hiscall,dxgrid,f1,xdt,fbest,xsnr,plog,msg37, & + active_progress_generation,knowledge,evidence) + call timer('ft8_a8d ',1) + + if(msg37(1:1).ne.' ') then + if(associated(state%my_ft8var%callback)) then + nsnr=nint(xsnr) + iaptype=8 + qual=1.0 + if(plog.lt.-147.0) qual=0.16 + call state%my_ft8var%callback(nsnr,xdt,fbest,msg37,iaptype,qual,evidence) + endif + endif + end subroutine run_ft8_mtd_a8_decode + + end subroutine run_ft8_kernel +end module ft8_engine_kernel diff --git a/lib/ft8var/cwfilter.f90 b/lib/ft8var/cwfilter.f90 index e305047d..1115d3de 100644 --- a/lib/ft8var/cwfilter.f90 +++ b/lib/ft8var/cwfilter.f90 @@ -1,4 +1,8 @@ -subroutine cwfilter(first) +subroutine cwfilter(first,knowledge,render_legacy) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8sdvar_for_state use ft8_mod1, only : cw,windowc1,windowx,pivalue,facx,mcq,m73,mrr73,mrrr,one,twopi,facc1,dt,csync,idtone25,csynccq, & idtone25_valid, & @@ -13,12 +17,23 @@ subroutine cwfilter(first) integer itone(79) integer*1 msgbits(77) logical, intent(in) :: first + type(pack77_state), target, optional, intent(inout) :: knowledge + logical, optional, intent(in) :: render_legacy + logical :: emit_line + logical, save :: process_initialized=.false. + type(pack77_state), pointer :: codec + + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge + emit_line=.true. + if(present(render_legacy)) emit_line=render_legacy !pushing callsigns from ALLCALL to memory !note that with new, larger ALLCALL7.TXT files, dimensions of various ncall arrays may need to be increased in jt65_mod9.f90 !on 20250709 callj dim was increased from 9000 to 10000 when updated ALLCALL7.TXT file was added if(first) then allocate(csig0(151680)) + if(.not.process_initialized) then ! Open the shipped read-only ALLCALL7.TXT for reading only. status='old' with ! action='read' makes a missing/unreadable file degrade cleanly to an empty ! callsign DB (handled by the count check below) instead of status='unknown' @@ -60,9 +75,10 @@ subroutine cwfilter(first) ncallk.lt.1 .or. ncalllm.lt.1 .or. ncalln.lt.1 .or. ncallo.lt.1 .or. ncallpq.lt.1 .or. ncallr.lt.1 .or. & ncallst.lt.1 .or. ncalluv.lt.1 .or. ncallw.lt.1 .or. ncallxz.lt.1) then ldbvalid=.false. - write(*,4) 'ALLCALL7.TXT is too short or broken?','d' ! 50th position for "d" + if(emit_line) write(*,4) 'ALLCALL7.TXT is too short or broken?','d' 4 format(a36,13x,a1) - call flush(6) + if(emit_line) call flush(6) + endif endif pivalue=4.d0*atan(1.d0) @@ -77,10 +93,12 @@ subroutine cwfilter(first) windowx=facx*windowx facc1=0.01/sqrt(61440.) ! 1.0/sqrt(192000.*3200.) NFFT1*NFFT2 - mcq=2*mcq-1 - mrrr=2*mrrr-1 - m73=2*m73-1 - mrr73=2*mrr73-1 + if(.not.process_initialized) then + mcq=2*mcq-1 + mrrr=2*mrrr-1 + m73=2*m73-1 + mrr73=2*mrr73-1 + endif one=.false. do i=0,511 @@ -118,7 +136,7 @@ subroutine cwfilter(first) idtone25_valid(2:25)=.false. do i=2,25 i3=-1; n3=-1 - call genft8sdvar(msgcq25(i),i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msgcq25(i),i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) cycle if(i.eq.2) then call gen_ft8wave(itone,79,1920,2.0,12000.0,0.0,csig0,xjunk,1,151680) @@ -165,6 +183,7 @@ subroutine cwfilter(first) ctwk256(i)=cmplx(cos(phi),sin(phi)) phi=mod(phi+dphi,twopi) enddo + process_initialized=.true. endif ! this filter is being used for signal subtraction @@ -177,8 +196,9 @@ subroutine cwfilter(first) sumw=sumw+window1(j) enddo cw=0. - cw(1:NFILT1+1)=window1/sumw - cw=cshift(cw,NFILT1/2+1) + do j=-NFILT1/2,NFILT1/2 + cw(modulo(j-1,NFFT)+1)=window1(j)/sumw + enddo do j=1,NFILT1/2+1 endcorr(j)=1.0/(1.0-sum(window1(j-1:NFILT1/2))/sumw) enddo diff --git a/lib/ft8var/fillhashvar.f90 b/lib/ft8var/fillhashvar.f90 index 851ddc13..39489a08 100644 --- a/lib/ft8var/fillhashvar.f90 +++ b/lib/ft8var/fillhashvar.f90 @@ -1,11 +1,21 @@ -subroutine fillhashvar(numthreads,lfill) +subroutine fillhashvar(numthreads,lfill,knowledge) use packjt77 use ft8_mod1, only : mycall,hiscall integer, intent(in) :: numthreads logical, intent(in) :: lfill + type(pack77_state), target, optional, intent(inout) :: knowledge character*13 cw + if(present(knowledge)) then + if(lfill) then + call fold_queued_calls_for_state(knowledge,numthreads) + else + call prepare_configured_decode_for_state(knowledge,mycall,hiscall) + endif + return + endif + if(lfill) then ! End of a configured/var decode pass: merge per-thread successful decode ! effects into the shared callsign hash and recent-call state. diff --git a/lib/ft8var/four2avar.f90 b/lib/ft8var/four2avar.f90 index 1653955b..80ef88b3 100644 --- a/lib/ft8var/four2avar.f90 +++ b/lib/ft8var/four2avar.f90 @@ -22,7 +22,7 @@ subroutine four2avar(a,nfft,ndim,isign,iform) parameter (NPMAX=2100) !Max numberf of stored plans parameter (NSMALL=16385) !Max size of "small" FFTs complex a(nfft) !Array to be transformed - complex aa(NSMALL) !Local copy of "small" a() + complex, allocatable :: aa(:) !Local copy of "small" a() integer nn(NPMAX),ns(NPMAX),nf(NPMAX) !Params of stored plans integer*8 nl(NPMAX),nloc !More params of plans integer*8 plan(NPMAX) !Pointers to stored plans @@ -76,6 +76,7 @@ subroutine four2avar(a,nfft,ndim,isign,iform) if(nfft.le.NSMALL) then jz=nfft if(iform.le.0) jz=nfft/2+1 + allocate(aa(jz)) aa(1:jz)=a(1:jz) endif diff --git a/lib/ft8var/ft8_decodevar.f90 b/lib/ft8var/ft8_decodevar.f90 index d7324216..4a76ed34 100644 --- a/lib/ft8var/ft8_decodevar.f90 +++ b/lib/ft8var/ft8_decodevar.f90 @@ -1,24 +1,60 @@ module ft8_decodevar + use packjt77, only: pack77_state + use decoder_engine_types, only: ft8_signal_evidence + use ft8var_work_types logical ltry_a8 type :: ft8_decodervar procedure(ft8_decodevar_callback), pointer :: callback + type(pack77_state), pointer :: knowledge => null() contains procedure :: decodevar end type ft8_decodervar abstract interface - subroutine ft8_decodevar_callback (this,snr,dt,freq,decodedvar,nap,qual) - import ft8_decodervar + subroutine ft8_decodevar_callback (this,snr,dt,freq,decodedvar,nap,qual,evidence) + import ft8_decodervar,ft8_signal_evidence implicit none class(ft8_decodervar), intent(inout) :: this integer, intent(in) :: snr integer, intent(in) :: nap real, intent(in) :: dt,freq,qual character(len=37), intent(in) :: decodedvar !ft8md was 26 + type(ft8_signal_evidence), intent(in), optional :: evidence end subroutine ft8_decodevar_callback end interface + interface + subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & + lsubtract,tmpcqdec,tmpmyc,nagainfil,iaptype,f1,xdt,nbadcrc,lft8sdec, & + msg37,msg37_2,xsnr,stophint,nthr,lFreeText,ipass,lft8subpass,lspecial, & + lcqcand,ncqsignal,nmycsignal,npass,i3bit,lft8s,lmycallstd,lhiscallstd, & + levenint,loddint,lft8sd,i3,n3,nft8rxfsens,ncount,msgsrcvd,lrepliedother, & + lhashmsg,lqsothread,lft8lowth,lhighsens,tmpcqsig,tmpmycsig,tmpqsosig, & + lnohiscall,lnomycall,lnohisgrid,qual,iaptype2,progress_generation,knowledge,evidence) + import pack77_state,ft8_signal_evidence,tmpcqdec_struct,tmpmyc_struct, & + tmpcqsig_struct,tmpmycsig_struct,tmpqsosig_struct + real :: residual(180000),f1,xdt,xsnr,qual + complex :: spectrum(0:96000) + integer :: nQSOProgress,nfqso,nftx,napwid,iaptype,nbadcrc,nthr,ipass + integer :: ncqsignal,nmycsignal,npass,i3bit,i3,n3,nft8rxfsens,ncount + integer :: iaptype2,progress_generation + logical :: newdat1,lsubtract,nagainfil,lFreeText,lspecial + logical(kind=1) :: lft8sdec,stophint,lft8subpass,lcqcand,lft8s + logical(kind=1) :: lmycallstd,lhiscallstd,levenint,loddint,lft8sd + logical(kind=1) :: lrepliedother,lhashmsg,lqsothread,lft8lowth,lhighsens + logical(kind=1) :: lnohiscall,lnomycall,lnohisgrid + character(len=37) :: msg37,msg37_2,msgsrcvd(130) + type(tmpcqdec_struct) :: tmpcqdec(*) + type(tmpmyc_struct) :: tmpmyc(*) + type(tmpcqsig_struct) :: tmpcqsig(*) + type(tmpmycsig_struct) :: tmpmycsig(*) + type(tmpqsosig_struct) :: tmpqsosig(*) + type(pack77_state), target, optional, intent(inout) :: knowledge + type(ft8_signal_evidence), optional, intent(out) :: evidence + end subroutine ft8bvar + end interface + contains subroutine decodevar(this,nQSOProgress,nfqso,nft8rxfsens,nftx, & @@ -27,6 +63,7 @@ contains progress_generation,residual,spectrum) use omp_lib + use ft8_codec_context, only: get_ft8_codec_state use ft8_mtd_residual, only : mtd_publish_worker,mtd_transform_phase use decode_completion_module, only : write_decode_progress @@ -66,6 +103,8 @@ contains character msg37*37,msg37_2*37,msg26*37,call2*12 !ft8md msg26 was *26 character*37 msgsrcvd(130) integer nsnr + type(pack77_state), pointer :: codec + type(ft8_signal_evidence) :: evidence type oddtmp_struct real freq @@ -83,39 +122,14 @@ contains end type eventmp_struct type(eventmp_struct) eventmp(130) - type tmpcqdec_struct - real freq - real xdt - end type tmpcqdec_struct type(tmpcqdec_struct) tmpcqdec(numdeccq) ! 40 sigs - - type tmpcqsig_struct - real freq - real xdt - complex cs(0:7,79) - end type tmpcqsig_struct type(tmpcqsig_struct), allocatable :: tmpcqsig(:) ! 20 sigs - - type tmpmyc_struct - real freq - real xdt - end type tmpmyc_struct type(tmpmyc_struct) tmpmyc(numdecmyc) ! 25 sigs - - type tmpmycsig_struct - real freq - real xdt - complex cs(0:7,79) - end type tmpmycsig_struct type(tmpmycsig_struct) tmpmycsig(nummycsig) ! 5 sigs - - type tmpqsosig_struct - real freq - real xdt - complex cs(0:7,79) - end type tmpqsosig_struct type(tmpqsosig_struct) tmpqsosig(1) + codec => this%knowledge + if(.not.associated(codec)) codec => get_ft8_codec_state() allocate(tmpcqsig(numcqsig)) oddtmp%lstate=.false. eventmp%lstate=.false. @@ -262,7 +276,7 @@ contains nft8rxfsens,ncount,msgsrcvd,lrepliedother,lhashmsg,lqsothread, & lft8lowth,lhighsens,tmpcqsig,tmpmycsig,tmpqsosig, & lnohiscall,lnomycall,lnohisgrid,qual,iaptype2, & - progress_generation) + progress_generation,codec,evidence) nsnr=nint(xsnr) xdt=xdt-0.5 if(nbadcrc.eq.0) then @@ -328,7 +342,7 @@ contains if(.not.lhidemsg) then msg26=msg37(1:37) !ft8md was 1:26 if(associated(this%callback)) then - call this%callback(nsnr,xdt,f1,msg26,iaptype2,qual) + call this%callback(nsnr,xdt,f1,msg26,iaptype2,qual,evidence) endif endif diff --git a/lib/ft8var/ft8_mod1.f90 b/lib/ft8var/ft8_mod1.f90 index cd1f0d2c..435a1957 100644 --- a/lib/ft8var/ft8_mod1.f90 +++ b/lib/ft8var/ft8_mod1.f90 @@ -209,4 +209,54 @@ module ft8_mod1 end type oddqso_struct type(oddqso_struct) oddqso(1,nmaxthreads) +contains + + subroutine reset_ft8_mod1() + dd8=0. + allmessages='' + allfreq=0. + allsnrs=0 + ndecodes=0 + nmsg=0 + nintcount=0 + nft8cycles=0 + nlasttx=0 + sumxdtt=0. + avexdt=0. + lastrxmsg%lstate=.false. + lastrxmsg%lastmsg='' + lastrxmsg%xdt=0. + odd%lstate=.false. + even%lstate=.false. + oddcopy%lstate=.false. + evencopy%lstate=.false. + odd%msg='' + even%msg='' + oddcopy%msg='' + evencopy%msg='' + calldteven%call2='' + calldtodd%call2='' + calldteven%dt=0. + calldtodd%dt=0. + incall%msg='' + incall%xdt=0. + msgroot='' + msgincall='' + xdtincall=0. + nincallthr=0 + ncandallthr=0 + idtone25_valid=.false. + idtone56_valid=.false. + idtone76_valid=.false. + csyncsd_valid=.false. + csyncsdcq_valid=.false. + first_osd=.true. + lqsomsgdcd=.false. + lapmyc=.false. + lasthcall='' + mycall12_0='dummy' + mycall12_00='dummy' + hiscall12_0='dummy' + end subroutine reset_ft8_mod1 + end module ft8_mod1 diff --git a/lib/ft8var/ft8apsetvar.f90 b/lib/ft8var/ft8apsetvar.f90 index f23d604e..bffd2d9e 100644 --- a/lib/ft8var/ft8apsetvar.f90 +++ b/lib/ft8var/ft8apsetvar.f90 @@ -1,6 +1,7 @@ -subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) +subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads,knowledge) use packjt77 + use ft8_codec_context, only: get_ft8_codec_state use ft8_mod1, only : apsym,mycall,hiscall,apsymsp,lhound,apsymdxns1,apsymdxnsrrr,mybcall,hisbcall,apcqsym,hisgrid4, & apsymdxnsrr73,apsymdxns73,apsymmyns1,apsymmyns2,apsymmynsrr73,apsymmyns73,apsymdxstd,apsymdxnsr73, & apsymdxns732,apsymmynsrrr @@ -13,12 +14,25 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) logical(1), intent(in) :: lmycallstd,lhiscallstd type(unpack77_options) :: no_record_options type(pack77_options) :: no_tx_hash_options + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec data mycallprev/'QQ2QQ'/ data hiscallprev/'QQ1QQ'/ data lhoundprev/.false./ data first/.true./ save hiscallprev,mycallprev,lhoundprev,first + go to 900 +entry reset_ft8apsetvar() + hiscallprev='QQ1QQ' + mycallprev='QQ2QQ' + lhoundprev=.false. + first=.true. + return +900 continue + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge + i1=0 i3=-1 n3=-1 @@ -34,7 +48,7 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) first=.false.; mycallprev=mycall; lhoundprev=lhound ! shall hash both callsigns for making AP masks with nonstandard callsign message - if(.not.lhound) call fillhashvar(numthreads,.true.) + if(.not.lhound) call fold_queued_calls_for_state(codec,numthreads) lnohiscall=.false. hiscallt=hiscall @@ -51,8 +65,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) else; msg='CQ '//trim(hiscall) endif - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(lhiscallstd .and. i3.ne.1 .or. .not.lhiscallstd .and. i3.ne.4 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 1 read(c77,'(77i1)',err=1) apcqsym(1:77) @@ -62,8 +76,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) if(lhiscallstd .and. .not.lmycallstd) then msg=trim(hiscall)//' '//trim(hiscall)//' RRR' i3=0; n3=0 - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.1 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 2 read(c77,'(58i1)',err=2) apsymdxstd(1:58) @@ -73,16 +87,16 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) if(.not.lhound .and. .not.lhiscallstd .and. len_trim(hiscall).gt.2) then ! nonstandard DXCall searching msg='<W9XYZ> '//trim(hiscall)//' RR73' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.4 .or. .not.unpk77_successvar) go to 3 read(c77,'(77i1)',err=3) apsymdxnsrr73(1:77) apsymdxnsrr73=2*apsymdxnsrr73-1 msg='<W9XYZ> '//trim(hiscall)//' 73' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.4 .or. .not.unpk77_successvar) go to 4 read(c77,'(77i1)',err=4) apsymdxns73(1:77) @@ -93,28 +107,28 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) if(.not.lhound .and. .not.lmycallstd .and. len_trim(mycall).gt.2) then if(lhiscallstd) then msg='<'//trim(mycall)//'> '//trim(hiscall)//' -15' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) if(i3.ne.1 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 5 read(c77,'(58i1)',err=5) apsymmyns2(1:58) apsymmyns2=2*apsymmyns2-1 nlenmyc=len_trim(mycall) msg=trim(mycall)//' <'//trim(hiscall)//'> RR73' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 6 read(c77,'(77i1)',err=6) apsymmynsrr73(1:77) apsymmynsrr73=2*apsymmynsrr73-1 msg=trim(mycall)//' <'//trim(hiscall)//'> 73' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 7 read(c77,'(77i1)',err=7) apsymmyns73(1:77) apsymmyns73=2*apsymmyns73-1 msg=trim(mycall)//' <'//trim(hiscall)//'> RRR' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 15 read(c77,'(77i1)',err=15) apsymmynsrrr(1:77) apsymmynsrrr=2*apsymmynsrrr-1 @@ -122,8 +136,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) else if(lnohiscall) then msg='<'//trim(mycall)//'> ZZ1ZZZ -15' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) if(i3.ne.1 .or. msgchk.ne.msg .or. .not.unpk77_successvar) go to 8 read(c77,'(29i1)',err=8) apsymmyns1(1:29) apsymmyns1=2*apsymmyns1-1 @@ -135,8 +149,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) if(.not.lhound .and. lmycallstd .and. (lhiscallstd .or. lnohiscall)) then msg=trim(mycall)//' '//trim(hiscallt)//' RRR' i3=0; n3=0 - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.1 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 9 read(c77,'(58i1)',err=9) apsym(1:58) @@ -147,8 +161,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) ! standard messages from Fox, always base callsigns if(len_trim(hisbcall).gt.2 .and. len_trim(mybcall).gt.2) then msg=trim(mybcall)//' '//trim(hisbcall)//' -15' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.1 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 9 read(c77,'(58i1)',err=9) apsym(1:58) @@ -160,8 +174,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) ! special messages msg=trim(mycall)//' RR73; '//trim(mycall)//' <'//trim(hiscallt)//'> -16' i3=0; n3=1 - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk i1=0; i1=index(msgchk,'<'); if(i1.lt.15) return if(i3.ne.0 .or. msg(1:i1).ne.msgchk(1:i1) .or. .not.unpk77_successvar) go to 10 @@ -171,32 +185,32 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads) if(.not.lhound .and. lmycallstd .and. .not.lhiscallstd .and. len_trim(hiscall).gt.2) then msg=trim(mycall)//' <'//trim(hiscall)//'> -16' ! report, rreport - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.1 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 11 read(c77,'(58i1)',err=11) apsymdxns1(1:58) apsymdxns1=2*apsymdxns1-1 msg='<'//trim(mycall)//'> '//trim(hiscall)//' RRR' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 12 read(c77,'(77i1)',err=12) apsymdxnsrrr(1:77) apsymdxnsrrr=2*apsymdxnsrrr-1 msg='<'//trim(mycall)//'> '//trim(hiscall)//' RR73' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 13 read(c77,'(77i1)',err=13) apsymdxnsr73(1:77) apsymdxnsr73=2*apsymdxnsr73-1 msg='<'//trim(mycall)//'> '//trim(hiscall)//' 73' - call pack77(msg,i3,n3,c77,no_tx_hash_options) - call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options) + call pack77_for_state(codec,msg,i3,n3,c77,no_tx_hash_options) + call unpack77_configured_for_state(codec,c77,1,msgchk,unpk77_successvar,no_record_options) !read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 14 read(c77,'(77i1)',err=14) apsymdxns732(1:77) diff --git a/lib/ft8var/ft8bvar.f90 b/lib/ft8var/ft8bvar.f90 index caf1d94c..5e774347 100644 --- a/lib/ft8var/ft8bvar.f90 +++ b/lib/ft8var/ft8bvar.f90 @@ -5,9 +5,14 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & nmycsignal,npass,i3bit,lft8s,lmycallstd,lhiscallstd,levenint,loddint,lft8sd, & i3,n3,nft8rxfsens,ncount,msgsrcvd,lrepliedother,lhashmsg,lqsothread, & lft8lowth,lhighsens,tmpcqsig,tmpmycsig,tmpqsosig,lnohiscall, & - lnomycall,lnohisgrid,qual,iaptype2,progress_generation) - - use packjt77, only : unpack77, unpack77_configured, unpack77_options + lnomycall,lnohisgrid,qual,iaptype2,progress_generation,knowledge,evidence) + + use packjt77, only : pack77_state,unpack77_configured_for_state,unpack77_options + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: ft8sd1var,ft8sdvar,ft8svar,ft8mfcqvar,tonesdvar, & + ft8var_tones_from_77bits + use ft8var_work_types + use decoder_engine_types, only: ft8_signal_evidence,engine_payload_decoded use ft8_mtd_residual, only : mtd_commit_subtraction,mtd_mark_spectrum_current, & mtd_refresh_candidate use decode_completion_module, only : write_decode_progress @@ -56,40 +61,24 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & lcqdxcsig,lcqdxcnssig,lqsocandave,lcall1hash,lqsosigtype3,lqso73,lqsorr73, & lqsorrr,lfoxspecrpt,lfoxstdr73,lapcqonly,lcall2hash,lskipnotap integer iaptype2 + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + type(ft8_signal_evidence), optional, intent(out) :: evidence + character(len=37) :: decoded_payload_message + logical :: has_decoded_payload - type tmpcqdec_struct - real freq - real xdt - end type tmpcqdec_struct type(tmpcqdec_struct) tmpcqdec(numdeccq) - - type tmpcqsig_struct - real freq - real xdt - complex cs(0:7,79) - end type tmpcqsig_struct type(tmpcqsig_struct) tmpcqsig(numcqsig) ! 20 sigs 24 threads - - type tmpmyc_struct - real freq - real xdt - end type tmpmyc_struct type(tmpmyc_struct) tmpmyc(numdecmyc) - - type tmpmycsig_struct - real freq - real xdt - complex cs(0:7,79) - end type tmpmycsig_struct type(tmpmycsig_struct) tmpmycsig(nummycsig) ! 5 sigs - - type tmpqsosig_struct - real freq - real xdt - complex cs(0:7,79) - end type tmpqsosig_struct type(tmpqsosig_struct) tmpqsosig(1) + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge + if(present(evidence)) evidence=ft8_signal_evidence() + has_decoded_payload=.false. + decoded_payload_message='' + itone=0 iaptype2 = 99 !ft8md max_iterations=30 @@ -256,7 +245,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & cd0=cd3 endif if(iqso.eq.4) then - call tonesdvar(msgd,lcq) + call tonesdvar(msgd,lcq,codec) if(.not.ldeepsync) go to 32 cd0=cd1 endif @@ -732,7 +721,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & 32 if(lsd) then if(iqso.eq.4 .and. .not.ldeepsync) go to 64 - call ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq) + call ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq,codec) if(lft8sd) then if(levenint) then evencopy(isd)%lstate=.false. @@ -766,7 +755,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & go to 2 endif else - call ft8mfcqvar(s8,itone,msgd,msg37,lft8sd) + call ft8mfcqvar(s8,itone,msgd,msg37,lft8sd,codec) if(lft8sd) then if(levenint) then evencopy(isd)%lstate=.false. @@ -812,7 +801,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & if(.not.lqsomsgdcd .and. .not.(.not.lmycallstd .and. .not.lhiscallstd)) then if(.not.lft8sdec .and. dfqso.lt.2.0) then if(lvirtual2 .or. lvirtual3) srr=0.0 - call ft8svar(s82,srr,itone,msg37,lft8s,nft8rxfsens,stophint) + call ft8svar(s82,srr,itone,msg37,lft8s,nft8rxfsens,stophint,codec) if(lft8s) then if(index(msg37,'<').gt.0) then lhashmsg=.true. @@ -2176,7 +2165,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & if(.not.lqsomsgdcd .and. .not.(.not.lmycallstd .and. & .not.lhiscallstd)) then if(.not.lft8sdec .and. .not.stophint .and. dfqso.lt.2.0) then - call ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint) + call ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint,codec) if(lft8s) then if(index(msg37,'<').gt.0) then lhashmsg=.true. @@ -2195,7 +2184,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & endif if(lsd .and. isubp2.eq.3 .and. nbadcrc.eq.1 .and. srr.lt.7.0) then ! low DR setups shall not try FT8SDvar for strong signals - call ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq) + call ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq,codec) if(lft8sd) then if(levenint) then evencopy(isd)%lstate=.false. @@ -2275,7 +2264,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & ! and n3.eq.5 for USA calls with EU VHF ! added .or. n3.eq.2 .or. n3.eq.8 .or. n3.eq.9 as test for EU VHF !print*,'did not cycle at line 2248' - call unpack77_configured(c77,1,msg37,unpk77_successvar, & + call unpack77_configured_for_state(codec,c77,1,msg37,unpk77_successvar, & unpack77_options(thread_index=nthr)) if(.not.unpk77_successvar) then if(lqsothread .and. (.not.lhound .and. iaptype.ge.3 .or. lhound .and. & @@ -2283,7 +2272,7 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & if(.not.lqsomsgdcd .and. .not.(.not.lmycallstd .and. & .not.lhiscallstd)) then if(.not.lft8sdec .and. .not.stophint .and. dfqso.lt.2.0) then - call ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint) + call ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint,codec) if(lft8s) then if(index(msg37,'<').gt.0) then lhashmsg=.true. @@ -2310,7 +2299,10 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & lcall1hash=.false. if(msg37(1:1).eq.'<') lcall1hash=.true. nbadcrc=0 ! If we get this far: valid codeword, valid (i3,n3), nonquirky message. - call get_tones_from_77bits(message77,itone) + call ft8var_tones_from_77bits(message77,itone) + has_decoded_payload=.true. + decoded_payload_message=msg37 + if(present(evidence)) evidence%payload77=message77 ! 0.1 K1ABC RR73; W9XYZ <KH1/KH7Z> -11 28 28 10 5 71 DXpedition Mode i3bit=0 if(i3.eq.0 .and. n3.eq.1) i3bit=1 @@ -2956,6 +2948,17 @@ subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, & endif endif + if(present(evidence) .and. nbadcrc.eq.0) then + if(all(itone(1:7).eq.icos7)) then + evidence%tones=int(itone,kind=1) + evidence%has_tones=1 + endif + evidence%has_waveform_start=1 + evidence%waveform_start_seconds=xdt + evidence%method=iaptype2 + if(has_decoded_payload .and. msg37.eq.decoded_payload_message) & + evidence%payload_origin=engine_payload_decoded + endif return end subroutine ft8bvar diff --git a/lib/ft8var/ft8mfcqvar.f90 b/lib/ft8var/ft8mfcqvar.f90 index bd58058e..52662227 100644 --- a/lib/ft8var/ft8mfcqvar.f90 +++ b/lib/ft8var/ft8mfcqvar.f90 @@ -1,5 +1,9 @@ -subroutine ft8mfcqvar(s8,itone,msgd,msg37,lft8sd) +subroutine ft8mfcqvar(s8,itone,msgd,msg37,lft8sd,knowledge) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8sdvar_for_state use ft8_mod1, only : idtone25,idtone25_valid real, intent(in) :: s8(0:7,79) @@ -8,12 +12,17 @@ subroutine ft8mfcqvar(s8,itone,msgd,msg37,lft8sd) integer itone(79),mrs(58),mrs2(58) integer*1 msgbits(77) logical(1) lft8sd + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge if(len_trim(msgd).lt.6) return idtone25(1,1:58)=0 idtone25_valid(1)=.false. i3=-1; n3=-1 - call genft8sdvar(msgd,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msgd,i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) return idtone25(1,1:29)=itone(8:36) idtone25(1,30:58)=itone(44:72) diff --git a/lib/ft8var/ft8sd1var.f90 b/lib/ft8var/ft8sd1var.f90 index 3c6fd2c5..b5260fbd 100644 --- a/lib/ft8var/ft8sd1var.f90 +++ b/lib/ft8var/ft8sd1var.f90 @@ -1,4 +1,8 @@ -subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq) +subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq,knowledge) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8sdvar_for_state use ft8_mod1, only : mycall real, intent(in) :: s8(0:7,79) @@ -10,6 +14,11 @@ subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq) integer*1 msgbits(77) logical(1), intent(in) :: lcq logical(1) lft8sd,lr73,lgrid,lmatched(58),valid4(4) + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge lmatched=.false.; lr73=.false.; lgrid=.false. itonedem=11 @@ -40,7 +49,7 @@ subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq) if(lcq .or. lgrid .or. lr73) then i3=-1; n3=-1 msg372=msgd - call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msg372,i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) return idtone(1:29)=itone(8:36) idtone(30:58)=itone(44:72) @@ -49,7 +58,7 @@ subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq) do i=1,4 msg372=msg4(i) i3=-1; n3=-1 - call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msg372,i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) cycle valid4(i)=.true. idtone4(i,1:29)=itone(8:36) diff --git a/lib/ft8var/ft8sdvar.f90 b/lib/ft8var/ft8sdvar.f90 index f6332e64..8eaf7e9a 100644 --- a/lib/ft8var/ft8sdvar.f90 +++ b/lib/ft8var/ft8sdvar.f90 @@ -1,4 +1,8 @@ -subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq) +subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq,knowledge) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8sdvar_for_state use ft8_mod1, only : mycall real, intent(in) :: s8(0:7,79) @@ -10,6 +14,11 @@ subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq) integer*1 msgbits(77) logical(1), intent(in) :: lcq logical(1) lft8sd,lmatched(58),valid4(4) + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge if(index(msgd,' RR73').gt.0 .or. index(msgd,' 73').gt.0) return ! do not process 73 messages ! do not process messages with grid @@ -38,7 +47,7 @@ subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq) if(lcq) then i3=-1; n3=-1 msg372=msgd - call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msg372,i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) return idtone(1:29)=itone(8:36) idtone(30:58)=itone(44:72) @@ -47,7 +56,7 @@ subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq) do i=1,4 msg372=msg4(i) i3=-1; n3=-1 - call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msg372,i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) cycle valid4(i)=.true. idtone4(i,1:29)=itone(8:36) diff --git a/lib/ft8var/ft8svar.f90 b/lib/ft8var/ft8svar.f90 index 1d0cc4fc..b8eb3aab 100644 --- a/lib/ft8var/ft8svar.f90 +++ b/lib/ft8var/ft8svar.f90 @@ -1,5 +1,9 @@ -subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint) +subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint,knowledge) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8sdvar_for_state use ft8_mod1, only : itone56,idtone56,msg,nlasttx,lastrxmsg,mycall,hiscall, & idtone56_valid @@ -14,6 +18,11 @@ subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint) logical(1), intent(in) :: stophint logical(1), intent(out) :: lft8s logical(1) lmatched(58),lmycall,lhiscall,lrrr,lr73,lcallingrprt,lastrrprt,lastreport,lgrid + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge ! taken from ft8_mod1 ! integer itone56(56,79),idtone56(56,58) @@ -59,7 +68,7 @@ subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint) itone56(53,1:79)=0 idtone56_valid(53)=.false. i3=-1; n3=-1 - call genft8sdvar(lastrxmsg(1)%lastmsg,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,lastrxmsg(1)%lastmsg,i3,n3,msgsent37,msgbits,itone) if(i3.ge.0) then msg(53)=lastrxmsg(1)%lastmsg idtone56(53,1:29)=itone(8:36) diff --git a/lib/ft8var/genft8sdvar.f90 b/lib/ft8var/genft8sdvar.f90 index ae2ca408..36eefda6 100644 --- a/lib/ft8var/genft8sdvar.f90 +++ b/lib/ft8var/genft8sdvar.f90 @@ -1,46 +1,14 @@ subroutine genft8sdvar(msg,i3,n3,msgsent,msgbits,itone) - -! Encode an FT8 message, producing array itone(). - - use packjt77 - use ft8_mod1, only : icos7,graymap - character msg*37,msgsent*37,c77*77 - integer*1 msgbits(77),codeword(174) - integer itone(79) - logical unpk77_successvar - - i3=-1 - n3=-1 - call pack77(msg,i3,n3,c77,pack77_options(record_tx_hashes=.false.)) - ! SD thresholds are calibrated for classic Type 1/2 templates only. - if(.not.(i3.ge.0 .and. (i3.eq.1 .or. i3.eq.2) .and. & - index(msg,'<').eq.0)) then - i3=-1 - n3=-1 - endif - if(i3.lt.0) go to 1 - call unpack77_configured(c77,0,msgsent,unpk77_successvar, & - unpack77_options(record_hashes=.false.,record_recent_calls=.false.)) - read(c77,'(77i1)',err=1) msgbits - if(unpk77_successvar) go to 2 -1 msgbits=0 - itone=0 - msgsent='*** bad message *** ' - go to 900 - -2 call encode174_91var(msgbits,codeword) !Encode the test message - -! Message structure: S7 D29 S7 D29 S7 - itone(1:7)=icos7; itone(37:43)=icos7; itone(73:79)=icos7 - k=7 - do j=1,58 - i=3*j -2 - k=k+1 - if(j.eq.30) k=k+7 - indx=codeword(i)*4 + codeword(i+1)*2 + codeword(i+2) - itone(k)=graymap(indx) - enddo - -900 return + use ft8var_codec_context, only: genft8sdvar_for_state + use ft8_codec_context, only: get_ft8_codec_state + use packjt77, only: pack77_state + implicit none + character(len=37), intent(in) :: msg + integer, intent(out) :: i3,n3,itone(79) + character(len=37), intent(out) :: msgsent + integer(kind=1), intent(out) :: msgbits(77) + type(pack77_state), pointer :: state + state => get_ft8_codec_state() + call genft8sdvar_for_state(state,msg,i3,n3,msgsent,msgbits,itone) end subroutine genft8sdvar diff --git a/lib/ft8var/genft8var.f90 b/lib/ft8var/genft8var.f90 index 86defc7e..3d901bce 100644 --- a/lib/ft8var/genft8var.f90 +++ b/lib/ft8var/genft8var.f90 @@ -1,39 +1,174 @@ -subroutine genft8var(msg,i3,n3,ntxhash,msgsent,msgbits,itone) +module ft8var_work_types + implicit none + type :: tmpcqdec_struct + real :: freq,xdt + end type + type :: tmpcqsig_struct + real :: freq,xdt + complex :: cs(0:7,79) + end type + type :: tmpmyc_struct + real :: freq,xdt + end type + type :: tmpmycsig_struct + real :: freq,xdt + complex :: cs(0:7,79) + end type + type :: tmpqsosig_struct + real :: freq,xdt + complex :: cs(0:7,79) + end type +end module ft8var_work_types + +module ft8var_codec_context + use packjt77, only: pack77_state,pack77_for_state,unpack77_configured_for_state, & + pack77_options,unpack77_options + use ft8_codec_context, only: get_ft8_codec_state + use ft8_mod1, only: icos7,graymap + implicit none + private + public :: genft8var_for_state,genft8sdvar_for_state,ft8var_tones_from_77bits + public :: tonesdvar,ft8sd1var,ft8sdvar,ft8svar,ft8mfcqvar + + interface + subroutine tonesdvar(msgd,lcq,knowledge) + import pack77_state + character(len=37) :: msgd + logical(kind=1) :: lcq + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq,knowledge) + import pack77_state + real :: s8(0:7,79) + integer :: itone(79) + character(len=37) :: msgd,msg37 + logical(kind=1) :: lft8sd,lcq + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq,knowledge) + import pack77_state + real :: s8(0:7,79),srr + integer :: itone(79) + character(len=37) :: msgd,msg37 + logical(kind=1) :: lft8sd,lcq + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint,knowledge) + import pack77_state + real :: s8(0:7,79),srr + integer :: itone(79),nft8rxfsens + character(len=37) :: msg37 + logical(kind=1) :: lft8s,stophint + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + subroutine ft8mfcqvar(s8,itone,msgd,msg37,lft8sd,knowledge) + import pack77_state + real :: s8(0:7,79) + integer :: itone(79) + character(len=37) :: msgd,msg37 + logical(kind=1) :: lft8sd + type(pack77_state), target, optional, intent(inout) :: knowledge + end subroutine + end interface + +contains + + subroutine genft8var_for_state(state,msg,i3,n3,ntxhash,msgsent,msgbits,itone) + type(pack77_state), target, intent(inout) :: state + character(len=37), intent(in) :: msg + integer, intent(inout) :: i3,n3 + integer, intent(in) :: ntxhash + character(len=37), intent(out) :: msgsent + integer(kind=1), intent(out) :: msgbits(77) + integer, intent(out) :: itone(79) + character(len=77) :: c77 + logical :: unpacked + + call pack77_for_state(state,msg,i3,n3,c77,pack77_options(record_tx_hashes=ntxhash.eq.1)) + call unpack77_configured_for_state(state,c77,0,msgsent,unpacked, & + unpack77_options(record_hashes=.false.,record_recent_calls=.false.)) + read(c77,'(77i1)',err=10) msgbits + if(unpacked) then + call ft8var_tones_from_77bits(msgbits,itone) + return + endif +10 msgbits=0 + itone=0 + msgsent='*** bad message ***' + end subroutine genft8var_for_state -! Encode an FT8 message, producing array itone(). - - use packjt77 - use ft8_mod1, only : icos7,graymap - character msg*37,msgsent*37,c77*77 - integer*1 msgbits(77),codeword(174) - integer itone(79) - logical unpk77_successvar - - call pack77(msg,i3,n3,c77, & - pack77_options(record_tx_hashes=ntxhash.eq.1)) - call unpack77_configured(c77,0,msgsent,unpk77_successvar, & - unpack77_options(record_hashes=.false.,record_recent_calls=.false.)) - read(c77,'(77i1)',err=1) msgbits - if(unpk77_successvar) go to 2 -1 msgbits=0 - itone=0 - msgsent='*** bad message *** ' - go to 900 - -entry get_tones_from_77bits(msgbits,itone) - -2 call encode174_91var(msgbits,codeword) !Encode the test message - -! Message structure: S7 D29 S7 D29 S7 - itone(1:7)=icos7; itone(37:43)=icos7; itone(73:79)=icos7 - k=7 - do j=1,58 - i=3*j -2 - k=k+1 - if(j.eq.30) k=k+7 - indx=codeword(i)*4 + codeword(i+1)*2 + codeword(i+2) - itone(k)=graymap(indx) - enddo - -900 return + subroutine genft8sdvar_for_state(state,msg,i3,n3,msgsent,msgbits,itone) + type(pack77_state), target, intent(inout) :: state + character(len=37), intent(in) :: msg + integer, intent(out) :: i3,n3 + character(len=37), intent(out) :: msgsent + integer(kind=1), intent(out) :: msgbits(77) + integer, intent(out) :: itone(79) + character(len=77) :: c77 + logical :: unpacked + + i3=-1 + n3=-1 + call pack77_for_state(state,msg,i3,n3,c77,pack77_options(record_tx_hashes=.false.)) + if(.not.(i3.ge.0 .and. (i3.eq.1 .or. i3.eq.2) .and. index(msg,'<').eq.0)) then + i3=-1 + n3=-1 + endif + if(i3.ge.0) then + call unpack77_configured_for_state(state,c77,0,msgsent,unpacked, & + unpack77_options(record_hashes=.false.,record_recent_calls=.false.)) + read(c77,'(77i1)',err=20) msgbits + if(unpacked) then + call ft8var_tones_from_77bits(msgbits,itone) + return + endif + endif +20 msgbits=0 + itone=0 + msgsent='*** bad message ***' + end subroutine genft8sdvar_for_state + + subroutine ft8var_tones_from_77bits(msgbits,itone) + integer(kind=1), intent(in) :: msgbits(77) + integer, intent(out) :: itone(79) + integer(kind=1) :: codeword(174) + integer :: i,j,k,indx + + call encode174_91var(msgbits,codeword) + itone(1:7)=icos7 + itone(37:43)=icos7 + itone(73:79)=icos7 + k=7 + do j=1,58 + i=3*j-2 + k=k+1 + if(j.eq.30) k=k+7 + indx=codeword(i)*4+codeword(i+1)*2+codeword(i+2) + itone(k)=graymap(indx) + enddo + end subroutine ft8var_tones_from_77bits +end module ft8var_codec_context + +subroutine genft8var(msg,i3,n3,ntxhash,msgsent,msgbits,itone) + use ft8var_codec_context, only: genft8var_for_state + use ft8_codec_context, only: get_ft8_codec_state + use packjt77, only: pack77_state + implicit none + character(len=37), intent(in) :: msg + integer, intent(inout) :: i3,n3 + integer, intent(in) :: ntxhash + character(len=37), intent(out) :: msgsent + integer(kind=1), intent(out) :: msgbits(77) + integer, intent(out) :: itone(79) + type(pack77_state), pointer :: state + state => get_ft8_codec_state() + call genft8var_for_state(state,msg,i3,n3,ntxhash,msgsent,msgbits,itone) end subroutine genft8var + +subroutine get_tones_from_77bits(msgbits,itone) + use ft8var_codec_context, only: ft8var_tones_from_77bits + implicit none + integer(kind=1), intent(in) :: msgbits(77) + integer, intent(out) :: itone(79) + call ft8var_tones_from_77bits(msgbits,itone) +end subroutine get_tones_from_77bits diff --git a/lib/ft8var/partintft8.f90 b/lib/ft8var/partintft8.f90 index 6b696bad..7ef8ab8c 100644 --- a/lib/ft8var/partintft8.f90 +++ b/lib/ft8var/partintft8.f90 @@ -1,7 +1,12 @@ -subroutine partintft8(ndelay,nutc) +subroutine partintft8(ndelay,nutc,render_legacy) use ft8_mod1, only : dd8 real rnd + logical, optional, intent(in) :: render_legacy + logical :: emit_line + + emit_line=.true. + if(present(render_legacy)) emit_line=render_legacy if(ndelay.gt.120) ndelay=120 numsamp=nint(float(ndelay)*1200) @@ -10,9 +15,9 @@ subroutine partintft8(ndelay,nutc) call random_number(rnd) dd8(i)=10.0*rnd-5. enddo - write(*,2) nutc,'partial loss of data','d' + if(emit_line) write(*,2) nutc,'partial loss of data','d' 2 format(i6.6,2x,a20,21x,a1) - call flush(6) + if(emit_line) call flush(6) return -end subroutine partintft8
\ No newline at end of file +end subroutine partintft8 diff --git a/lib/ft8var/tone8.f90 b/lib/ft8var/tone8.f90 index 63e21e94..b2b61de8 100644 --- a/lib/ft8var/tone8.f90 +++ b/lib/ft8var/tone8.f90 @@ -1,4 +1,8 @@ -subroutine tone8(lmycallstd,lhiscallstd) +subroutine tone8(lmycallstd,lhiscallstd,knowledge) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8var_for_state use ft8_mod1, only : itone56,idtone56,msg,csynce,mycall,hiscall,idtonecqdxcns,idtonedxcns73,mybcall,hisbcall,lhound, & idtone56_valid, & @@ -9,6 +13,8 @@ subroutine tone8(lmycallstd,lhiscallstd) integer itone(79),itone1(79) integer*1 msgbits(77) logical(1), intent(in) :: lmycallstd,lhiscallstd + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec logical(1) valid_first data rpt/'-01 ','-02 ','-03 ','-04 ','-05 ','-06 ','-07 ','-08 ','-09 ','-10 ', & @@ -22,6 +28,8 @@ subroutine tone8(lmycallstd,lhiscallstd) ! integer itone56(56,79),idtone56(56,58) ! character*37 msg(56) + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge idtone56(1:56,1:58)=0 itone56(1:56,1:79)=0 idtone56_valid(1:56)=.false. @@ -30,12 +38,12 @@ subroutine tone8(lmycallstd,lhiscallstd) if(lhound .and. len_trim(mybcall).gt.2 .and. len_trim(hisbcall).gt.2) then msg37=''; msg37=trim(mybcall)//' '//trim(hisbcall)//' RR73' i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) idtonefox73(1:29)=itone(8:36) idtonefox73(30:58)=itone(44:72) msg37=''; msg37=trim(mybcall)//' RR73; '//trim(mybcall)//' <'//trim(hiscall)//'> -12' i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) idtonespec(1:29)=itone(8:36) idtonespec(30:58)=itone(44:72) endif @@ -43,12 +51,12 @@ subroutine tone8(lmycallstd,lhiscallstd) if(.not.lhiscallstd .and. len(trim(hiscall)).gt.2) then msg37=''; msg37='CQ '//trim(hiscall) i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) idtonecqdxcns(1:29)=itone(8:36) idtonecqdxcns(30:58)=itone(44:72) msg37=''; msg37='<AA1AAA> '//trim(hiscall)//' 73' i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) idtonedxcns73(1:29)=itone(8:36) idtonedxcns73(30:58)=itone(44:72) endif @@ -64,7 +72,7 @@ subroutine tone8(lmycallstd,lhiscallstd) msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i)) msg(i)=msg37 i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) call store_tone_slot(i,itone,i3.ge.0,i.eq.1) enddo go to 2 @@ -74,7 +82,7 @@ subroutine tone8(lmycallstd,lhiscallstd) do i=1,52 msg37=''; msg37=trim(mycall)//' '//trim(hiscall14)//' '//trim(rpt(i)) i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) call store_tone_slot(i,itone,i3.ge.0,i.eq.1) msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i)) msg(i)=msg37 @@ -82,7 +90,7 @@ subroutine tone8(lmycallstd,lhiscallstd) do i=54,56 msg37=''; msg37=trim(mycall14)//' '//trim(hiscall)//' '//trim(rpt(i)) i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) call store_tone_slot(i,itone,i3.ge.0,.false.) msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i)) msg(i)=msg37 @@ -90,7 +98,7 @@ subroutine tone8(lmycallstd,lhiscallstd) msg37=''; msg37=trim(mycall14)//' '//trim(hiscall) msg(53)=msg37 i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) call store_tone_slot(53,itone,i3.ge.0,.false.) go to 2 endif @@ -99,7 +107,7 @@ subroutine tone8(lmycallstd,lhiscallstd) do i=1,52 msg37=''; msg37=trim(mycall14)//' '//trim(hiscall)//' '//trim(rpt(i)) i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) call store_tone_slot(i,itone,i3.ge.0,i.eq.1) msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i)) msg(i)=msg37 @@ -107,7 +115,7 @@ subroutine tone8(lmycallstd,lhiscallstd) do i=54,56 msg37=''; msg37=trim(mycall)//' '//trim(hiscall14)//' '//trim(rpt(i)) i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) call store_tone_slot(i,itone,i3.ge.0,.false.) msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i)) msg(i)=msg37 @@ -115,7 +123,7 @@ subroutine tone8(lmycallstd,lhiscallstd) msg37=''; msg37=trim(mycall14)//' '//trim(hiscall) msg(53)=msg37 i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) call store_tone_slot(53,itone,i3.ge.0,.false.) go to 2 endif diff --git a/lib/ft8var/tone8myc.f90 b/lib/ft8var/tone8myc.f90 index 83f05568..f478a52b 100644 --- a/lib/ft8var/tone8myc.f90 +++ b/lib/ft8var/tone8myc.f90 @@ -1,13 +1,21 @@ -subroutine tone8myc() +subroutine tone8myc(knowledge) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8var_for_state use ft8_mod1, only : idtonemyc,mycall character msg37*37,msgsent37*37 integer itone(79) integer*1 msgbits(77) + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge msg37=''; msg37=trim(mycall)//' AA1AAA FN25' i3=-1; n3=-1 - call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone) + call genft8var_for_state(codec,msg37,i3,n3,0,msgsent37,msgbits,itone) idtonemyc(1:29)=itone(8:36); idtonemyc(30:58)=itone(44:72) return diff --git a/lib/ft8var/tonesdvar.f90 b/lib/ft8var/tonesdvar.f90 index 50d3cb00..462ce2b6 100644 --- a/lib/ft8var/tonesdvar.f90 +++ b/lib/ft8var/tonesdvar.f90 @@ -1,4 +1,8 @@ -subroutine tonesdvar(msgd,lcq) +subroutine tonesdvar(msgd,lcq,knowledge) + + use packjt77, only: pack77_state + use ft8_codec_context, only: get_ft8_codec_state + use ft8var_codec_context, only: genft8sdvar_for_state use ft8_mod1, only : csyncsd,csyncsdcq,itone76,idtone76,msgsd76, & idtone76_valid,csyncsd_valid,csyncsdcq_valid @@ -10,6 +14,8 @@ subroutine tonesdvar(msgd,lcq) integer*1 msgbits(77) logical(1), intent(in) :: lcq logical(1) lgrid,lr73,valid_first + type(pack77_state), target, optional, intent(inout) :: knowledge + type(pack77_state), pointer :: codec data rpt/'+09 ','+08 ','+07 ','+06 ','+05 ','+04 ','+03 ','+02 ','+01 ','+00 ', & '-01 ','-02 ','-03 ','-04 ','-05 ','-06 ','-07 ','-08 ','-09 ','-10 ', & @@ -25,6 +31,8 @@ subroutine tonesdvar(msgd,lcq) ! character*37 msgsd76(76) ! complex csyncsd(0:18,32),csyncsdcq(0:71,32) + codec => get_ft8_codec_state() + if(present(knowledge)) codec => knowledge lgrid=.false.; lr73=.false. valid_first=.false. idtone76(1:76,1:58)=0 @@ -39,7 +47,7 @@ subroutine tonesdvar(msgd,lcq) if(lcq) then msg37=msgd i3=-1; n3=-1 - call genft8sdvar(msg37,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msg37,i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) return else c1=' '; c2=' ' @@ -58,7 +66,7 @@ subroutine tonesdvar(msgd,lcq) msg37=trim(c1)//' '//trim(c2)//' '//trim(rpt(i)) msgsd76(i)=msg37 i3=-1; n3=-1 - call genft8sdvar(msg37,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msg37,i3,n3,msgsent37,msgbits,itone) if(i3.lt.0) cycle if(i.eq.1) then itone1=itone @@ -73,7 +81,7 @@ subroutine tonesdvar(msgd,lcq) msg37=trim(c1)//' '//trim(c2)//' '//trim(grid) msgsd76(76)=msg37 i3=-1; n3=-1 - call genft8sdvar(msg37,i3,n3,msgsent37,msgbits,itone) + call genft8sdvar_for_state(codec,msg37,i3,n3,msgsent37,msgbits,itone) if(i3.ge.0) then idtone76(76,1:29)=itone(8:36) idtone76(76,30:58)=itone(44:72) diff --git a/lib/ftrsd/ftrsdap.c b/lib/ftrsd/ftrsdap.c index b2b85ddd..6f028d44 100644 --- a/lib/ftrsd/ftrsdap.c +++ b/lib/ftrsd/ftrsdap.c @@ -53,7 +53,7 @@ void ftrsdap_(int mrsym[], int mrprob[], int mr2sym[], int mr2prob[], // Initialize the KA9Q Reed-Solomon encoder/decoder unsigned int symsize=6, gfpoly=0x43, fcr=3, prim=1, nroots=51; - rs=init_rs_int(symsize, gfpoly, fcr, prim, nroots, 0); + if (!rs) rs=init_rs_int(symsize, gfpoly, fcr, prim, nroots, 0); // Reverse the received symbol vectors for BM decoder for (i=0; i<63; i++) { diff --git a/lib/get_q3list.f90 b/lib/get_q3list.f90 index d9b66e2d..2987b574 100644 --- a/lib/get_q3list.f90 +++ b/lib/get_q3list.f90 @@ -1,92 +1,61 @@ -subroutine get_q3list(fname,bDiskData,nlist,list) +subroutine get_q3list(fname,bDiskData,capacity,nlist,list) + use types, only: q3list + use, intrinsic :: iso_fortran_env, only: int64 + use q65_callers, only: Q65_MAX_CALLERS, Q65_ROW_WIDTH, & + q65_load_callers, q65_expire_callers use jpl_ephemeris_status, only: EPHEMERIS_INVALID_INPUT, & EPHEMERIS_UNAVAILABLE + implicit none - type q3list - character*6 call - character*4 grid - integer nsec - integer nfreq - integer moonel - end type q3list - - parameter (MAX_CALLERS=50) - character*(*) fname - character*37 list(MAX_CALLERS) - character*8 grid6 - logical*1 bDiskData - integer time - integer nt(8) - integer utc_year,utc_month,utc_day - integer ephemeris_result - integer indx(MAX_CALLERS) - type(q3list) ctmp(MAX_CALLERS),callers(MAX_CALLERS) - character*256 jpleph_file_name,file24name - common/jplcom/jpleph_file_name - common/lu24com/file24name - - nhist2=0 - open(24,file=fname,status='unknown',form='unformatted') - read(24,end=1) nhist2 - if(nhist2.ge.1 .and. nhist2.le.MAX_CALLERS) then - read(24,end=1) ctmp(1:nhist2) - else - nhist2=0 - endif -1 rewind 24 - if(nhist2.eq.0) go to 900 - + character(len=*), intent(in) :: fname + logical*1, intent(in) :: bDiskData + integer, intent(in) :: capacity + integer, intent(out) :: nlist + character(len=*), intent(inout) :: list(*) + character(len=8) :: grid6 + integer :: nt(8),now,nhist,status,i,j,mjd + integer :: utc_year,utc_month,utc_day,ephemeris_result + integer :: indx(Q65_MAX_CALLERS) + real :: uth,xlon,xlat,RASun,DecSun,xLST,AzSun,ElSun,day + real :: RAMoon,DecMoon,HA,AzMoon,ElMoon,vr,techo,age + type(q3list) :: history(Q65_MAX_CALLERS),callers(Q65_MAX_CALLERS) + + nlist=0 + if(capacity.le.0 .or. len(list).lt.Q65_ROW_WIDTH) return + call q65_load_callers(fname,history,nhist,status) + if(status.ne.0 .or. nhist.eq.0) return now=time() + call q65_expire_callers(history,nhist,now) call date_and_time(values=nt) call normalize_utc_calendar(nt,utc_year,utc_month,utc_day,uth) - j=0 - - do i=1,nhist2 - age=(now - ctmp(i)%nsec)/3600.0 - if(age.gt.24.0) cycle - grid6=ctmp(i)%grid//'mm' + + do i=1,nhist + grid6=history(i)%grid//'mm' call grid2deg(grid6,xlon,xlat) - call sun(utc_year,utc_month,utc_day,uth,-xlon,xlat,RASun,DecSun, & + call sun(utc_year,utc_month,utc_day,uth,-xlon,xlat,RASun,DecSun, & xLST,AzSun,ElSun,mjd,day) - call moondopjpl(utc_year,utc_month,utc_day,uth,-xlon,xlat,RAMoon, & - DecMoon, & - xLST,HA,AzMoon,ElMoon,vr,techo,ephemeris_result) + call moondopjpl(utc_year,utc_month,utc_day,uth,-xlon,xlat,RAMoon, & + DecMoon,xLST,HA,AzMoon,ElMoon,vr,techo,ephemeris_result) if(ephemeris_result.eq.EPHEMERIS_INVALID_INPUT .or. & ephemeris_result.eq.EPHEMERIS_UNAVAILABLE) cycle if(ElMoon.lt.-5.0 .and. (.not.bDiskData)) cycle - j=j+1 !Keep this one... - callers(j)=ctmp(i) - callers(j)%moonel=nint(ElMoon) !... and save its current moonel + nlist=nlist+1 + callers(nlist)=history(i) + callers(nlist)%moonel=nint(ElMoon) enddo - nhist2=j - write(24) nhist2 - write(24) callers(1:nhist2) - - call indexx(callers(1:nhist2)%nfreq,nhist2,indx) - do i=1,nhist2 + if(nlist.eq.0) return + call indexx(callers(1:nlist)%nfreq,nlist,indx) + nlist=min(nlist,capacity) + do i=1,nlist j=indx(i) - moon_el=nint(ElMoon) - age=(now - callers(j)%nsec)/3600.0 - write(list(i),1000) i,callers(j)%nfreq,callers(j)%call, & + age=real(int(now,int64)-int(callers(j)%nsec,int64))/3600.0 + write(list(i),1000) i,callers(j)%nfreq,callers(j)%call, & callers(j)%grid,callers(j)%moonel,age,char(0) 1000 format(i2,'.',i6,2x,a6,2x,a4,i5,f7.1,1x,a1) - -! h1=mod(now,86400)/3600.0 -! h2=mod(callers(i)%nsec,86400)/3600.0 -! hd=h1-h2 -! if(hd.lt.0.0) hd=hd+24.0 -! write(*,3301) i,callers(i)%call,now,callers(i)%nsec,h1,h2,hd -!3301 format(i3,2x,a6,2i12,3f10.6) - enddo -900 close(24) - nlist=nhist2 - file24name=fname - - return end subroutine get_q3list subroutine normalize_utc_calendar(values,year,month,day,uth) @@ -150,47 +119,22 @@ contains end subroutine normalize_utc_calendar -subroutine rm_q3list(dxcall0) - - parameter (MAX_CALLERS=50) - type q3list - character*6 call - character*4 grid - integer nsec - integer nfreq - integer moonel - end type q3list - character*(*) dxcall0 - character*6 dxcall - character*256 file24name - type(q3list) callers(MAX_CALLERS) - common/lu24com/file24name - - dxcall=dxcall0 - open(24,file=trim(file24name),status='unknown',form='unformatted') - read(24) nhist2 - read(24) callers(1:nhist2) - - if(nhist2.eq.MAX_CALLERS .and. dxcall.eq.callers(nhist2)%call) then - nhist2=MAX_CALLERS - 1 - go to 10 - endif +subroutine rm_q3list(fname,dxcall) - iz=nhist2 - do i=1,iz - if(callers(i)%call .eq. dxcall) then - nhist2=nhist2-1 - callers(i:nhist2)=callers(i+1:nhist2+1) !Remove dxcall from q3list - exit - endif - enddo + use types, only: q3list + use q65_callers, only: Q65_MAX_CALLERS, q65_load_callers, & + q65_save_callers, q65_remove_caller + implicit none -10 rewind 24 - write(24) nhist2 - write(24) callers(1:nhist2) - close(24) + character(len=*), intent(in) :: fname,dxcall + type(q3list) :: callers(Q65_MAX_CALLERS) + integer :: count,status + + call q65_load_callers(fname,callers,count,status) + if(status.ne.0) return + call q65_remove_caller(callers,count,dxcall) + call q65_save_callers(fname,callers,count,status) - return end subroutine rm_q3list subroutine jpl_setup(fname) diff --git a/lib/hint65.f90 b/lib/hint65.f90 index 00eaf40c..97efd851 100644 --- a/lib/hint65.f90 +++ b/lib/hint65.f90 @@ -1,23 +1,16 @@ subroutine hint65(s3,mrs,mrs2,nadd,nflip,mycall,hiscall,hisgrid,qual,decoded) use packjt - use prog_args + use jt65_mod, only: jt65_work,ensure_jt65_workspace parameter (MAXCALLS=10000,MAXRPT=63) - parameter (MAXMSG=2*MAXCALLS + 2 + MAXRPT) + parameter (MAXMSG=2*MAXCALLS + 3 + MAXRPT) real s3(64,63) - integer*1 sym1(0:62,MAXMSG) - integer*1 sym2(0:62,MAXMSG) integer mrs(63),mrs2(63) - integer dgen(12),sym(0:62),sym_rev(0:62) - character*6 mycall,hiscall,hisgrid,call2(MAXCALLS) - character*4 grid2(MAXCALLS),rpt(MAXRPT) - character callsign*12,grid*4 - character*180 line + integer dgen(12),sym_rev(0:62) + character*6 mycall,hiscall,hisgrid + character*4 rpt(MAXRPT) character ceme*3,msg*22,msg00*22 - character*22 msg0(MAXMSG),decoded - logical*1 eme(MAXCALLS) - logical first - data first/.true./ + character*22 decoded data rpt/'-01','-02','-03','-04','-05', & '-06','-07','-08','-09','-10', & '-11','-12','-13','-14','-15', & @@ -31,39 +24,16 @@ subroutine hint65(s3,mrs,mrs2,nadd,nflip,mycall,hiscall,hisgrid,qual,decoded) 'R-21','R-22','R-23','R-24','R-25', & 'R-26','R-27','R-28','R-29','R-30', & 'RO','RRR','73'/ - save first,sym1,nused,msg0,sym2 - - first=.true. !### For now, at least: always recompute hypothetical messages - if(first) then - neme=0 - open(23,file=trim(data_dir)//'/CALL3.TXT',status='unknown') - icall=0 - j=0 - do i=1,MAXCALLS - read(23,1002,end=10) line -1002 format(a80) - if(line(1:4).eq.'ZZZZ') cycle - if(line(1:2).eq.'//') cycle - i1=index(line,',') - if(i1.lt.4) cycle - i2=index(line(i1+1:),',') - if(i2.lt.5) cycle - i2=i2+i1 - i3=index(line(i2+1:),',') - if(i3.lt.1) i3=index(line(i2+1:),' ') - i3=i2+i3 - callsign=line(1:i1-1) - grid=line(i1+1:i1+4) - ceme=line(i2+1:i3-1) - eme(i)=ceme.eq.'EME' - if(neme.eq.1 .and. (.not.eme(i))) cycle - j=j+1 - call2(j)=callsign(1:6) !### Fix for compound callsigns! - grid2(j)=grid - enddo -10 ncalls=j - close(23) - + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%symbols2)) then + allocate(jt65_work%symbols2(0:62,MAXMSG),jt65_work%messages(MAXMSG)) + endif + associate(sym2=>jt65_work%symbols2,msg0=>jt65_work%messages, & + nused=>jt65_work%hint_count) + if(jt65_work%hint_revision/=jt65_work%call_revision.or.mycall/=jt65_work%hint_mycall.or. & + hiscall/=jt65_work%hint_hiscall.or.hisgrid/=jt65_work%hint_grid) then + ncalls=0 + if(allocated(jt65_work%calls)) ncalls=size(jt65_work%calls) ! NB: generation of test messages is not yet complete! j=0 do i=-1,ncalls @@ -80,14 +50,12 @@ subroutine hint65(s3,mrs,mrs2,nadd,nflip,mycall,hiscall,hisgrid,qual,decoded) if(m.eq.2) msg='CQ '//hiscall//' '//hisgrid(1:4) if(m.ge.3) msg=mycall//' '//hiscall//' '//rpt(m-2) else - if(m.eq.1) msg=mycall//' '//call2(i)//' '//grid2(i) - if(m.eq.2) msg='CQ '//call2(i)//' '//grid2(i) + if(m.eq.1) msg=mycall//' '//jt65_work%calls(i)(1:6)//' '//jt65_work%grids(i) + if(m.eq.2) msg='CQ '//jt65_work%calls(i)(1:6)//' '//jt65_work%grids(i) endif call fmtmsg(msg,iz) call packmsg(msg,dgen,itype) !Pack message into 72 bits call rs_encode(dgen,sym_rev) !RS encode - sym(0:62)=sym_rev(62:0:-1) - sym1(0:62,j)=sym call interleave63(sym_rev,1) !Interleave channel symbols call graycode(sym_rev,63,1,sym_rev) !Apply Gray code @@ -96,7 +64,10 @@ subroutine hint65(s3,mrs,mrs2,nadd,nflip,mycall,hiscall,hisgrid,qual,decoded) enddo enddo nused=j - first=.false. + jt65_work%hint_revision=jt65_work%call_revision + jt65_work%hint_mycall=mycall + jt65_work%hint_hiscall=hiscall + jt65_work%hint_grid=hisgrid endif ref0=0. @@ -124,6 +95,7 @@ subroutine hint65(s3,mrs,mrs2,nadd,nflip,mycall,hiscall,hisgrid,qual,decoded) psum=psum + s3(i,j) if(i.eq.mrs(j)+1) ref=ref - s3(i,j) + s3(mrs2(j)+1,j) enddo + if(ref<=0.) cycle p=psum/ref if(p.gt.u1) then @@ -150,5 +122,6 @@ subroutine hint65(s3,mrs,mrs2,nadd,nflip,mycall,hiscall,hisgrid,qual,decoded) qmin=1.0 if(qual.ge.qmin) decoded=msg0(ipk) + end associate return end subroutine hint65 diff --git a/lib/jt65_decode.f90 b/lib/jt65_decode.f90 index 18a901ce..3c5f9e6a 100644 --- a/lib/jt65_decode.f90 +++ b/lib/jt65_decode.f90 @@ -1,11 +1,34 @@ module jt65_decode + use jt65_mod, only: jt65_workspace,jt65_average_entry,jt65_work, & + clear_jt65_averages,destroy_jt65_plans,jt65_ap_epoch + use, intrinsic :: iso_c_binding, only: c_int16_t,c_int64_t + integer, parameter :: NSZ=3413, NZMAX=60*12000 + type jt65_options + integer :: utc=0,low_frequency=200,high_frequency=4000,receive_frequency=1500,tolerance=1000 + integer :: submode=0,min_sync=0,passes=2,trials=1000,aggressiveness=0,effort=1,qso_progress=0 + logical :: repeat=.false.,single_decode=.false.,vhf=.false.,average=.false. + logical :: auto_clear=.false.,deep_search=.false.,ap=.false. + character(len=12) :: mycall='',hiscall='' + character(len=6) :: hisgrid='' + end type + type :: jt65_decoder + type(jt65_workspace), pointer :: workspace=>null() procedure(jt65_decode_callback), pointer :: callback => null() contains procedure :: decode + procedure :: decode_pcm + procedure :: initialize + procedure :: release_input + procedure :: clear_averages + procedure :: reset + procedure :: destroy + procedure :: set_calls + procedure :: get_averages + final :: finalize end type jt65_decoder ! Callback function to be called with each decode @@ -35,10 +58,116 @@ module jt65_decode contains + subroutine initialize(this) + class(jt65_decoder), intent(inout) :: this + if(.not.associated(this%workspace)) allocate(this%workspace) + end subroutine + + subroutine release_input(this) + class(jt65_decoder), intent(inout) :: this + if(.not.associated(this%workspace)) return + this%workspace%afc_valid=.false. + this%workspace%input_id=0 + this%workspace%last_average_input=0 + if(allocated(this%workspace%reception_ids)) this%workspace%reception_ids=0 + end subroutine + + subroutine clear_averages(this) + class(jt65_decoder), intent(inout) :: this + if(associated(this%workspace)) call clear_jt65_averages(this%workspace) + end subroutine + + subroutine reset(this) + class(jt65_decoder), intent(inout) :: this + call this%release_input() + call this%clear_averages() + jt65_ap_epoch=jt65_ap_epoch+1 + if(.not.associated(this%workspace)) return + this%workspace%submode=-1 + this%workspace%profile=-1 + if(allocated(this%workspace%calls)) deallocate(this%workspace%calls,this%workspace%grids) + this%workspace%call_revision=this%workspace%call_revision+1 + this%workspace%hint_revision=-1 + end subroutine + + subroutine destroy(this) + class(jt65_decoder), intent(inout) :: this + if(.not.associated(this%workspace)) return + if(associated(jt65_work,this%workspace)) nullify(jt65_work) + call destroy_jt65_plans(this%workspace) + deallocate(this%workspace) + nullify(this%workspace,this%callback) + end subroutine + + subroutine finalize(this) + type(jt65_decoder), intent(inout) :: this + call this%destroy() + end subroutine + + subroutine set_calls(this,calls,grids) + class(jt65_decoder), intent(inout) :: this + character(len=12), intent(in) :: calls(:) + character(len=4), intent(in) :: grids(:) + integer :: n + call this%initialize() + n=min(size(calls),size(grids),10000) + if(allocated(this%workspace%calls)) then + if(size(this%workspace%calls)==n) then + if(all(this%workspace%calls==calls(:n)).and.all(this%workspace%grids==grids(:n))) return + endif + deallocate(this%workspace%calls,this%workspace%grids) + endif + allocate(this%workspace%calls(n),this%workspace%grids(n)) + this%workspace%calls=calls(:n) + this%workspace%grids=grids(:n) + this%workspace%call_revision=this%workspace%call_revision+1 + end subroutine + + subroutine get_averages(this,entries,count) + class(jt65_decoder), intent(in) :: this + type(jt65_average_entry), intent(out) :: entries(:) + integer, intent(out) :: count + count=0 + if(.not.associated(this%workspace)) return + if(.not.allocated(this%workspace%averages)) return + count=min(size(entries),this%workspace%average_count) + entries(:count)=this%workspace%averages(:count) + entries(:count)%dt=entries(:count)%dt-1. + end subroutine + + subroutine decode_pcm(this,callback,samples,sample_count,options,input_id) + class(jt65_decoder), intent(inout) :: this + procedure(jt65_decode_callback) :: callback + integer(c_int16_t), intent(in) :: samples(:) + integer, intent(in) :: sample_count + type(jt65_options), intent(in) :: options + integer(c_int64_t), intent(in) :: input_id + integer :: n,depth,flags + call this%initialize() + if(.not.allocated(this%workspace%audio)) allocate(this%workspace%audio(NZMAX)) + n=min(sample_count,size(samples),NZMAX) + if(n<=0) return + this%workspace%audio(:n)=samples(:n) + this%workspace%audio(n+1:)=0. + this%workspace%input_id=input_id + depth=options%effort + if(options%average) depth=ior(depth,16) + if(options%deep_search) depth=ior(depth,32) + if(options%auto_clear) depth=ior(depth,128) + flags=0 + if(options%single_decode) flags=ior(flags,32) + if(options%vhf) flags=ior(flags,64) + call decode(this,callback,this%workspace%audio,min(n,52*12000),.true.,options%utc, & + options%low_frequency,options%high_frequency,options%receive_frequency,options%tolerance, & + options%submode,options%min_sync,options%repeat,options%passes,.false.,options%trials, & + options%aggressiveness,depth,0.,.false.,options%mycall,options%hiscall,options%hisgrid, & + flags,options%qso_progress,options%ap,prepared=.true.) + end subroutine + subroutine decode(this,callback,dd0,npts,newdat,nutc,nf1,nf2,nfqso, & ntol,nsubmode,minsync,nagain,n2pass,nrobust,ntrials,naggressive, & ndepth,emedelay,clearave,mycall,hiscall,hisgrid,nexp_decode, & - nQSOProgress,ljt65apon) + nQSOProgress,ljt65apon,prepared) ! Process dd0() data to find and decode JT65 signals. @@ -57,8 +186,8 @@ contains character(len=12), intent(in) :: mycall, hiscall character(len=6), intent(in) :: hisgrid - real dd(NZMAX) - real ss(552,NSZ) + logical, optional, intent(in) :: prepared + type(jt65_workspace), pointer :: previous_work real savg(NSZ) real a(5) character*22 decoded,decoded0,avemsg,deepave @@ -76,13 +205,12 @@ contains character*22 decoded end type accepted_decode type(accepted_decode) dec(50) - logical :: first_time,prtavg,single_decode,bVHF,clear_avg65 + logical :: first_time,prtavg,single_decode,bVHF integer h0(0:11),d0(0:11) real r0(0:11) common/decstats/ntry65a,ntry65b,n65a,n65b,num9,numfano common/steve/thresh0 - common/sync/ss ! 0 1 2 3 4 5 6 7 8 9 10 11 data h0/41,42,43,43,44,45,46,47,48,48,49,49/ @@ -90,17 +218,36 @@ contains ! 0 1 2 3 4 5 6 7 8 9 10 11 data r0/0.70,0.72,0.74,0.76,0.78,0.80,0.82,0.84,0.86,0.88,0.90,0.90/ - data nutc0/-999/,nfreq0/-999/,nsave/0/,clear_avg65/.true./ - save + + call this%initialize() + if(.not.allocated(this%workspace%audio)) allocate(this%workspace%audio(NZMAX)) + if(.not.allocated(this%workspace%spectra)) allocate(this%workspace%spectra(552,NSZ)) + previous_work=>jt65_work + jt65_work=>this%workspace + associate(dd=>jt65_work%audio,ss=>jt65_work%spectra,nutc0=>jt65_work%utc0, & + nfreq0=>jt65_work%frequency0,nsave=>jt65_work%saved,nsum=>jt65_work%nsum, & + clear_avg65=>jt65_work%clear_average) this%callback => callback first_time=nrobust .and. (emedelay.eq.-999.9) !Silence compiler warning first_time=newdat - dd=dd0 + if(present(prepared)) then + if(.not.prepared) dd=dd0 + else + dd=dd0 + jt65_work%input_id=0 + endif + neme=0 + ndeepave=0 ndecoded=0 ndecoded0=0 single_decode=iand(nexp_decode,32).ne.0 .or. nagain bVHF=iand(nexp_decode,64).ne.0 + width=0. + if(jt65_work%submode/=nsubmode.or.jt65_work%profile/=merge(1,0,bVHF)) call this%clear_averages() + jt65_work%submode=nsubmode + jt65_work%profile=merge(1,0,bVHF) + if(clearave) call this%clear_averages() if(bVHF) then nvec=ntrials @@ -108,10 +255,10 @@ contains if(n2pass.gt.1) npass=2 else nvec=1000 - if(ndepth.eq.1) then + if(iand(ndepth,3).eq.1) then npass=2 nvec=100 - elseif(ndepth.eq.2) then + elseif(iand(ndepth,3).eq.2) then npass=2 nvec=1000 else @@ -147,6 +294,7 @@ contains ss=0. call symspec65(dd,npts,nqsym,savg) !Get normalized symbol spectra call timer('symsp65 ',1) + if(nqsym==0) exit nfa=nf1 nfb=nf2 @@ -184,11 +332,7 @@ contains freq0=0. prtavg=.false. if(.not.nagain) nsum=0 - if(clearave) then - nsum=0 - nsave=0 - clear_avg65=.true. - endif + if(bVHF) then ! Be sure to search for shorthand message at nfqso +/- ntol @@ -250,7 +394,7 @@ contains ! s2db=sync1 - 30.0 + db(width/3.3) !### VHF/UHF/microwave if(nspecial.gt.0) s2db=sync2 else - s2db=10.0*log10(sync2) - 35 !### Empirical (HF) + s2db=10.0*log10(max(sync2,tiny(1.0))) - 35 !### Empirical (HF) endif nsnr=nint(s2db) if(nsnr.lt.-30) nsnr=-30 @@ -260,8 +404,11 @@ contains if(nft.ne.1 .and. iand(ndepth,16).eq.16 .and. & sync1.ge.float(minsync) .and. (.not.prtavg)) then ! Single-sequence FT decode failed, so try for an average FT decode. - if(nutc.ne.nutc0 .or. abs(nfreq-nfreq0).gt.ntol) then + if(clear_avg65.or.abs(nfreq-nfreq0).gt.ntol.or. & + (jt65_work%input_id/=0.and.jt65_work%input_id/=jt65_work%last_average_input).or. & + (jt65_work%input_id==0.and.nutc/=nutc0)) then ! This is a new minute or a new frequency, so call avg65. + jt65_work%last_average_input=jt65_work%input_id nutc0=nutc nfreq0=nfreq nsave=nsave+1 @@ -342,7 +489,9 @@ contains if(ipass.gt.1 .and. ndecoded.eq.ndecoded0) exit ndecoded0=ndecoded enddo ! ipass -900 return +900 continue + end associate + jt65_work=>previous_work end subroutine decode subroutine avg65(nutc,nsave,snrsync,dtxx,nflip,nfreq,mode65,ntol,ndepth, & @@ -359,20 +508,20 @@ contains logical nagain integer iused(64) ! Accumulated data for message averaging - integer iutc(MAXAVE) - integer nfsave(MAXAVE) - integer nflipsave(MAXAVE) real s1b(-255:256,126) - real s1save(-255:256,126,MAXAVE) real s2(66,126) - real s3save(64,63,MAXAVE) real s3b(64,63) real s3c(64,63) - real dtsave(MAXAVE) - real syncsave(MAXAVE) - logical first,clear_avg65,ljt65apon - data first/.true./ - save + logical clear_avg65,ljt65apon + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%history1)) then + allocate(jt65_work%history1(-255:256,126,MAXAVE),jt65_work%history3(64,63,MAXAVE)) + allocate(jt65_work%averages(MAXAVE),jt65_work%reception_ids(MAXAVE)) + clear_avg65=.true. + endif + associate(iutc=>jt65_work%averages%utc,nfsave=>jt65_work%averages%frequency, & + nflipsave=>jt65_work%averages%polarity,dtsave=>jt65_work%averages%dt, & + syncsave=>jt65_work%averages%sync,s1save=>jt65_work%history1,s3save=>jt65_work%history3) nftt=0 avemsg=' ' @@ -381,28 +530,32 @@ contains deepbest=' ' nfttbest=0 - if(first .or. clear_avg65) then + if(clear_avg65) then iutc=-1 nfsave=0 - dtdiff=0.2 + jt65_work%reception_ids=0 + jt65_work%average_count=0 s3save=0. s1save=0. nsave=1 !### ??? ! Silence compiler warnings if(nagain .and. ndeepave.eq.-99 .and. neme.eq.-99) stop - first=.false. clear_avg65=.false. endif do i=1,64 if(iutc(i).lt.0) exit - if(nutc.eq.iutc(i) .and. abs(nfreq-nfsave(i)).le.ntol) then + if(abs(nfreq-nfsave(i)).le.ntol.and. & + ((jt65_work%input_id/=0.and.jt65_work%reception_ids(i)==jt65_work%input_id).or. & + (jt65_work%input_id==0.and.nutc==iutc(i)))) then nsave=mod(nsave-2+MAXAVE,MAXAVE)+1 go to 10 endif enddo ! Save data for message averaging + jt65_work%reception_ids(nsave)=jt65_work%input_id + jt65_work%average_count=max(jt65_work%average_count,nsave) iutc(nsave)=nutc syncsave(nsave)=snrsync dtsave(nsave)=dtxx @@ -421,9 +574,10 @@ contains do i=1,MAXAVE !Consider all saved spectra cused(i)='.' + jt65_work%averages(i)%used=.false. if(iutc(i).lt.0) exit if(mod(iutc(i),2).ne.mod(nutc,2)) cycle !Use only same (odd/even) seq - if(abs(dtxx-dtsave(i)).gt.dtdiff) cycle !DT must match + if(abs(dtxx-dtsave(i)).gt.0.2) cycle !DT must match if(abs(nfreq-nfsave(i)).gt.ntol) cycle !Freq must match if(nflipsave(i).eq.0) cycle !No sync if(nflip.ne.nflipsave(i)) cycle !Sync type (*/#) must match @@ -434,6 +588,7 @@ contains dtsum=dtsum + dtsave(i) nfsum=nfsum + nfsave(i) cused(i)='$' + jt65_work%averages(i)%used=.true. nsum=nsum+1 iused(nsum)=i enddo @@ -448,13 +603,6 @@ contains fave=float(nfsum)/nsum endif - do i=1,nsave - csync=' ' - if(nflipsave(i).lt.0.0) csync='#' - if(nflipsave(i).gt.0.0) csync='*' - write(14,1000) cused(i),iutc(i),syncsave(i),dtsave(i)-1.0,nfsave(i),csync -1000 format(a1,i5.4,f6.1,f6.2,i6,1x,a1) - enddo if(nsum.lt.2) go to 900 df=1378.125/512.0 @@ -526,7 +674,7 @@ contains nftt=nfttbest endif 900 continue - + end associate return end subroutine avg65 diff --git a/lib/jt65_host_support.f90 b/lib/jt65_host_support.f90 new file mode 100644 index 00000000..6abd3b74 --- /dev/null +++ b/lib/jt65_host_support.f90 @@ -0,0 +1,61 @@ +module jt65_host_support + use jt65_decode, only: jt65_decoder,jt65_average_entry + use prog_args, only: data_dir + implicit none + private + public :: load_jt65_calls,write_jt65_averages + +contains + + subroutine load_jt65_calls(calls,grids) + character(len=12), allocatable, intent(out) :: calls(:) + character(len=4), allocatable, intent(out) :: grids(:) + character(len=12), allocatable :: call_buffer(:) + character(len=4), allocatable :: grid_buffer(:) + character(len=180) :: line + integer :: unit,ios,count,first,second + + allocate(call_buffer(10000),grid_buffer(10000)) + count=0 + open(newunit=unit,file=trim(data_dir)//'/CALL3.TXT',status='old',action='read',iostat=ios) + if(ios==0) then + do while(count<size(call_buffer)) + read(unit,'(a)',iostat=ios) line + if(ios/=0) exit + if(line(:4)=='ZZZZ'.or.line(:2)=='//') cycle + first=index(line,',') + if(first<4) cycle + second=index(line(first+1:),',') + if(second<5) cycle + count=count+1 + call_buffer(count)=line(:first-1) + grid_buffer(count)=line(first+1:first+4) + enddo + close(unit) + endif + calls=call_buffer(:count) + grids=grid_buffer(:count) + end subroutine load_jt65_calls + + subroutine write_jt65_averages(decoder,unit) + class(jt65_decoder), intent(inout) :: decoder + integer, intent(in) :: unit + type(jt65_average_entry) :: entries(64) + integer :: count,i + character :: used,polarity + + call decoder%get_averages(entries,count) + rewind(unit) + do i=1,count + used='.' + if(entries(i)%used) used='$' + polarity=' ' + if(entries(i)%polarity<0) polarity='#' + if(entries(i)%polarity>0) polarity='*' + write(unit,'(a1,i5.4,f6.1,f6.2,i6,1x,a1)') used,entries(i)%utc, & + entries(i)%sync,entries(i)%dt,entries(i)%frequency,polarity + enddo + endfile(unit) + flush(unit) + end subroutine write_jt65_averages +end module jt65_host_support diff --git a/lib/jt65_mod.f90 b/lib/jt65_mod.f90 index 772ebeae..4d1ddc1a 100644 --- a/lib/jt65_mod.f90 +++ b/lib/jt65_mod.f90 @@ -1,5 +1,8 @@ module jt65_mod + use, intrinsic :: iso_c_binding + use FFTW3 + save integer param(0:9) @@ -12,4 +15,76 @@ module jt65_mod real pr(126) real width + integer, parameter :: jt65_max_calls=10000 + type jt65_average_entry + integer :: utc=-1,frequency=0,polarity=0 + real :: sync=0.,dt=0. + logical :: used=.false. + end type + + type jt65_workspace + real, allocatable :: audio(:),spectra(:,:),big_input(:),filter(:) + complex, allocatable :: filter_fft(:),filtered(:) + complex, allocatable :: cx(:),cx1(:),c5x(:),integral(:) + complex, allocatable :: cref(:),camp(:),cfilt(:),cw(:) + real, allocatable :: history1(:,:,:),history3(:,:,:) + type(jt65_average_entry), allocatable :: averages(:) + integer(c_int64_t), allocatable :: reception_ids(:) + character(len=12), allocatable :: calls(:) + character(len=4), allocatable :: grids(:) + integer(c_int8_t), allocatable :: symbols2(:,:) + character(len=22), allocatable :: messages(:) + integer :: utc0=-999,frequency0=-999,saved=0,nsum=0 + integer :: submode=-1,profile=-1,average_count=0 + integer :: patience=-1,threads=-1,sub_patience=-1,sub_threads=-1 + integer :: call_revision=0,hint_revision=-1,hint_count=0 + integer(c_int64_t) :: input_id=0,last_average_input=0 + character(len=6) :: hint_mycall='',hint_hiscall='',hint_grid='' + logical :: clear_average=.true.,afc_valid=.false.,filter_valid=.false. + real :: afc_parameters(3)=0. + type(c_ptr) :: big_plan=c_null_ptr,short_plan=c_null_ptr,filter_plan=c_null_ptr + type(c_ptr) :: subtract_forward=c_null_ptr,subtract_inverse=c_null_ptr,window_plan=c_null_ptr + end type + ! DSP helpers share the active owner; JT65 calls must remain serialized. + type(jt65_workspace), pointer :: jt65_work=>null() + type(jt65_workspace), target :: fallback_workspace + integer :: jt65_ap_epoch=0 + +contains + + subroutine ensure_jt65_workspace() + if(.not.associated(jt65_work)) jt65_work=>fallback_workspace + end subroutine + + subroutine clear_jt65_averages(work) + type(jt65_workspace), intent(inout) :: work + work%utc0=-999 + work%frequency0=-999 + work%saved=0 + work%nsum=0 + work%last_average_input=0 + work%average_count=0 + work%clear_average=.true. + if(allocated(work%averages)) work%averages%utc=-1 + end subroutine + + subroutine destroy_jt65_plans(work) + type(jt65_workspace), intent(inout) :: work + !$omp critical(fftw) + if(c_associated(work%big_plan)) call fftwf_destroy_plan(work%big_plan) + if(c_associated(work%short_plan)) call fftwf_destroy_plan(work%short_plan) + if(c_associated(work%filter_plan)) call fftwf_destroy_plan(work%filter_plan) + if(c_associated(work%subtract_forward)) call fftwf_destroy_plan(work%subtract_forward) + if(c_associated(work%subtract_inverse)) call fftwf_destroy_plan(work%subtract_inverse) + if(c_associated(work%window_plan)) call fftwf_destroy_plan(work%window_plan) + !$omp end critical(fftw) + work%big_plan=c_null_ptr + work%short_plan=c_null_ptr + work%filter_plan=c_null_ptr + work%subtract_forward=c_null_ptr + work%subtract_inverse=c_null_ptr + work%window_plan=c_null_ptr + work%filter_valid=.false. + end subroutine + end module jt65_mod diff --git a/lib/jt65_test.f90 b/lib/jt65_test.f90 index d6a80a2e..644e5fbd 100644 --- a/lib/jt65_test.f90 +++ b/lib/jt65_test.f90 @@ -15,6 +15,7 @@ contains nQSOProgress,ljt65apon) use timer_module, only: timer use jt65_decode + use jt65_host_support, only: load_jt65_calls implicit none include 'constants.f90' @@ -24,10 +25,17 @@ contains logical, intent(in) :: nrobust,ljt65apon character(len=12), intent(in) :: mycall, hiscall character(len=6), intent(in) :: hisgrid - type(jt65_decoder) :: my_decoder + type(jt65_decoder), save :: my_decoder + character(len=12), allocatable :: calls(:) + character(len=4), allocatable :: grids(:) logical nclearave !### Should be a dummy arg? nclearave=.false. + if(iand(ndepth,32)/=0) then + call load_jt65_calls(calls,grids) + call my_decoder%set_calls(calls,grids) + endif + call timer('jt65a ',0) call my_decoder%decode(my_callback,dd,npts=52*12000,newdat=.true., & nutc=nutc,nf1=nflow,nf2=nfhigh,nfqso=nfqso,ntol=ntol, & diff --git a/lib/jt9.f90 b/lib/jt9.f90 index be09716b..1e59bd8e 100644 --- a/lib/jt9.f90 +++ b/lib/jt9.f90 @@ -12,11 +12,10 @@ program jt9 use readwav use jt9_input_validation, only: parse_integer, parse_real, parse_wav_filename_nutc use, intrinsic :: iso_fortran_env, only: error_unit - use ft8_mod1, only : dd8 - use jt65_mod6, only : dd use streaming_emit, only: streaming_emit_set_enabled, streaming_emit_error use jt9_params_init, only: init_default_params, init_streaming_extra_fields, & apply_per_mode_policy, cli_args_t + use decode_completion_module, only: decode_completion_result, write_decode_completion include 'jt9com.f90' @@ -32,6 +31,8 @@ program jt9 real*4 s(NSMAX) real*8 TRperiod integer npct_unused + integer(c_int) :: engine_attempt_no, engine_valid_samples + integer(c_int64_t) :: engine_input_id character c character(len=500) optarg, infile @@ -45,11 +46,12 @@ program jt9 bLowSidelobes = .false., nexp_decode_set = .false., & have_ntol = .false.,multift8 = .false.,hidedupes = .false., & lft8lowth = .true.,lft8subpass = .true.,lwidedxcsearch = .true., & - stream_mode = .false. - type (option) :: long_options(43) = [ & + stream_mode = .false., use_mtd_fft_plans = .false., wav_utc_has_seconds + type (option) :: long_options(44) = [ & option ('help', .false., 'h', 'Display this help message', ''), & option ('version', .false., 'v', 'Display version and build revision', ''),& - option ('shmem',.true.,'s','Use shared memory for sample data','KEY'), & + option ('shmem',.true.,'s','Use native shared memory for sample data','NAME'), & + option ('ipc-lock', .true., '1', 'Shared-memory worker lifetime lock', 'PATH'), & option ('stream', .false., '0', & 'Read framed PCM samples from stdin', & ''), & @@ -135,7 +137,7 @@ program jt9 TRperiod=60.d0 do - call getopt('hvs:e:a:b:r:m:p:d:f:F:w:t:9876543WYqkTMUSZL:S:H:c:G:x:g:X:Q:C:R:N:E:D:', & + call getopt('hvs:e:a:b:r:m:p:d:f:F:w:t:9876543WYqkTMUSZL:S:H:c:G:x:g:X:Q:C:R:N:E:D:1:', & long_options,c,optarg,arglen,stat,offset,remain,.true.) if (stat .ne. 0) then exit @@ -148,6 +150,8 @@ program jt9 case ('s') read_files = .false. shm_key = optarg(:arglen) + case ('1') + ipc_lock_path = optarg(:arglen) case ('0') read_files = .false. stream_mode = .true. @@ -256,7 +260,7 @@ program jt9 print *, ' Reads data from *.wav files.' print *, '' print *, ' jt9 -s <key> [-w patience] [-m threads] [-e path] [-a path] [-t path] [-r path]' - print *, ' Gets data from shared memory region with key==<key>' + print *, ' Gets data from the native shared memory name supplied with -s' print *, '' print *, ' cat <pcm-stream> | jt9 --stream' print *, ' Reads framed PCM samples from stdin.' @@ -389,11 +393,14 @@ program jt9 ' Hz WAV sample rate for the selected mode' stop 2 end if - call parse_wav_filename_nutc(infile, nutc) + call parse_wav_filename_nutc(infile, nutc, wav_utc_has_seconds) + if((mode.eq.66.or.mode.eq.240.or.mode.eq.241.or.mode.eq.242).and..not.wav_utc_has_seconds) & + nutc=100*nutc nsps=6912 npts=TRperiod*12000.d0 kstep=nsps/2 k=0 + engine_valid_samples=0 nhsym=0 nhsym0=-999 if(iarg .eq. offset + 1) then @@ -405,7 +412,8 @@ program jt9 if(mode.eq.5) npts=21*3456 if(mode.eq.66) npts=TRperiod*12000 nblocks=npts/kstep - if(mode.eq.4) nblocks=(npts+kstep-1)/kstep + if(mode.eq.4.or.mode.eq.9.or.mode.eq.240.or.mode.eq.241.or.mode.eq.242) & + nblocks=(npts+kstep-1)/kstep do iblk=1,nblocks k0=(iblk-1)*kstep k=min(iblk*kstep,npts) @@ -421,12 +429,13 @@ program jt9 stop 2 end if if (samples_read == 0) then - print*,'EOF on input file ',trim(infile) + if(mode.ne.9.or.engine_valid_samples.eq.0) print*,'EOF on input file ',trim(infile) exit end if + engine_valid_samples=k0+samples_read nhsym=(k-2048)/kstep if(nhsym.ge.1 .and. nhsym.ne.nhsym0) then - if(mode.eq.9 .or. mode.eq.74) then + if(mode.eq.74) then ! Compute rough symbol spectra for the JT9 decoder ingain=0 call timer('symspec ',0) @@ -436,15 +445,17 @@ program jt9 call timer('symspec ',1) endif nhsym0=nhsym - if(nhsym.ge.181 .and. mode.ne.240 .and. mode.ne.241 .and. & + if(nhsym.ge.181 .and. mode.ne.9 .and. mode.ne.240 .and. mode.ne.241 .and. & mode.ne.242 .and. mode.ne.66) exit endif if (samples_read < k-k0) then - print*,'EOF on input file ',trim(infile) + if(mode.ne.9) print*,'EOF on input file ',trim(infile) exit end if enddo close(unit=wav%lun) + engine_input_id=int(iarg-offset,c_int64_t) + engine_attempt_no=0 ! WAV-path-only mode adjustment (mode=164 with submode<100 bumps by 100). ! Hoisted before init_default_params so the bumped value is threaded @@ -467,6 +478,7 @@ program jt9 call init_default_params(shared_data%params, mode, TRperiod, args) ! WAV-path post-init overrides. + shared_data%params%ntr = int(TRperiod) shared_data%params%nutc = nutc ! parsed from filename shared_data%params%ndiskdat = .true. ! reading from disk shared_data%params%nzhsym = nhsym ! per-period (matches former jt9.f90:486) @@ -518,19 +530,16 @@ program jt9 shared_data%params%nzhsym=nearly id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder(shared_data%ss,id2a, & - shared_data%params,nfsample) + call run_engine_wav(id2a,nearly*3456) nearly=47 shared_data%params%nzhsym=nearly id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder(shared_data%ss,id2a, & - shared_data%params,nfsample) + call run_engine_wav(id2a,nearly*3456) id2a(nearly*3456+1:50*3456)=shared_data%id2(nearly*3456+1:50*3456) id2a(50*3456+1:)=0 shared_data%params%nzhsym=50 - call multimode_decoder(shared_data%ss,id2a, & - shared_data%params,nfsample) + call run_engine_wav(id2a,50*3456) cycle else if(mode.eq.8 .and. shared_data%params%lmultift8) then if(shared_data%params%ndecoderstart.lt.2) then @@ -539,38 +548,24 @@ program jt9 shared_data%params%nzhsym=nearly id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder(shared_data%ss,id2a, & - shared_data%params,nfsample) + call run_engine_wav(id2a,nearly*3456) if(shared_data%params%ndecoderstart.lt.2) then nearly=46 shared_data%params%lmultift8=.false. shared_data%params%nzhsym=nearly id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder(shared_data%ss,id2a, & - shared_data%params,nfsample) + call run_engine_wav(id2a,nearly*3456) endif if(shared_data%params%ndecoderstart.eq.0) nearly=49 if(shared_data%params%ndecoderstart.eq.1) nearly=50 shared_data%params%lmultift8=.true. shared_data%params%nzhsym=nearly - id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456) - id2a(nearly*3456+1:)=0 - dd(1:nearly*3456)=shared_data%id2(1:nearly*3456) - dd(nearly*3456+1:)=0 - dd8(1:nearly*3456)=shared_data%id2(1:nearly*3456) - dd8(nearly*3456+1:)=0 else if(shared_data%params%ndecoderstart.eq.2) nearly=48 if(shared_data%params%ndecoderstart.eq.3) nearly=49 if(shared_data%params%ndecoderstart.eq.4) nearly=50 shared_data%params%nzhsym=nearly - id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456) - id2a(nearly*3456+1:)=0 - dd(1:nearly*3456)=shared_data%id2(1:nearly*3456) - dd(nearly*3456+1:)=0 - dd8(1:nearly*3456)=shared_data%id2(1:nearly*3456) - dd8(nearly*3456+1:)=0 endif ! MSK144 @@ -579,8 +574,15 @@ program jt9 endif ! Normal decoding pass - call multimode_decoder(shared_data%ss,shared_data%id2, & - shared_data%params,nfsample) + if(mode.eq.8.or.mode.eq.9.or.mode.eq.65.or.mode.eq.66.or. & + mode.eq.240.or.mode.eq.241.or.mode.eq.242) then + call run_engine_wav(shared_data%id2,engine_valid_samples) + else if(mode.eq.5) then + call run_engine_wav(shared_data%id2,72576) + else + call multimode_decoder(shared_data%ss,shared_data%id2, & + shared_data%params,nfsample) + endif enddo call timer('jt9 ',1) @@ -593,12 +595,14 @@ program jt9 ! Save FFTW wisdom and free memory if(len(trim(wisfile)).gt.0) iret=fftwf_export_wisdom_to_filename(wisfile) - if(mode.eq.8 .and. shared_data%params%lmultift8) then + if(allocated(shared_data)) then + use_mtd_fft_plans=mode.eq.8 .and. shared_data%params%lmultift8 + endif + if(use_mtd_fft_plans) then call four2avar(a,-1,1,1,1) call filbigvar(-1.,0,0.,0,0.,0.,0) !used for FFT plans for FT8 multithread detector else call four2a(a,-1,1,1,1) - call filbig(a,-1,1,0.0,0,0,0,0,0) !used for all other FFT plans endif call fftwf_cleanup_threads() call fftwf_cleanup() @@ -606,6 +610,20 @@ program jt9 contains + subroutine run_engine_wav(samples, pass_samples) + integer*2, intent(inout) :: samples(*) + integer, intent(in) :: pass_samples + type(decode_completion_result) :: completion + + engine_attempt_no=engine_attempt_no+1 + call run_decoder_engine(samples,shared_data%params, & + nfsample,completion,0,engine_input_id,engine_input_id, & + engine_attempt_no,min(engine_valid_samples,pass_samples)) + if(.not.completion%available) return + if(.not.lquiet) call write_decode_completion(completion) + call flush(6) + end subroutine run_engine_wav + subroutine require_integer(option, text, value) character(len=*), intent(in) :: option, text integer, intent(out) :: value diff --git a/lib/jt9_decode.f90 b/lib/jt9_decode.f90 index d862504a..9970e45f 100644 --- a/lib/jt9_decode.f90 +++ b/lib/jt9_decode.f90 @@ -1,9 +1,36 @@ module jt9_decode + use, intrinsic :: iso_c_binding, only: c_short, c_ptr, c_float, c_float_complex, c_null_ptr, c_associated + use fftw3, only: fftwf_plan_dft_r2c_1d, fftwf_execute_dft_r2c, fftwf_destroy_plan, FFTW_ESTIMATE + use jt9_downsample, only: jt9_downsample_workspace + use jt9_soft_symbols, only: softsym + private + public :: jt9_decoder, jt9_spectrum_workspace + + type :: jt9_spectrum_workspace + private + real(c_float), allocatable :: input(:) + complex(c_float_complex), allocatable :: output(:) + type(c_ptr) :: plan=c_null_ptr + contains + procedure :: initialize => initialize_spectrum + procedure :: prepare_spectra + procedure :: clear => clear_spectrum + final :: finalize_spectrum + end type jt9_spectrum_workspace type :: jt9_decoder - procedure(jt9_decode_callback), pointer :: callback + procedure(jt9_decode_callback), pointer :: callback=>null() + type(jt9_downsample_workspace), private :: downsample + type(jt9_spectrum_workspace), private :: spectrum + real, allocatable, private :: spectra(:,:), ccfred(:), red2(:) + logical, allocatable, private :: ccfok(:), done(:) contains + procedure :: initialize procedure :: decode + procedure :: decode_pcm + procedure :: release_input + procedure :: reset + final :: finalize_decoder end type jt9_decoder abstract interface @@ -23,6 +50,98 @@ module jt9_decode contains + subroutine initialize(this) + class(jt9_decoder), intent(inout) :: this + if(.not.allocated(this%ccfred)) then + allocate(this%ccfred(6827),this%red2(6827),this%ccfok(6827),this%done(6827)) + endif + end subroutine initialize + + subroutine decode_pcm(this,callback,samples,sample_count,receive_frequency, & + search_low,search_high,tolerance,depth,submode,repeat) + class(jt9_decoder), intent(inout) :: this + procedure(jt9_decode_callback) :: callback + ! The engine owns the full analysis buffer and pads beyond sample_count. + integer(c_short), intent(in) :: samples(60*12000) + integer, intent(in) :: sample_count,receive_frequency,search_low,search_high,tolerance,depth,submode + logical, intent(in) :: repeat + integer :: count,half_symbols + + count=max(0,min(sample_count,60*12000)) + half_symbols=min(181,max(0,(count-2048)/3456)) + call this%release_input() + if(half_symbols.lt.2) return + if(.not.any(samples(1:count).ne.0)) return + if(.not.allocated(this%spectra)) allocate(this%spectra(184,6827)) + call this%spectrum%prepare_spectra(samples,half_symbols,this%spectra) + call this%decode(callback,this%spectra,samples,receive_frequency,.true.,count/8, & + search_low,search_low,search_high,tolerance,half_symbols,repeat,depth,9,submode,0) + end subroutine decode_pcm + + subroutine initialize_spectrum(this) + class(jt9_spectrum_workspace), intent(inout) :: this + if(c_associated(this%plan)) return + allocate(this%input(16384),this%output(0:8192)) + !$omp critical(fftw) + this%plan=fftwf_plan_dft_r2c_1d(16384,this%input,this%output,FFTW_ESTIMATE) + !$omp end critical(fftw) + end subroutine initialize_spectrum + + subroutine prepare_spectra(this,samples,half_symbols,spectra) + class(jt9_spectrum_workspace), intent(inout) :: this + integer(c_short), intent(in) :: samples(:) + integer, intent(in) :: half_symbols + real, intent(out) :: spectra(184,6827) + integer :: row,first,last,source_first + real, parameter :: scale=(1.0/16384)**2 + + call this%initialize() + spectra=0. + do row=1,half_symbols + last=row*3456 + first=last-16384+1 + source_first=max(1,first) + this%input=0. + this%input(source_first-first+1:16384)=0.1*samples(source_first:last) + call fftwf_execute_dft_r2c(this%plan,this%input,this%output) + spectra(row,:)=scale*(real(this%output(0:6826))**2+aimag(this%output(0:6826))**2) + enddo + end subroutine prepare_spectra + + subroutine clear_spectrum(this) + class(jt9_spectrum_workspace), intent(inout) :: this + !$omp critical(fftw) + if(c_associated(this%plan)) call fftwf_destroy_plan(this%plan) + !$omp end critical(fftw) + this%plan=c_null_ptr + if(allocated(this%input)) deallocate(this%input,this%output) + end subroutine clear_spectrum + + subroutine finalize_spectrum(this) + type(jt9_spectrum_workspace), intent(inout) :: this + call this%clear() + end subroutine finalize_spectrum + + subroutine release_input(this) + class(jt9_decoder), intent(inout) :: this + call this%downsample%invalidate() + nullify(this%callback) + end subroutine release_input + + subroutine reset(this) + class(jt9_decoder), intent(inout) :: this + call this%release_input() + end subroutine reset + + subroutine finalize_decoder(this) + type(jt9_decoder), intent(inout) :: this + call this%downsample%clear() + call this%spectrum%clear() + if(allocated(this%spectra)) deallocate(this%spectra) + if(allocated(this%ccfred)) deallocate(this%ccfred,this%red2,this%ccfok,this%done) + nullify(this%callback) + end subroutine finalize_decoder + subroutine decode(this,callback,ss,id2,nfqso,newdat,npts8,nfa, & nfsplit,nfb,ntol,nzhsym,nagain,ndepth,nmode,nsubmode,nexp_decode) use timer_module, only: timer @@ -33,20 +152,18 @@ contains real ss(184,NSMAX) logical, intent(in) :: newdat, nagain character*22 msg - real*4 ccfred(NSMAX) - real*4 red2(NSMAX) - logical ccfok(NSMAX) - logical done(NSMAX) - integer*2 id2(NTMAX*12000) + integer*2, intent(in) :: id2(*) integer*1 i1SoftSymbols(207) common/decstats/ntry65a,ntry65b,n65a,n65b,num9,numfano - save ccfred,red2 if(nexp_decode.eq.-99) stop !Silence compiler warning + call this%initialize() + associate(ccfred=>this%ccfred,red2=>this%red2,ccfok=>this%ccfok,done=>this%done) this%callback => callback + if(newdat) call this%downsample%invalidate() if(nmode.eq.9 .and. nsubmode.ge.1) then - call decode9w(nfqso,ntol,nsubmode,ss,id2,sync,nsnr,xdt,freq,msg) - if (associated(this%callback)) then + call decode9w(nfqso,ntol,nsubmode,ss,nzhsym,id2,sync,nsnr,xdt,freq,msg) + if (associated(this%callback).and.len_trim(msg)>0) then ndrift=0 call this%callback(sync,nsnr,xdt,freq,ndrift,msg) end if @@ -66,13 +183,12 @@ contains if(nmode.eq.65+9) nf1=nfsplit ia=max(1,nint((nf1-nf0)/df3)) ib=min(NSMAX,nint((nfb-nf0)/df3)) + if(ib.le.ia) go to 999 lag1=-int(2.5/tstep + 0.9999) lag2=int(5.0/tstep + 0.9999) - if(newdat) then - call timer('sync9 ',0) - call sync9(ss,nzhsym,lag1,lag2,ia,ib,ccfred,red2,ipk) - call timer('sync9 ',1) - endif + call timer('sync9 ',0) + call sync9(ss,nzhsym,lag1,lag2,ia,ib,ccfred,red2,ipk) + call timer('sync9 ',1) nsps8=nsps/8 df8=1500.0/nsps8 @@ -130,7 +246,7 @@ contains call timer('softsym ',0) fpk=nf0 + df3*(i-1) - call softsym(id2,npts8,nsps8,newdat,fpk,syncpk,snrdb,xdt, & + call softsym(this%downsample,id2,npts8,nsps8,fpk,syncpk,snrdb,xdt, & freq,drift,a3,schk,i1SoftSymbols) call timer('softsym ',1) @@ -167,6 +283,8 @@ contains if(nagain) exit enddo -999 return +999 nullify(this%callback) + end associate + return end subroutine decode end module jt9_decode diff --git a/lib/jt9_input_validation.f90 b/lib/jt9_input_validation.f90 index 333fb30b..bb59bd6f 100644 --- a/lib/jt9_input_validation.f90 +++ b/lib/jt9_input_validation.f90 @@ -102,14 +102,16 @@ contains is_real_token = i > length end function is_real_token - subroutine parse_wav_filename_nutc(filename, nutc) + subroutine parse_wav_filename_nutc(filename, nutc, includes_seconds) character(len=*), intent(in) :: filename integer, intent(out) :: nutc + logical, optional, intent(out) :: includes_seconds integer :: dot, ios, length character(len=:), allocatable :: stem nutc = 0 + if (present(includes_seconds)) includes_seconds = .false. length = len_trim(filename) if (length == 0) return @@ -121,7 +123,10 @@ contains if (len(stem) >= 6) then if (all_digits(stem(len(stem) - 5:))) then read(stem(len(stem) - 5:), *, iostat=ios) nutc - if (ios == 0) return + if (ios == 0) then + if (present(includes_seconds)) includes_seconds = .true. + return + end if end if end if if (len(stem) >= 5) then diff --git a/lib/jt9_params_init.f90 b/lib/jt9_params_init.f90 index 782a7e12..aba14b66 100644 --- a/lib/jt9_params_init.f90 +++ b/lib/jt9_params_init.f90 @@ -114,6 +114,8 @@ contains params%nzhsym = 50 ! caller may overwrite per-period params%nsubmode = args%nsubmode params%nagain = .false. + params%b_even_seq = .false. + params%b_superfox = .false. params%ndepth = args%ndepth params%lft8apon = .true. params%lapcqonly = .false. @@ -186,8 +188,6 @@ contains params%minsync = 0 params%nlist = 0 params%max_drift = 0 - params%b_even_seq = .false. - params%b_superfox = .false. params%lft8lowth = args%lft8lowth params%lft8subpass = args%lft8subpass params%lwidedxcsearch = args%lwidedxcsearch diff --git a/lib/jt9a.f90 b/lib/jt9a.f90 index 9daa8272..c1a5a20a 100644 --- a/lib/jt9a.f90 +++ b/lib/jt9a.f90 @@ -1,5 +1,8 @@ subroutine jt9a() - use, intrinsic :: iso_c_binding, only: c_f_pointer, c_null_char, c_bool, c_sizeof, c_int + use, intrinsic :: iso_c_binding, only: c_f_pointer, c_null_char, c_bool, c_int, & + c_ptr, c_null_ptr, c_size_t + use decoder_ipc_layout_module, only: decoder_ipc_fortran_validate, & + decoder_ipc_report_layout_error, DECODER_IPC_LAYOUT_VERSION, DECODER_IPC_LAYOUT_ATTACH use decoder_ipc_atomic, only: decoder_ipc_control_try_claim, & decoder_ipc_control_finish, decoder_ipc_progress_bind, & decoder_ipc_progress_unbind, DECODER_IPC_CLAIM_INVALID, & @@ -11,8 +14,6 @@ subroutine jt9a() use timer_module, only: timer use timer_impl, only: init_timer !, limtrace use shmem - use ft8_mod1, only : dd8 - use jt65_mod6, only : dd include 'jt9com.f90' @@ -22,48 +23,68 @@ subroutine jt9a() type(shared_dec_data), pointer, volatile :: shared_memory type(params_block) :: local_params logical(c_bool) :: ok - integer(c_int) :: active_generation, claim_result + integer(c_int) :: active_generation, claim_result, pass_attempt_no, pass_valid_samples + integer(c_int) :: layout_status + integer(c_size_t) :: available_bytes + type(c_ptr) :: shared_address type(decode_completion_result) :: completion - call init_timer (trim(data_dir)//'/timer.out') + layout_status=0 ! open(23,file=trim(data_dir)//'/CALL3.TXT',status='unknown') ! limtrace=-1 !Disable all calls to timer() -! Multiple instances: set the shared memory key before attaching - call shmem_setkey(trim(shm_key)//c_null_char) - ok=shmem_attach() - if(.not.ok) call abort + ok=shmem_lock_worker(trim(ipc_lock_path)//c_null_char) + if(.not.ok) then + write(*,'(a)') '<DecoderError> status=worker-lock' + call flush(6) + stop 1 + endif + ok=shmem_attach(trim(shm_key)//c_null_char) + if(.not.ok) then + layout_status=DECODER_IPC_LAYOUT_ATTACH + call decoder_ipc_report_layout_error(layout_status,c_null_ptr,0_c_size_t) + go to 999 + endif msdelay=10 - call c_f_pointer(shmem_address(),shared_memory) - nbytes=shmem_size() - if(nbytes.lt.c_sizeof(shared_memory)) then - ok=shmem_detach() - print*,'jt9a: Incompatible shared-memory layout.' + shared_address=shmem_address() + available_bytes=shmem_size() + layout_status=decoder_ipc_fortran_validate(shared_address,available_bytes) + if(layout_status.ne.0) then + call decoder_ipc_report_layout_error(layout_status,shared_address,available_bytes) go to 999 endif + call init_timer (trim(data_dir)//'/timer.out') + call c_f_pointer(shared_address,shared_memory) call decoder_ipc_progress_bind(shared_memory%control%generation, & shared_memory%control%state, shared_memory%control%version, & shared_memory%control%progress) call reset_decode_completion(completion) + write(*,'(a,i0)') '<DecoderReady> version=',DECODER_IPC_VERSION + call flush(6) -10 claim_result=decoder_ipc_control_try_claim( & +10 layout_status=decoder_ipc_fortran_validate(shared_address,available_bytes) + if(layout_status.ne.0) then + call decoder_ipc_report_layout_error(layout_status,shared_address,available_bytes) + go to 999 + endif + claim_result=decoder_ipc_control_try_claim( & shared_memory%control%generation, shared_memory%control%state, & shared_memory%control%version, active_generation) if(claim_result.eq.DECODER_IPC_CLAIM_SHUTDOWN) then - ok=shmem_detach() go to 999 endif if(claim_result.eq.DECODER_IPC_CLAIM_INCOMPATIBLE) then - ok=shmem_detach() - print*,'jt9a: Incompatible shared-memory protocol version.' + layout_status=DECODER_IPC_LAYOUT_VERSION + call decoder_ipc_report_layout_error(layout_status,shared_address,available_bytes) go to 999 endif if(claim_result.eq.DECODER_IPC_CLAIM_INVALID) then - ok=shmem_detach() - print*,'jt9a: Invalid decoder request generation.' + layout_status=DECODER_IPC_CLAIM_INVALID + write(*,'(a)') '<DecoderError> status=invalid-generation' + call flush(6) go to 999 endif if(claim_result.eq.DECODER_IPC_CLAIM_NONE) then @@ -74,6 +95,7 @@ subroutine jt9a() write(*,'(a,i0)') '<DecodeStarted> gen=',active_generation call flush(6) local_params=shared_memory%payload%params + pass_attempt_no=shared_memory%metadata%attempt_no call timer('decoder ',0) if(local_params%nmode.eq.8 .and. local_params%ndiskdat .and. & .not. local_params%nagain .and. .not. local_params%lmultift8) then @@ -82,48 +104,53 @@ subroutine jt9a() local_params%nzhsym=nearly id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, & - 12000,completion,active_generation) + call run_decoder_engine(id2a,local_params, & + 12000,completion,active_generation,shared_memory%metadata%input_id, & + shared_memory%metadata%analysis_id,pass_attempt_no, & + min(shared_memory%metadata%valid_samples,nearly*3456)) + pass_attempt_no=pass_attempt_no+1 nearly=47 local_params%nzhsym=nearly id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, & - 12000,completion,active_generation) + call run_decoder_engine(id2a,local_params, & + 12000,completion,active_generation,shared_memory%metadata%input_id, & + shared_memory%metadata%analysis_id,pass_attempt_no, & + min(shared_memory%metadata%valid_samples,nearly*3456)) + pass_attempt_no=pass_attempt_no+1 local_params%nzhsym=50 endif !ft8md if(local_params%nmode.eq.8 .and. local_params%lmultift8 .and. & .not. local_params%nagain .and. local_params%ndiskdat) then - npts1=180000 if(local_params%ndecoderstart.lt.2) then nearly=41 local_params%lmultift8=.false. local_params%nzhsym=nearly id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, & - 12000,completion,active_generation) + call run_decoder_engine(id2a,local_params, & + 12000,completion,active_generation,shared_memory%metadata%input_id, & + shared_memory%metadata%analysis_id,pass_attempt_no, & + min(shared_memory%metadata%valid_samples,nearly*3456)) + pass_attempt_no=pass_attempt_no+1 if(local_params%ndecoderstart.lt.2) then nearly=46 local_params%lmultift8=.false. local_params%nzhsym=nearly id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) id2a(nearly*3456+1:)=0 - call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, & - 12000,completion,active_generation) + call run_decoder_engine(id2a,local_params, & + 12000,completion,active_generation,shared_memory%metadata%input_id, & + shared_memory%metadata%analysis_id,pass_attempt_no, & + min(shared_memory%metadata%valid_samples,nearly*3456)) + pass_attempt_no=pass_attempt_no+1 endif if(local_params%ndecoderstart.eq.0) nearly=49 if(local_params%ndecoderstart.eq.1) nearly=50 local_params%lmultift8=.true. shared_memory%payload%params%nzhsym=nearly - id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) - id2a(nearly*3456+1:)=0 - dd(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) - dd(nearly*3456+1:)=0 - dd8(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) - dd8(nearly*3456+1:)=0 if(local_params%ndecoderstart.eq.0) shared_memory%payload%params%nzhsym=49 if(local_params%ndecoderstart.eq.1) shared_memory%payload%params%nzhsym=50 else @@ -132,36 +159,11 @@ subroutine jt9a() if(local_params%ndecoderstart.eq.3) nearly=49 if(local_params%ndecoderstart.eq.4) nearly=50 shared_memory%payload%params%nzhsym=nearly - id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) - id2a(nearly*3456+1:)=0 - dd(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) - dd(nearly*3456+1:)=0 - dd8(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456) - dd8(nearly*3456+1:)=0 if(local_params%ndecoderstart.eq.2) shared_memory%payload%params%nzhsym=48 if(local_params%ndecoderstart.eq.3) shared_memory%payload%params%nzhsym=49 if(local_params%ndecoderstart.eq.4) shared_memory%payload%params%nzhsym=50 endif - elseif (local_params%nmode.eq.8 .and. local_params%lmultift8 .and. .not. & - local_params%ndiskdat) then - npts1=min(180000,local_params%nzhsym*3456) - dd(1:npts1)=shared_memory%payload%id2(1:npts1) - dd(npts1+1:)=0 - rms=sum(abs(dd(1:10))) + sum(abs(dd(76001:76010))) + sum(abs(dd(151670:151680))) - dd8(1:npts1)=dd(1:npts1) - dd8(npts1+1:)=0 - -!### WHY WAS THIS STUFF HERE ??? ### -! if(rms.gt.0.001) then -! dd(1:npts1)=shared_memory%payload%dd2(1:npts1) -! dd8(1:npts1)=dd(1:npts1) -!print *,'win7',rms -! else ! workaround for zero data values of dd2 array under WinXP -! dd(1:npts1)=shared_memory%payload%id2(1:npts1) -! dd8(1:npts1)=dd(1:npts1) -!print *, 'winxp',rms -! endif -!### + local_params%nzhsym=nearly endif !end ft8md @@ -169,6 +171,19 @@ subroutine jt9a() ! MSK144 call decode_msk144_core(shared_memory%payload%id2, local_params, data_dir, & completion) + elseif(local_params%nmode.eq.8.or.local_params%nmode.eq.5.or.local_params%nmode.eq.9.or. & + local_params%nmode.eq.65.or.local_params%nmode.eq.66.or. & + local_params%nmode.eq.240.or.local_params%nmode.eq.241.or.local_params%nmode.eq.242) then + pass_valid_samples=min(shared_memory%metadata%valid_samples,180000) + if(local_params%nmode.eq.9.or.local_params%nmode.eq.65) & + pass_valid_samples=min(shared_memory%metadata%valid_samples,720000) + if(local_params%nmode.eq.66.or.local_params%nmode.eq.240.or. & + local_params%nmode.eq.241.or.local_params%nmode.eq.242) & + pass_valid_samples=min(shared_memory%metadata%valid_samples,local_params%ntr*12000) + call run_decoder_engine(shared_memory%payload%id2, & + local_params,12000,completion,active_generation, & + shared_memory%metadata%input_id,shared_memory%metadata%analysis_id, & + pass_attempt_no,pass_valid_samples) else ! Normal decoding pass call multimode_decoder_core(shared_memory%payload%ss, & @@ -191,6 +206,7 @@ subroutine jt9a() 999 call decoder_ipc_progress_unbind() call timer('decoder ',101) + if(layout_status.ne.0) stop 1 return end subroutine jt9a diff --git a/lib/jt9a_stub.f90 b/lib/jt9a_stub.f90 index ca06055f..f250ce4c 100644 --- a/lib/jt9a_stub.f90 +++ b/lib/jt9a_stub.f90 @@ -1,9 +1,4 @@ -! Headless stub for jt9a(): the GUI shared-memory worker loop (lib/jt9a.f90) -! is excluded from headless builds so jt9 links zero Qt (the real jt9a -! depends on QSharedMemory). The headless jt9 is driven by `--stream` -! or a WAV file; the GUI-worker entry is unreachable in normal use. If reached -! (bare `jt9` with no --stream and no input file), fail clean with a diagnostic -! instead of attaching shared memory (which the real jt9a aborts on). +! Reject shared-memory worker mode in the streaming-only executable. subroutine jt9a() use, intrinsic :: iso_fortran_env, only: error_unit write(error_unit,'(a)') 'jt9: GUI shared-memory worker mode is not available '// & diff --git a/lib/jt9com.f90 b/lib/jt9com.f90 index fc0577a2..5383a82d 100644 --- a/lib/jt9com.f90 +++ b/lib/jt9com.f90 @@ -1,7 +1,7 @@ - use, intrinsic :: iso_c_binding, only: c_int, c_short, c_float, c_char, c_bool + use, intrinsic :: iso_c_binding, only: c_int, c_int64_t, c_short, c_float, c_char, c_bool include 'constants.f90' - integer(c_int), parameter :: DECODER_IPC_VERSION = 2 + integer(c_int), parameter :: DECODER_IPC_VERSION = 4 integer(c_int), parameter :: DECODER_IPC_IDLE = 0 integer(c_int), parameter :: DECODER_IPC_READY = 1 integer(c_int), parameter :: DECODER_IPC_DECODING = 2 @@ -18,6 +18,18 @@ integer(c_int) :: progress end type decoder_ipc_control + type, bind(C) :: decoder_ipc_field_layout + integer(c_int) :: offset, bytes + end type decoder_ipc_field_layout + + type, bind(C) :: decoder_ipc_layout + integer(c_int) :: magic, protocol_version, header_bytes, payload_bytes + integer(c_int) :: logical_bytes, payload_offset, capabilities + integer(c_int) :: int_bytes, short_bytes, float_bytes, bool_bytes, char_bytes + integer(c_int) :: endian_marker, field_count + type(decoder_ipc_field_layout) :: fields(96) + end type decoder_ipc_layout + type, bind(C) :: params_block integer(c_int) :: nutc logical(c_bool) :: ndiskdat @@ -113,7 +125,16 @@ type(params_block) :: params end type dec_data + type, bind(C) :: decoder_input_metadata + integer(c_int64_t) :: input_id + integer(c_int64_t) :: analysis_id + integer(c_int) :: attempt_no + integer(c_int) :: valid_samples + end type decoder_input_metadata + type, bind(C) :: shared_dec_data type(decoder_ipc_control) :: control + type(decoder_ipc_layout) :: layout type(dec_data) :: payload + type(decoder_input_metadata) :: metadata end type shared_dec_data diff --git a/lib/jt9w.f90 b/lib/jt9w.f90 index 47623e7b..969cffea 100644 --- a/lib/jt9w.f90 +++ b/lib/jt9w.f90 @@ -19,8 +19,8 @@ program jt9w read(60,end=999) nutc,nfqso,ntol,ndepth,nmode,nsubmode,ss,id2 if(nutc.ne.iutc) cycle ntol=100 - call decode9w(nutc,nfqso,ntol,nsubmode,ss,id2,sync,nsnr,xdt,freq,decoded) - write(*,1100) nutc,nsnr,xdt1-1.0,nint(freq),decoded + call decode9w(nfqso,ntol,nsubmode,ss,184,id2,sync,nsnr,xdt,freq,decoded) + write(*,1100) nutc,nsnr,xdt,nint(freq),decoded 1100 format(i4.4,i4,f5.1,i5,1x,'@',1x,a22) exit enddo diff --git a/lib/jtty/genjtty.f90 b/lib/jtty/genjtty.f90 index 80be9c02..65294a15 100644 --- a/lib/jtty/genjtty.f90 +++ b/lib/jtty/genjtty.f90 @@ -8,23 +8,37 @@ subroutine genjtty(umsg,itone,nsym) parameter (MAX_TONES=59*16) !Max number of channel symbols character*80 umsg !User-formatted message integer itone(MAX_TONES) !Array of tone frequencies for this message + + interface + subroutine genjtty_profile(umsg,exchange_profile,itone,nsym,frame_starts,is_final) + use jtty_mod, only: MAX_FRAMES + character(len=80), intent(inout) :: umsg + integer, intent(in) :: exchange_profile + integer, intent(out) :: itone(59*MAX_FRAMES),nsym + integer, intent(out), optional :: frame_starts(MAX_FRAMES) + integer, intent(in), optional :: is_final + end subroutine genjtty_profile + end interface + call genjtty_profile(umsg,JTTY_EXCHANGE_UNKNOWN,itone,nsym) return end subroutine genjtty -subroutine genjtty_profile(umsg,exchange_profile,itone,nsym) +subroutine genjtty_profile(umsg,exchange_profile,itone,nsym,frame_starts,is_final) use jtty_mod, only: pack_jtty,MAX_FRAMES implicit none character(len=80), intent(inout) :: umsg integer, intent(in) :: exchange_profile integer, intent(out) :: itone(59*MAX_FRAMES),nsym + integer, intent(out), optional :: frame_starts(MAX_FRAMES) + integer, intent(in), optional :: is_final character(len=34) :: frames(MAX_FRAMES) integer :: nframes nsym=0 - call pack_jtty(umsg,frames,nframes,exchange_profile) + call pack_jtty(umsg,frames,nframes,exchange_profile,frame_starts,is_final) if(nframes.le.0) return call genjtty_frames(frames,nframes,itone,nsym) end subroutine genjtty_profile @@ -70,7 +84,7 @@ end subroutine genjtty_frames subroutine genjtty_atoms_c(c_atoms,natoms,itone,nsym,status) bind(C,name='genjtty_atoms_c') use iso_c_binding, only: c_char,c_int,c_null_char - use packjt77_grammar, only: pack77_arrl_section_index + use packjt77_grammar, only: pack77_arrl_section_index,pack77_arrl_section_name use jtty_mod, only: jtty_source_atom,jtty_source_atom_c,JTTY_ATOM_CALL, & JTTY_ATOM_EXCH_NUM,JTTY_ATOM_EXCH_LOC,JTTY_ATOM_EXCH_PAIR, & JTTY_ATOM_CONTROL,JTTY_ATOM_GRID4,jtty_call_atom,jtty_exch_num_atom, & @@ -119,7 +133,7 @@ subroutine genjtty_atoms_c(c_atoms,natoms,itone,nsym,status) bind(C,name='genjtt if(c_atoms(i)%subtype.ne.1) return if(c_atoms(i)%role.lt.0 .or. c_atoms(i)%role.gt.5) return section_index=pack77_arrl_section_index(descriptor_text) - if(section_index.lt.1) then + if(section_index.lt.1 .or. descriptor_text.ne.pack77_arrl_section_name(section_index)) then status=JTTY_ENCODE_UNKNOWN_SECTION return endif diff --git a/lib/jtty/jtty_design.md b/lib/jtty/jtty_design.md index 9448c8db..6755cb12 100644 --- a/lib/jtty/jtty_design.md +++ b/lib/jtty/jtty_design.md @@ -2,44 +2,29 @@ JTTY is a new digital mode designed for fast RTTY-like contest exchanges and other keyboard-to-keyboard communication on the amateur radio bands. It has an operational feel similar to standard RTTY, but far better weak-signal performance and a lower error rate. JTTY transmissions can start at any time and typically last a few seconds. Any arbitrary message can be sent using letters, digits, spaces, and punctuation. Source encoding is especially well optimized for the short, fixed-format messages generally used in RTTY-style radio contesting. -## Frame and waveform +This overview describes the design and gives examples of its use. The detailed protocol and source-interface rules are defined in [jtty_source_encoding.txt](jtty_source_encoding.txt). N1MM setup and macro examples are in [jtty_n1mm_integration.md](jtty_n1mm_integration.md); transmit checks are in [jtty_tx_manual_checks.md](jtty_tx_manual_checks.md). -A transmission contains one or more 1.888-second frames. Each frame carries a 32-bit source-grammar word followed by two universal control bits: a reserved bit that is always zero and an end-of-message (EOM) bit set only on the final source atom. A 12-bit CRC extends this 34-bit payload to 46 bits. A tail-biting, rate-1/2 convolutional code with constraint length K=10 produces 92 coded bits. +## Frame and waveform -The waveform is Gaussian-smoothed four-tone frequency-shift keying (4-GFSK), with two coded bits per tone symbol. A frame contains a 13-symbol synchronization sequence followed by 46 coded symbols. At 12000/384 = 31.25 baud, its duration is (13+46)/31.25 = 1.888 seconds. The occupied bandwidth (99% of transmitted power) is 127 Hz. +A transmission contains one or more 1.888-second frames. The waveform is Gaussian-smoothed four-tone frequency-shift keying (4-GFSK) at 31.25 baud. The occupied bandwidth (99% of transmitted power) is 127 Hz. Each frame carries one source atom, protected by a CRC and a tail-biting convolutional code. An end-of-message (EOM) bit marks the final atom. -The receiver verifies FEC, CRC, the universal reserved-zero bit, and the complete source grammar. A structurally invalid source word is discarded before display, EOM handling, slot creation, or signal subtraction. +The receiver verifies FEC, CRC, the reserved-zero bit, and the complete source grammar before using a decoded atom. An invalid atom is discarded before display, EOM handling, slot creation, or signal subtraction. ## Source contracts JTTY separates automatic text packing from typed native actions. -Ordinary keyboard text, `sjtty` input, externally queued strings, and untagged N1MM/MMTTY text use the literal source interface. Text is folded to uppercase, spaces are normalized, and unsupported characters become `#`. The explicit RTTY Roundup profile also canonicalizes report-prefixed serials as described below. The encoder chooses the minimum-frame combination of recognized compact atoms and five-character TEXT5 frames that preserves the resulting normalized text exactly. "Literal" identifies the text interface, not a requirement to use TEXT5 or bypass profile normalization. +Ordinary keyboard text, `sjtty` input, externally queued strings, and untagged N1MM/MMTTY text use the literal source interface. Text is folded to uppercase, spaces are normalized, and unsupported characters become `#`. The explicit RTTY Roundup profile also canonicalizes report-prefixed serials. The encoder chooses the minimum-frame combination of recognized compact atoms and five-character TEXT5 frames that preserves the resulting normalized text exactly. "Literal" identifies the text interface, not a requirement to use TEXT5 or bypass profile normalization. The eight shipped JTTY function-key templates use a NativeMacro contract. When a default template is selected, it is compiled to typed call and exchange atoms before placeholder expansion. Native atoms provide compact transmission and unambiguous fields for future logger integration. A customized template that does not match a native form falls back to automatic text packing after normal placeholder expansion. A recognized native template with invalid runtime data is rejected rather than silently transmitted with different semantics. -Earlier JTTY packing minimized frames using compact calls, a generic `599 ` plus five-character format, and TEXT5. STRUCT30 replaced that generic exchange format with richer typed atoms. Restricting ordinary input to TEXT5 avoided guessing whether `05` meant a serial, zone, or check, but also lost unambiguous callsign compaction. Automatic packing retains the minimum-frame algorithm, with context-free recognition and an explicit exchange profile that can normalize serials and enable additional typed candidates. +Restricting ordinary input to TEXT5 would avoid guessing whether `05` meant a serial, zone, or check, but would also lose unambiguous callsign compaction. Automatic packing uses a minimum-frame algorithm, with context-free recognition and an explicit exchange profile that can normalize serials and enable additional typed candidates. ## Automatic text packing -At complete token boundaries, the packer considers the six callsign forms below, registered control phrases (including within longer messages), and these STRUCT30 forms: - -| Text form | Automatic atom | -| --- | --- | -| Canonical unsigned decimal, optionally preceded by `599` | GENERIC_NUMERIC, 0-131071, with no leading zeros except `0` | -| `599 <location>` | GENERIC_QTH, exactly two or three base-36 characters including at least one letter | -| Valid four-character Maidenhead locator, optionally preceded by `599` | GRID4 | -| `<count><class> <section>` | CLASS_SECTION, count 1-32, class A-F, registered ARRL/RAC section | - -Every candidate must pass the existing codec validation and render exactly as its span in the normalized text. Calls must round-trip through the standard callsign codec; QTH tokens must obey the wire format's canonical length rules. - -The GUI captures an exchange profile from the existing special operating activity when each message is submitted: Unknown, Field Day, or RTTY Roundup. No activity means Unknown even though native macros default to serial exchanges. All profiles retain the context-free candidates above. Only RTTY Roundup adds candidates: full `599 <number>` as SERIAL and full `599 <location>` as STATE_PROVINCE, using the native exchange rules and requiring a location token to contain a letter. Bare numbers are never inferred as serials. Field Day adds no candidates because class/section syntax is already self-identifying. No new configuration or wire format is needed. - -Zones, checks, ages, power, license years, other specific location categories, zone/location pairs, and serial/time pairs are not inferred. Under RTTY Roundup, equally compact serial or state/province candidates take precedence over their generic equivalents through the subtype ordering below. +Automatic packing recognizes calls, registered control phrases, generic numbers and locations, grids, and Field Day class/section exchanges at complete token boundaries. A dynamic program over character offsets selects the fewest frames under this recognition policy, rather than greedily taking the first compact form. -A dynamic program over character offsets selects the fewest frames under this recognition policy, rather than greedily taking the first compact form. TEXT5 consumes exactly five characters except at the end; an interior short fragment cannot be padded to reach a compact candidate because that would change the text. Structured atoms supply an implicit single space when followed by another token. Equal-cost alternatives prefer a structured atom, then the longest consumed span, then atom kind/subtype/role order. - -Before packing, the explicit RTTY Roundup profile canonicalizes a decimal token following a complete `599` token as a serial: `599 05` becomes `599 005`, and `599 0123` becomes `599 123`. Both use one SERIAL frame. Eligible tokens contain one to six digits with value 0-131071; unsupported tokens retain their spelling and use the normal fallback. Bare digits and all text under Unknown or Field Day retain their spelling after ordinary normalization. The canonical message is returned to the GUI for display and logging. If serial normalization expands the message beyond 80 characters, submission is rejected rather than truncating it. +The GUI captures an exchange profile from the existing special operating activity when each message is submitted: Unknown, Field Day, or RTTY Roundup. No activity means Unknown even though native macros default to serial exchanges. RTTY Roundup also recognizes report-prefixed serial and state/province exchanges and normalizes serial spelling. The detailed recognition, normalization, spacing, and tie-breaking rules are in the specification's "Automatic text packing" section. The result need not match the theoretical minimum with perfect knowledge of exchange semantics. Under Unknown or Field Day, `599 001` and `599 05` still take two frames. An explicit codec caller can encode `599 05` as a CQ zone in one frame, but the current GUI macros do not expose that numeric kind; RTTY Roundup explicitly selects serial meaning instead. @@ -47,64 +32,19 @@ The result need not match the theoretical minimum with perfect knowledge of exch ## Source grammar -Bits 31-32 select one of four message types. The complete normative definition, including field ranges, enum assignments, validity rules, and golden vectors, is in [jtty_source_encoding.txt](jtty_source_encoding.txt). - -| `i2.n2` | Contents | Canonical rendering | -| --- | --- | --- | -| `0.0` | CQ call action | `CQ <call> CQ` | -| `0.1` | CALL action | `<call>` | -| `0.2` | TU/CQ call action | `TU <call> CQ` | -| `0.3` | CALL/TU action | `<call> TU` | -| `1.0` | CALL/AGN call action | `<call> AGN?` | -| `1.1` | TU NOW/CALL action | `TU NOW <call>` | -| `1.2`, `1.3` | Reserved | Invalid in version 1 | -| `2` | STRUCT30 | Typed exchange, pair, time, control, or GRID4 atom | -| `3` | TEXT5 | Five six-bit JTTY characters | - -STRUCT30 places a 27-bit family body before a three-bit family selector: - -| Family | Name | Fields, in transmitted bit order | -| --- | --- | --- | -| `000` | EXCH_NUM | `role1 + number_kind4 + value17 + zero5` | -| `001` | EXCH_LOC | `role1 + location_kind4 + length1 + base36_token16 + zero5` | -| `010` | EXCH_PAIR | `pair_schema3 + pair_data23 + zero1` | -| `011` | EXCH_NUM_TIME | `role1 + serial14 + minute_of_day11 + zero1` | -| `100` | MISC | `subtype4 + subtype_data23` | -| `101` | Profiled/dense extension | Reserved | -| `110` | Versioned extension | Reserved | -| `111` | Guard space | Invalid | - -The assigned fields cover serials, zones, ages, power, checks, four-digit first-license years, generic numbers, two- or three-character locations, zone/location pairs, Field Day class/section pairs, serial/time pairs, GRID4, and 18 common control phrases. Native values render canonically: serials use at least three digits, zones and checks at least two, UTC time exactly four, and license years exactly four. A full exchange adds `599`; a field-only atom omits it. Decimal width, separator style, `5NN` spelling, and visible repetition do not consume wire bits. - -The former `i2=2` meaning, literal `599 ` followed by five characters, has been intentionally replaced by STRUCT30. There is no discriminator: old receivers display new STRUCT30 bits as `599` text, and some old type-2 frames are valid new STRUCT30 words with different meanings. JTTY is unreleased, so there is no legacy decoder mode. Automatic packing uses only the current grammar; unrecognized `599 ...` text remains available through TEXT5. - -## Native function keys +A source atom carries a compact callsign action, a typed STRUCT30 exchange or control, or five TEXT5 characters. STRUCT30 covers numeric and location fields, paired exchanges, UTC time, grids, and common control phrases. Typed atoms have canonical renderings; formatting choices and visible repetition do not consume wire bits. -Current native templates and control phrases match after case folding and -whitespace normalization, before placeholders are expanded. The three -superseded serial templates are accepted only in their exact saved-default -form so edited variants remain literal. +The bit layouts, field ranges, enum assignments, validity rules, and golden vectors are kept in [jtty_source_encoding.txt](jtty_source_encoding.txt). -| Key | Template | Native meaning | -| --- | --- | --- | -| F1 | `CQ %M CQ` | CQ with the configured call | -| F2 | `%H %E` | His call, then configured full exchange | -| F3 | `%H TU CQ %M CQ` | His call/TU, then CQ with the configured call | -| F4 | `%M` | Configured call | -| F5 | `%H` | His call | -| F6 | `TU NOW %Q %E` | Queued call, then configured full exchange | -| F7 | `%H AGN?` | Request repeat from his call | -| F8 | `%E` | Configured full exchange | - -Keyboard shortcuts and the clickable F1-F8 buttons select the same actions. Native atom sequences use an implicit single-space separator and set EOM only on the last atom. Consecutive queued native messages do not need an intervening TEXT5 space frame. +## Native function keys -`%E` parses the selected contest profile: the default is a decimal serial, FIELD_DAY is exactly `<count><class> <section>`, and RTTY is a decimal serial or canonical two- or three-character state/province. `%G` is a field-only GRID4; the exact `599 %G` template selects its full-exchange role. The exact old F2, F6, and F8 defaults using `599 %N` remain recognized during migration and are replaced only when unchanged in saved settings. Edited variants remain literal. +Keyboard shortcuts and the clickable F1-F8 buttons select the same actions. `%E` supplies the configured contest exchange and `%G` a grid. The default templates, profile rules, and saved-template migration are defined in the specification's "Native function keys" section. The practical native GUI and N1MM transmit subset covers Call8, serial or RTTY state/province exchanges, Field Day class/section, GRID4, and registered control phrases. Automatic text packing additionally uses GENERIC_NUMERIC and GENERIC_QTH without assigning contest-specific meanings. Other normative STRUCT30 types are decoded, validated, and rendered canonically but are not inferred from text or exposed as general-purpose macros yet. ## Tagged N1MM actions -N1MM may explicitly request native encoding by starting TXTEXT with `[[JTTY:<ACTION>]]`. The assigned actions are `CQ`, `CALL_EXCH`, `CALL_TU_CQ`, `MYCALL`, `HISCALL`, `TU_NOW_EXCH`, `CALL_MY`, `CALL_TU_MY`, `EXCH`, `GRID`, and `CONTROL`. N1MM expands `{MYCALL}`, `!` or `{CALL}`, and `{EXCH}` before WSJT-X validates the action payload under the active profile. +N1MM may explicitly request native encoding by starting TXTEXT with `[[JTTY:<ACTION>]]`. N1MM expands its macros before WSJT-X validates the action payload under the active profile. Untagged N1MM text remains literal. A malformed tag, unknown action, invalid call, invalid exchange or grid, unregistered control phrase, or profile mismatch is rejected rather than transmitted as literal bracket text. The exact grammar and action payloads are in [jtty_source_encoding.txt](jtty_source_encoding.txt), with operating examples in [jtty_n1mm_integration.md](jtty_n1mm_integration.md). diff --git a/lib/jtty/jtty_design.txt b/lib/jtty/jtty_design.txt deleted file mode 100644 index b117e77c..00000000 --- a/lib/jtty/jtty_design.txt +++ /dev/null @@ -1,231 +0,0 @@ -JTTY: A possible WSJT mode for fast RTTY-like contest exchanges - -JTTY aims for an operational feel similar to conventional amateur RTTY, -with much better weak-signal performance and a much lower error rate. -Transmissions may start at any time and normally last a few seconds. - -FRAME AND WAVEFORM - -Each frame carries 32 message-grammar bits, a reserved-zero bit, and a -universal end-of-message bit. A 12-bit CRC extends the payload to 46 bits. -A tail-biting rate-1/2 convolutional code with constraint length K=10 -produces 92 coded bits. - -JTTY uses Gaussian-smoothed four-tone frequency-shift keying (4-GFSK). -A frame has 13 synchronization symbols followed by 46 coded symbols. -At 12000/384 = 31.25 baud, one frame lasts 1.888 seconds. Nominal -half-power bandwidth is 125 Hz. - -The receiver verifies FEC, CRC, the universal reserved-zero bit, and the -complete source grammar. An invalid source word is discarded before it can -be displayed, mark EOM, create a receive slot, or participate in signal -subtraction. - -SOURCE CONTRACTS - -Ordinary keyboard text, sjtty input, externally queued strings, and untagged -N1MM/MMTTY text use the literal source interface. After uppercase and space -normalization and replacement of unsupported characters with '#', automatic -packing selects the minimum-frame combination of recognized compact atoms -and TEXT5 that preserves the normalized text exactly. Explicit RTTY Roundup -also applies serial normalization below before packing. "Literal" identifies -the text interface, not a requirement to use TEXT5 or bypass that normalization. - -The eight shipped JTTY function-key templates are explicit native actions. -Their call, profile-exchange, and grid placeholders compile to typed atoms. A -customized template that does not match a native form uses automatic text -packing after normal placeholder expansion. If a recognized native template -has invalid runtime data, -transmission is rejected instead of changing meaning through a literal -fallback. - -Earlier JTTY packing minimized frames using compact calls, a generic "599 " -plus five-character format, and TEXT5. STRUCT30 replaced that exchange format -with richer typed atoms. Restricting ordinary input to TEXT5 avoided guessing -whether "05" meant a serial, zone, or check, but also lost unambiguous call -compaction. Automatic packing retains the minimum-frame algorithm with -context-free recognition and an explicit exchange profile that can normalize -serials and enable additional typed candidates. - -AUTOMATIC TEXT PACKING - -At complete token boundaries the packer considers: - - * The six call forms below, with an exact standard-call codec round trip. - * Registered CONTROL phrases, including inside longer messages. - * Canonical unsigned decimal 0-131071 as GENERIC_NUMERIC, field-only or - preceded by "599 ". Leading zeros are not canonical except for "0". - * "599 " plus a canonical two- or three-character base-36 token containing - at least one letter, as GENERIC_QTH. The wire length rules apply. - * Valid four-character Maidenhead GRID4, field-only or preceded by "599 ". - * CLASS_SECTION: count 1-32, class A-F, registered ARRL/RAC section. - -Every candidate must pass codec pack/unpack validation and render exactly as -its span in the normalized text. At submission the GUI captures Unknown, -Field Day, or RTTY -Roundup from the existing special operating activity. No activity means -Unknown even though native macros default to serial exchanges. All profiles -retain the context-free candidates above; Field Day adds no further candidates. - -Only RTTY Roundup adds full "599 <number>" SERIAL and full "599 <location>" -STATE_PROVINCE candidates under the native exchange rules. Locations must -contain a letter. Exact rendering after profile normalization remains -mandatory; bare serials are never -inferred. Zone, check, age, power, license-year, other specific location, -zone/location, and serial/time meanings are not inferred. No new configuration -or wire format is needed. Native actions retain their typed exchange semantics. - -Before packing, explicit RTTY Roundup canonicalizes a decimal token following -a complete "599" token as a serial: "599 05" becomes "599 005", and -"599 0123" becomes "599 123". Tokens must contain one to six digits and have -value 0-131071. Unsupported tokens retain their spelling for normal fallback. -Bare digits and Unknown or Field Day input retain their spelling after ordinary -normalization. The canonical message is returned to the GUI for display and -logging. Expansion beyond 80 characters is rejected rather than truncated. - -A dynamic program over source-character offsets chooses the minimum number -of frames under this recognition policy, rather than a greedy sequence. -TEXT5 consumes exactly five characters except at the end. Interior padding -cannot be used to reach a compact candidate because it would change the text. -Structured candidates consume one source space after their rendered span -when another token follows, matching the receiver's implicit separator. -Equal-cost choices prefer a structured atom, then the longest consumed span, -then ascending atom kind/subtype/role. -The subtype ordering prefers typed serial and state/province candidates over -generic candidates of equal frame count and span under RTTY Roundup. - -This minimum need not equal the theoretical minimum with perfect knowledge -of contest semantics. Examples for ordinary text under Unknown or Field Day, -without a native action: - --------------------------------------------------------------------------------- -Text Frames Encoding or limitation --------------------------------------------------------------------------------- -CQ K1ABC CQ 1 CQ call -CQ KA1ABC CQ 1 CQ call -WB9XYZ 1 Call -WB9XYZ TU CQ KA1ABC CQ 2 Two call atoms -WB9XYZ 599 123 2 Call plus generic number -599 123 1 Generic numeric exchange -599 MA 1 Generic QTH exchange -599 FN42 1 Full-role GRID4 -1D EMA 1 Class/section pair -599 001 2 Leading zeros must be preserved -599 05 2 No numeric kind is inferred -599 BRUCE 2 No generic five-character exchange --------------------------------------------------------------------------------- - -Under RTTY Roundup, "599 001" takes one frame and "K1ABC 599 001" takes two. -"599 123" and "599 MA" use SERIAL and STATE_PROVINCE instead of generic atoms -without changing frame counts. "599 05" and "599 0123" become "599 005" and -"599 123", each in one frame. - -sjtty defaults to Unknown. Its optional leading argument ---exchange-profile=unknown|field-day|rtty-roundup applies to both the -one-message packing invocation and the eight-argument waveform invocation. -Invalid values are errors. Example: - - sjtty --exchange-profile=rtty-roundup "599 001" - -SOURCE GRAMMAR - --------------------------------------------------------------------------------- -i2.n2 Example Bits Purpose --------------------------------------------------------------------------------- -0.0 CQ K1ABC CQ call28 + n2 CQ call action -0.1 K1ABC call28 + n2 CALL action -0.2 TU K1ABC CQ call28 + n2 TU/CQ action -0.3 K1ABC TU call28 + n2 CALL/TU action -1.0 K1ABC AGN? call28 + n2 CALL/AGN action -1.1 TU NOW K1ABC call28 + n2 TU NOW/CALL action -1.2 (reserved; invalid) -1.3 (reserved; invalid) -2 599 123 body27 + family3 STRUCT30 -3 HELLO 6 6 6 6 6 TEXT5 --------------------------------------------------------------------------------- - -Bits 1-30 contain the form listed above and bits 31-32 contain i2. Bit 33 -is always zero. Bit 34 is one only on the final atom of a source message. - -STRUCT30 replaces the former i2=2 "599 " plus five-character form: - --------------------------------------------------------------------------------- -Family Name Body fields, in transmitted bit order --------------------------------------------------------------------------------- -000 EXCH_NUM role1 kind4 value17 zero5 -001 EXCH_LOC role1 kind4 length1 token16 zero5 -010 EXCH_PAIR schema3 pair_data23 zero1 -011 EXCH_NUM_TIME role1 serial14 minute11 zero1 -100 MISC subtype4 subtype_data23 -101 PROFILED reserved; invalid in version 1 -110 VERSIONED reserved; invalid in version 1 -111 INVALID source-validity guard space --------------------------------------------------------------------------------- - -EXCH_NUM kinds 0-7 are serial, CQ zone, ITU zone, age, power, check, -first-license year, and generic numeric. EXCH_LOC kinds 0-4 are -state/province, ARRL/RAC section, country/prefix, generic QTH, and local -administrative code. EXCH_PAIR schemas are ZONE_LOC3 and CLASS_SECTION. -MISC subtypes are CONTROL and GRID4. All other IDs are invalid. - -Full-role fields render with a "599 " prefix; field-only fields omit it. -Serials use at least three digits, zones and checks at least two, UTC time -exactly four, and first-license year exactly four. Structured atoms supply -one implicit trailing space; TEXT5 characters are appended verbatim. Final -trailing spaces and TEXT5 padding are not displayed. Formatting choices and -visible repetitions are not encoded in typed fields. - -NATIVE FUNCTION KEYS - --------------------------------------------------------------------------------- -Key Template Native atoms --------------------------------------------------------------------------------- -F1 CQ %M CQ CQ(my_call) -F2 %H %E CALL(his_call), configured full exchange -F3 %H TU CQ %M CQ CALL_TU(his_call), CQ(my_call) -F4 %M CALL(my_call) -F5 %H CALL(his_call) -F6 TU NOW %Q %E TU_NOW_CALL(queue_call), configured exchange -F7 %H AGN? CALL_AGN(his_call) -F8 %E configured full exchange --------------------------------------------------------------------------------- - -Current templates and control phrases match case-insensitively while ignoring -whitespace differences, before placeholder expansion. Superseded serial -templates match only in their exact saved-default form. Keyboard F1-F8 -shortcuts and clickable buttons select the same actions. EOM is set only on -the final native atom; queued native messages do not require a TEXT5 spacing -frame between them. - -%E uses the selected profile: decimal serial by default, exact -"<count><class> <section>" for FIELD_DAY, and either decimal serial or a -canonical two- or three-character state/province for RTTY. %G is field-only -GRID4; the exact "599 %G" template selects full role. Exact old F2, F6, and F8 -defaults using 599 %N remain recognized during migration and are replaced only -when unchanged in saved settings; edited variants remain literal. - -N1MM can opt into native encoding with a leading [[JTTY:<ACTION>]] marker in -TXTEXT. Actions are CQ, CALL_EXCH, CALL_TU_CQ, MYCALL, HISCALL, TU_NOW_EXCH, -CALL_MY, CALL_TU_MY, EXCH, GRID, and CONTROL. Untagged N1MM strings use the -literal source interface with automatic text packing. -Invalid or unknown tagged requests are rejected, not transmitted as bracket -text. See jtty_source_encoding.txt and jtty_n1mm_integration.md for the payload -grammar. - -The practical native transmit subset is Call8, serial and RTTY state/province, -Field Day class/section, GRID4, and registered controls. Automatic text packing -also generates GENERIC_NUMERIC and GENERIC_QTH. Other normative atoms have -canonical receive decoding and rendering but are not inferred from text or -exposed as general-purpose macros in this version. - -The complete normative source definition, field ranges, enum assignments, -validation rules, and binary/hex vectors are in jtty_source_encoding.txt. - -COMPATIBILITY - -The old i2=2 form is intentionally incompatible with STRUCT30. There is no -version discriminator: old receivers display new STRUCT30 bits as "599" text, -and some old type-2 frames are valid new STRUCT30 words with different -meanings. JTTY is unreleased, so no legacy decoder mode is retained. Automatic -packing uses only the current grammar; unrecognized "599 ..." text remains -available through TEXT5. diff --git a/lib/jtty/jtty_mdecode.f90 b/lib/jtty/jtty_mdecode.f90 index 4f77d51f..8af7f3f6 100644 --- a/lib/jtty/jtty_mdecode.f90 +++ b/lib/jtty/jtty_mdecode.f90 @@ -1,6 +1,6 @@ module jtty_mdec - use iso_fortran_env, only: int64 + use iso_fortran_env, only: int64, real64 use iso_c_binding, only: c_ptr,c_null_ptr,c_associated,c_f_pointer, & c_float_complex,c_size_t use jtty_mod, only: MAX_FRAMES @@ -13,7 +13,7 @@ module jtty_mdec type :: decode real :: f1 = 0.0 !Synced audio frequency real :: xdt = 0.0 !Synced DT (0 to 0.5 s) - real :: tsync = 0.0 !Time of sync from istart=1 + real(real64) :: tsync = 0.0_real64 real :: snrdb = 0.0 !SNR of decoded frame character(len=80) :: decoded = '' logical :: trailing_sep = .false. !decoded ends with an implicit separator column @@ -23,8 +23,9 @@ module jtty_mdec type :: message_assembly integer(int64) :: message_id = 0_int64 real :: f1 = 0.0 - real :: tsync = 0.0 - real :: start_tsync = 0.0 + real(real64) :: tsync = 0.0_real64 + real(real64) :: start_tsync = 0.0_real64 + real :: start_snrdb = 0.0 !SNR of the message's first frame; never reassigned after integer :: k = 0 character(len=80) :: decoded = '' logical :: trailing_sep = .false. @@ -32,15 +33,18 @@ module jtty_mdec type :: frame_fingerprint real :: f1 = 0.0 - real :: tsync = 0.0 + real(real64) :: tsync = 0.0_real64 end type frame_fingerprint type :: message_update integer(int64) :: message_id = 0_int64 real :: f1 = 0.0 - real :: start_tsync = 0.0 + real(real64) :: start_tsync = 0.0_real64 + real(real64) :: latest_tsync = 0.0_real64 + real :: snr = 0.0 character(len=80) :: decoded = '' logical :: complete = .false. + integer :: terminal = 0 end type message_update integer, parameter :: MAX_DECODES = 100 @@ -52,12 +56,20 @@ module jtty_mdec real, parameter :: FRAME_HISTORY_FREQ_TOLERANCE = 3.0 real, parameter :: NEAR_SIMULTANEOUS_FREQ_TOLERANCE = 12.0 real, parameter :: CONTINUATION_TIME_TOLERANCE = 0.1 + ! pn leaks ~SNR_LEAKAGE_K*pt of signal power; corrected ratio still asymptotes near (1-k)/k for very strong signals. + real, parameter :: SNR_LEAKAGE_K = 0.048 + real, parameter :: SNR_FLOOR_DB = -17.0 ! weaker than the weakest sometimes-decodable JTTY signal integer :: ndecodes = 0 integer :: nactive = 0 integer :: nrecent = 0 integer :: npending = 0 integer :: pending_first = 1 integer(int64) :: next_message_id = 1_int64 + integer, parameter :: UPDATE_GROWING=0, UPDATE_COMPLETE=1 + integer, parameter :: UPDATE_EXPIRED=2, UPDATE_RECEPTION_ENDED=3 + integer(int64) :: sample_origin = 0_int64 + integer(int64) :: first_search_sample = 0_int64 + logical :: explicit_receive_context = .false. type(message_assembly) :: active_messages(MAX_ACTIVE_MESSAGES) type(frame_fingerprint) :: recent_frames(MAX_RECENT_FRAMES) type(message_update), allocatable :: pending_updates(:) @@ -68,11 +80,11 @@ module jtty_mdec integer, parameter :: MAX_SUBTRACTED = 16 logical :: interferer_pending = .false. real :: interferer_f1 = 0.0 - real :: interferer_tsync = 0.0 + real(real64) :: interferer_tsync = 0.0_real64 integer :: interferer_payload(PAYLOAD_BITS) = 0 integer :: nsubtracted = 0 real :: subtracted_f1(MAX_SUBTRACTED) = 0.0 - real :: subtracted_tsync(MAX_SUBTRACTED) = 0.0 + real(real64) :: subtracted_tsync(MAX_SUBTRACTED) = 0.0_real64 integer :: subtracted_payload(PAYLOAD_BITS,MAX_SUBTRACTED) = 0 complex, allocatable, private :: sync_chirp_weights(:),sync_chirp_kernel(:) integer, private :: sync_chirp_samples=0,sync_chirp_first_bin=-1 @@ -90,6 +102,10 @@ module jtty_mdec integer, parameter, private :: MIN_SYNC_FFT_ORDER=11,MAX_SYNC_FFT_ORDER=13 type(sync_fft_cache), private :: sync_fft_caches(MIN_SYNC_FFT_ORDER:MAX_SYNC_FFT_ORDER) + interface prune_receive_state + module procedure prune_receive_state_real64, prune_receive_state_real32 + end interface + contains subroutine release_sync_fft_cache(cache) @@ -217,6 +233,12 @@ contains sync_chirp_output_count=0 end subroutine jtty_release_fft_resources + pure real(real64) function sample_time(index) + integer, intent(in) :: index + + sample_time=real(sample_origin+int(index-1,int64),real64)/12000.0_real64 + end function sample_time + subroutine reset_decode_search_state() nactive=0 nrecent=0 @@ -228,14 +250,16 @@ contains end subroutine discard_pending_updates pure logical function same_frame(f1_a,tsync_a,f1_b,tsync_b) - real, intent(in) :: f1_a,tsync_a,f1_b,tsync_b + real, intent(in) :: f1_a,f1_b + real(real64), intent(in) :: tsync_a,tsync_b same_frame=abs(f1_a-f1_b).lt.FRAME_HISTORY_FREQ_TOLERANCE .and. & abs(tsync_a-tsync_b).lt.FRAME_HISTORY_TIME_TOLERANCE end function same_frame pure logical function same_recent_frame(f1_a,tsync_a,f1_b,tsync_b) - real, intent(in) :: f1_a,tsync_a,f1_b,tsync_b + real, intent(in) :: f1_a,f1_b + real(real64), intent(in) :: tsync_a,tsync_b same_recent_frame=abs(f1_a-f1_b).lt.NEAR_SIMULTANEOUS_FREQ_TOLERANCE .and. & abs(tsync_a-tsync_b).lt.FRAME_HISTORY_TIME_TOLERANCE @@ -283,11 +307,16 @@ contains recent_frames(nrecent)%tsync=candidate%tsync end subroutine remember_recent_frame - subroutine queue_message_update(message,complete) + subroutine queue_message_update(message,complete,terminal) type(message_assembly), intent(in) :: message logical, intent(in) :: complete + integer, optional, intent(in) :: terminal type(message_update), allocatable :: grown(:) - integer :: i,index,new_capacity + integer :: i,index,new_capacity,status + + status=UPDATE_GROWING + if(complete) status=UPDATE_COMPLETE + if(present(terminal)) status=terminal do i=0,npending-1 index=pending_first+i @@ -295,6 +324,8 @@ contains pending_updates(index)%f1=message%f1 pending_updates(index)%decoded=message%decoded pending_updates(index)%complete=complete + pending_updates(index)%latest_tsync=message%tsync + pending_updates(index)%terminal=status return endif enddo @@ -318,8 +349,11 @@ contains pending_updates(index)%message_id=message%message_id pending_updates(index)%f1=message%f1 pending_updates(index)%start_tsync=message%start_tsync + pending_updates(index)%latest_tsync=message%tsync + pending_updates(index)%snr=message%start_snrdb pending_updates(index)%decoded=message%decoded pending_updates(index)%complete=complete + pending_updates(index)%terminal=status end subroutine queue_message_update subroutine remove_active_message(index) @@ -344,6 +378,7 @@ contains message%f1=candidate%f1 message%tsync=candidate%tsync message%start_tsync=candidate%tsync + message%start_snrdb=candidate%snrdb message%decoded=candidate%decoded if(message%decoded(1:4).eq.'599 ') & message%decoded='~'//trim(message%decoded) @@ -403,9 +438,10 @@ contains accepted=.true. end subroutine append_active_message - subroutine prune_receive_state(forward_tsync,frame_period) - real, intent(in) :: forward_tsync,frame_period - real :: oldest_revisit + subroutine prune_receive_state_real64(forward_tsync,frame_period) + real(real64), intent(in) :: forward_tsync + real, intent(in) :: frame_period + real(real64) :: oldest_revisit integer :: i,keep oldest_revisit=forward_tsync-real(MAX_RETRO_STEPS)*frame_period/4.0 @@ -424,13 +460,19 @@ contains if(oldest_revisit-active_messages(i)%tsync.gt. & real(MAX_CONTINUATION_GAP)*frame_period+ & CONTINUATION_TIME_TOLERANCE) then - call queue_message_update(active_messages(i),.false.) + call queue_message_update(active_messages(i),.false.,UPDATE_EXPIRED) call remove_active_message(i) else i=i+1 endif enddo - end subroutine prune_receive_state + end subroutine prune_receive_state_real64 + + subroutine prune_receive_state_real32(forward_tsync,frame_period) + real, intent(in) :: forward_tsync,frame_period + + call prune_receive_state_real64(real(forward_tsync,real64),frame_period) + end subroutine prune_receive_state_real32 subroutine jtty_tbcc_reencode_for_subtraction(payload, tones) integer, intent(in) :: payload(PAYLOAD_BITS) integer, intent(out) :: tones(TOTAL_K) @@ -474,7 +516,8 @@ contains real, intent(in) :: frame_period logical, intent(out) :: match,is_window_dupe integer, intent(out) :: nframes_gap - real :: df1,dtsync,qstep,resid,fp_resid,df_tol + real :: df1,df_tol + real(real64) :: dtsync,qstep,resid,fp_resid integer :: nstep,nfp df1=candidate%f1-existing%f1 @@ -546,10 +589,11 @@ contains integer :: nsloc(2),nfz,ntz,ncand,ic,nc,nstep_search integer :: nc0,n_ch0_ok integer :: ja_ch0_ok(16),jb_ch0_ok(16) - real :: f1_ch0_ok(16),tsync_ch0_ok(16) + real :: f1_ch0_ok(16) + real(real64) :: tsync_ch0_ok(16) integer :: nsync,nsymerrs real :: fc,fwid - real :: fpk,pa,pt,pn + real :: fpk,pa,pt,pn,pn_corrected real :: fbest,xdtbest real :: xdt_retry real, allocatable, save :: s0(:,:) @@ -581,7 +625,8 @@ contains type(decode) :: cand(MAXCAND) !Candidates for decoding type(decode) :: dec !Current successful decode logical :: use_interferer - real :: use_interferer_f1, use_interferer_tsync + real :: use_interferer_f1 + real(real64) :: use_interferer_tsync integer :: use_interferer_payload(PAYLOAD_BITS) ! Capture and clear the retro-resweep interferer request (if any) as the @@ -596,7 +641,7 @@ contains nsync=0 - if(istart.eq.istart0 .and. .not.use_interferer) then + if(istart.eq.istart0 .and. .not.use_interferer .and. .not.explicit_receive_context) then ndecodes=0 call reset_decode_search_state() endif @@ -666,7 +711,7 @@ contains call jtty_tbcc_reencode_for_subtraction(use_interferer_payload, tone_symbols_chk) tone_symbols_full(NSYNC_SYM+1:NFRAME_SYM)=tone_symbols_chk call subtract_jtty(c0, nana, nchunk6, tone_symbols_full, NFRAME_SYM, & - nss, use_interferer_f1, use_interferer_tsync-(istart-1)/12000.0) + nss, use_interferer_f1, real(use_interferer_tsync-sample_time(istart))) endif ! Look for up to 2 sync candidates in each quarter-frame (0.424 second) by 2*FTol rectangle in @@ -974,13 +1019,13 @@ contains do ir=1,nactive if(active_messages(ir)%f1.lt.fc-fwid .or. & active_messages(ir)%f1.gt.fc+fwid) cycle - if(abs(((istart-1)/12000.0 - active_messages(ir)%tsync) - & + if(abs((sample_time(istart) - active_messages(ir)%tsync) - & nframe6/6000.0) & .gt. 0.1) cycle ! Derive the local offset from absolute sync time because the ! assembly may have been updated from a different decode window. xdt_retry=active_messages(ir)%tsync + nframe6/6000.0 - & - (istart-1)/12000.0 + sample_time(istart) if(xdt_retry.lt.0.0) cycle if(ncand .ge. MAXCAND) exit ncand=ncand+1 @@ -1063,10 +1108,11 @@ contains enddo pn=(pa-pt)/3.0 if(pn.gt.0.) then - snrdb=db(pt/pn) + ! Solve pt=S+N, pn=N+SNR_LEAKAGE_K*S for S/N + snrdb=max(db((pt-pn)/pn) - db(2500.0/baud), SNR_FLOOR_DB) cand(ncand)%snrdb=snrdb endif - cand(ncand)%tsync=(istart-1)/12000.0 + cand(ncand)%xdt + cand(ncand)%tsync=sample_time(istart) + real(cand(ncand)%xdt,real64) decoded_ok=.true. ! dupe detection @@ -1189,12 +1235,12 @@ contains real, intent(in) :: f0, ftol, smin integer :: n_local, nframe, step, istart_prev, k, i real :: f1_local(MAX_SUBTRACTED) - real :: tsync_local(MAX_SUBTRACTED) + real(real64) :: tsync_local(MAX_SUBTRACTED) integer :: payload_local(PAYLOAD_BITS,MAX_SUBTRACTED) nframe=59*nsps step=nframe/4 - call prune_receive_state((istart-1)/12000.0,nframe/12000.0) + call prune_receive_state(sample_time(istart),nframe/12000.0) interferer_pending=.false. ! defensive: no stale interferer input call jtty_mdecode(istart,istart0,iwave(istart),nchunk,nsps,ndebug,nfa,nfb, & @@ -1213,6 +1259,9 @@ contains do k=1,MAX_RETRO_STEPS istart_prev=istart-k*step if(istart_prev.lt.1) cycle + if(explicit_receive_context) then + if(sample_origin+int(istart_prev-1,int64).lt.first_search_sample) cycle + endif interferer_pending=.true. interferer_f1=f1_local(i) interferer_tsync=tsync_local(i) diff --git a/lib/jtty/jtty_mod.f90 b/lib/jtty/jtty_mod.f90 index 7ff25b5b..e043552f 100644 --- a/lib/jtty/jtty_mod.f90 +++ b/lib/jtty/jtty_mod.f90 @@ -8,7 +8,7 @@ module jtty_mod contains -subroutine pack_jtty(message,c32,nframes,exchange_profile) +subroutine pack_jtty(message,c32,nframes,exchange_profile,frame_starts,is_final) ! Input: character*80 message !JTTY message, as it appears to a user ! Output: character*34 c32 !34-bit payload: 32 bits of existing @@ -19,6 +19,10 @@ subroutine pack_jtty(message,c32,nframes,exchange_profile) ! !uses as a free extra check beyond ! !the CRC. ! integer nframes !Frames in this message (max = 16) +! integer frame_starts(MAX_FRAMES), optional +! !1-indexed start column of each frame's source text in the normalized message (a structured atom's span runs through its trailing separator space). +! integer is_final, optional +! !0/1; suppresses the "last frame of message" flag even on the final frame when 0 (absent means final, the existing behavior). ! ! Minimize frames after alphabet and exchange-profile normalization. @@ -27,6 +31,8 @@ subroutine pack_jtty(message,c32,nframes,exchange_profile) character*80 message,msg character*34 c32(MAX_FRAMES) integer, intent(in), optional :: exchange_profile + integer, intent(out), optional :: frame_starts(MAX_FRAMES) + integer, intent(in), optional :: is_final integer, parameter :: INF=999 type(jtty_source_atom) :: choice(80),atoms(MAX_FRAMES) integer :: dp(81),successor(80),n,ipos,inext,natoms,nframes,profile @@ -75,9 +81,10 @@ subroutine pack_jtty(message,c32,nframes,exchange_profile) do while(ipos.le.n) natoms=natoms+1 atoms(natoms)=choice(ipos) + if(present(frame_starts)) frame_starts(natoms)=ipos ipos=successor(ipos) enddo - call pack_jtty_atoms(atoms,natoms,c32,nframes,valid) + call pack_jtty_atoms(atoms,natoms,c32,nframes,valid,is_final) if(.not.valid) then c32='' nframes=-1 @@ -238,7 +245,7 @@ contains if(nwords.lt.2 .or. length.lt.2 .or. length.gt.3) return call decimal_value(words(1)(1:length-1),value,numeric) if(.not.numeric) return - section_index=pack77_arrl_section_index(trim(words(2))) + section_index=pack77_arrl_section_index(words(2)) call offer(jtty_class_section_atom(value,words(1)(length:length),section_index)) end subroutine try_compact diff --git a/lib/jtty/jtty_n1mm_integration.md b/lib/jtty/jtty_n1mm_integration.md index 63125cc9..7b3637c6 100644 --- a/lib/jtty/jtty_n1mm_integration.md +++ b/lib/jtty/jtty_n1mm_integration.md @@ -4,7 +4,7 @@ N1MM Logger+ can send either literal JTTY text or an explicit native action. Ordinary TXTEXT uses automatic minimum-frame packing after text and exchange-profile normalization, combining recognized compact forms with TEXT5. Explicit typed exchanges use a leading `[[JTTY:<ACTION>]]` marker in the transmitted text. The marker is consumed by WSJT-X and is never put on the air. -The bundled `JTTY Messages.mc` uses tagged actions for its common Run and S&P messages. This provides compact Call8 and STRUCT30 transmission without asking WSJT-X to infer meaning from visible logger text. +The bundled [`JTTY Messages.mc`](JTTY%20Messages.mc) uses tagged actions for its common Run and S&P messages. This provides compact Call8 and STRUCT30 transmission without asking WSJT-X to infer meaning from visible logger text. The action definitions and source-interface rules are kept in [jtty_source_encoding.txt](jtty_source_encoding.txt). ## Setup @@ -19,47 +19,23 @@ End-to-end validation with N1MM on Windows, including two-radio focus, call sele ## Literal TXTEXT -N1MM expands logger macros before passing TXTEXT to WSJT-X. An untagged result uses the literal source interface: +N1MM expands logger macros before passing TXTEXT to WSJT-X. An untagged result uses the literal source interface. Text is folded to uppercase, spaces are normalized, and unsupported characters become `#`. The existing special operating activity supplies a profile captured when each message is submitted. No activity selects Unknown, even though native macros default to serials. -- lowercase letters become uppercase; -- leading, trailing, and repeated spaces are removed; -- unsupported characters become `#`; -- explicit RTTY Roundup canonicalizes eligible report-prefixed decimal serials; -- recognized calls, control phrases, generic numbers, full generic QTH exchanges, grids, and class/section pairs compete with TEXT5 for the minimum frame count; -- every compact candidate must preserve its source text exactly after normalization. +`CQ N9ADG CQ`, `N9ADG`, `599 123`, `599 MA`, `599 FN42`, and `1D EMA` each use one frame without a tag. RTTY Roundup also normalizes report-prefixed serials: `599 05` becomes `599 005`, and `599 0123` becomes `599 123`, each in one frame. `599 001` takes one frame in RTTY Roundup and two otherwise. The canonical message is returned to the GUI for display and logging. -`CQ N9ADG CQ`, `N9ADG`, `599 123`, `599 MA`, `599 FN42`, and `1D EMA` each use one frame without a tag. Recognition works at token boundaries inside longer messages as well. The existing special operating activity supplies a profile captured when each message is submitted. No activity selects Unknown, even though native macros default to serials. Field Day uses the same context-free candidates as Unknown. +The full recognition, normalization, and spacing rules are in the "Automatic text packing" section of [jtty_source_encoding.txt](jtty_source_encoding.txt). More frame-count examples are in [jtty_design.md](jtty_design.md#contest-exchange-example). -RTTY Roundup additionally recognizes full `599 <number>` SERIAL and full `599 <location>` STATE_PROVINCE exchanges under the native rules; locations must contain a letter. Before packing, decimal tokens following a complete `599` token are normalized as serials: `599 05` becomes `599 005`, and `599 0123` becomes `599 123`, each in one frame. Eligible tokens have one to six digits and value 0-131071. Unsupported tokens keep their spelling for normal fallback. `599 001` takes one frame in RTTY Roundup and two otherwise, and `K1ABC 599 001` takes two in RTTY Roundup. +## Writing tagged macros -Bare digits and all Unknown or Field Day input retain their spelling after ordinary text normalization. Every compact candidate must exactly match the resulting normalized text. The canonical message is returned to the GUI for display and logging; expansion beyond 80 characters is rejected rather than truncated. Tagged exchanges retain explicit type semantics. The full recognition policy and spacing constraints are in [`jtty_design.md`](jtty_design.md). - -The former `i2=2` shortcut for literal `599 ` plus five characters has been replaced by STRUCT30. There is no compatibility discriminator: an old receiver displays new STRUCT30 bits as `599` text, and some old type-2 frames are valid new STRUCT30 words with a different meaning. JTTY is unreleased, so no legacy decoder mode is retained. - -## Tagged TXTEXT grammar - -Place the marker so it is the leading transmitted text. Non-transmitting N1MM -commands may execute between `{TX}` and the marker: +The marker must begin at the first non-space transmitted character; tag and +action matching is case-insensitive. Non-transmitting N1MM commands may +execute between `{TX}` and the marker: ```text {TX}[[JTTY:<ACTION>]]<payload>{RX} ``` -N1MM expands `{MYCALL}`, `!` or `{CALL}`, and `{EXCH}`. WSJT-X removes the marker, normalizes whitespace and case in the expanded payload, and validates it under the selected action and active JTTY profile. Tag and action matching is case-insensitive, but the tag must start at the first non-space transmitted character. - -| Action | Expanded payload | Native sequence | -| --- | --- | --- | -| `CQ` | `<mycall>` | CQ with my call | -| `CALL_EXCH` | `<hiscall> <exchange>` | His call, configured full exchange | -| `CALL_TU_CQ` | `<hiscall> <mycall>` | His call/TU, CQ with my call | -| `MYCALL` | `<mycall>` | My call | -| `HISCALL` | `<hiscall>` | His call | -| `TU_NOW_EXCH` | `<hiscall> <exchange>` | TU NOW/his call, configured full exchange | -| `CALL_MY` | `<hiscall> <mycall>` | His call, my call | -| `CALL_TU_MY` | `<hiscall> <mycall>` | His call/TU, my call | -| `EXCH` | `<exchange>` | Configured full exchange | -| `GRID` | `<grid4>` | Field-only GRID4 | -| `CONTROL` | `<registered phrase>` | Registered control phrase | +N1MM expands `{MYCALL}`, `!` or `{CALL}`, and `{EXCH}`. WSJT-X removes the marker and validates the expanded payload under the selected action and active JTTY profile. The complete action and payload table is in the specification's "Tagged N1MM TXTEXT" section. Payloads contain dynamic values, not the phrases implied by an action. For example, `CQ` receives only the callsign, `CALL_TU_CQ` receives two callsigns, @@ -67,19 +43,13 @@ and `TU_NOW_EXCH` receives a callsign and exchange. The action supplies `CQ`, `TU`, `TU NOW`, and canonical full-exchange report text where applicable. Do not add a hardcoded `599` to an exchange payload. -Profile exchange payloads are: - -- Default: one decimal serial in the 17-bit serial domain. -- `FIELD_DAY`: exactly `<count><class> <section>`, with count 1-32, class A-F, and a registered ARRL/RAC section. -- `RTTY`: either one decimal serial or one canonical two- or three-character state/province token. A three-character token may not have a leading zero because its two-character spelling would be canonical. - -For tagged N1MM input, `DX` is an expanded two-letter location token. The -special `DX` and `#` meanings that select the live serial apply only to the -local WSJT-X RTTY `%E` configuration. +Under the RTTY profile, an exchange payload is one decimal serial or one +canonical two- or three-character state/province token. For tagged N1MM +input, `DX` is an expanded two-letter location token. The special `DX` and +`#` meanings that select the live serial apply only to the local WSJT-X RTTY +`%E` configuration. -`GRID` accepts exactly one valid four-character Maidenhead locator. `CONTROL` accepts exactly one of the 18 registered phrases, including spaces and punctuation where shown in `jtty_source_encoding.txt`. - -An unknown or malformed leading JTTY marker, unsupported action, missing field, invalid call, invalid profile exchange, invalid grid, or unregistered control phrase is rejected. It never falls back to literal transmission. Untagged messages, including customized N1MM macros, use automatic text packing with the exchange profile captured at submission. A tag-shaped substring later in the text is just literal text. +An invalid tagged request is rejected rather than transmitted as literal text. A tag-shaped substring later in the message is just literal text. Check the action's payload and profile rules in the specification when editing a macro. An all-rejected transaction receives `OUTPUTCOMPLETE` at `XMIT OFF`. When a transaction also contains accepted or pending audio, completion waits until that audio has drained. `ABORT` clears the transaction without reporting a successful output completion. @@ -114,27 +84,6 @@ intended station and exchange. ## Native WSJT-X function keys -The WSJT-X JTTY editor offers the same native subset without an N1MM tag. The shipped defaults are: - -| Key | Template | -| --- | --- | -| F1 | `CQ %M CQ` | -| F2 | `%H %E` | -| F3 | `%H TU CQ %M CQ` | -| F4 | `%M` | -| F5 | `%H` | -| F6 | `TU NOW %Q %E` | -| F7 | `%H AGN?` | -| F8 | `%E` | - -`%E` is the configured profile exchange. `%G` is a field-only GRID4, while the exact template `599 %G` selects full-role GRID4. Current templates and control phrases match before expansion after case and whitespace normalization. - -The exact former F2, F6, and F8 defaults (`%H 599 %N`, `TU NOW %Q 599 %N`, and `599 %N`) remain recognized during migration and are replaced by `%E` only when unchanged in saved settings. An edited old default is a customized literal template. Likewise, an unrecognized current template uses automatic text packing after normal expansion. A recognized native template with invalid runtime data is rejected rather than changing semantics through fallback. - -Clickable F1-F8 buttons and keyboard shortcuts select the same actions. Native sequences set EOM only on their final atom and do not add a TEXT5 spacing frame between queued messages. - -## Current scope - -The practical tagged and GUI native transmit subset includes Call8, serial and RTTY state/province exchanges, Field Day class/section, GRID4, and registered controls. Automatic text packing additionally uses GENERIC_NUMERIC and GENERIC_QTH. The full wire codec also validates and canonically renders other STRUCT30 number/location kinds, ZONE_LOC3, and EXCH_NUM_TIME. Those remaining forms are receive-only in the current operator-facing integration unless an explicit native codec caller constructs them; they are not inferred from ordinary text. +The WSJT-X JTTY editor offers the same native subset without an N1MM tag. Its defaults and placeholder rules are in the "Native function keys" section of [jtty_source_encoding.txt](jtty_source_encoding.txt). Clickable F1-F8 buttons and keyboard shortcuts select the same actions. -The complete wire definition is in [`jtty_source_encoding.txt`](jtty_source_encoding.txt). +For checks covering both local function keys and N1MM transactions, see [jtty_tx_manual_checks.md](jtty_tx_manual_checks.md). diff --git a/lib/jtty/jtty_receive_context.f90 b/lib/jtty/jtty_receive_context.f90 new file mode 100644 index 00000000..aeb43cb5 --- /dev/null +++ b/lib/jtty/jtty_receive_context.f90 @@ -0,0 +1,297 @@ +module jtty_receive_context + use iso_c_binding, only: c_int, c_int16_t, c_int64_t, c_float, c_double, c_char + use iso_fortran_env, only: int64, real64 + use jtty_fec, only: PAYLOAD_BITS + use jtty_mdec + implicit none + private + + type :: receive_state + integer :: active_count=0, recent_count=0, pending_count=0, pending_head=1, decode_count=0 + type(message_assembly) :: active(MAX_ACTIVE_MESSAGES) + type(frame_fingerprint) :: recent(MAX_RECENT_FRAMES) + type(message_update), allocatable :: pending(:) + end type receive_state + + type :: receive_retro_state + logical :: active=.false. + integer :: count=0, signal=1, step=1 + real :: frequency(MAX_SUBTRACTED)=0.0 + real(real64) :: sync_time(MAX_SUBTRACTED)=0.0_real64 + integer :: payload(PAYLOAD_BITS,MAX_SUBTRACTED)=0 + end type receive_retro_state + + type :: receive_context + logical :: allocated=.false., running=.false. + integer :: nsps=384 + integer(int64) :: session_id=0, grid_origin=0, first_search=0, next_search=0 + type(receive_state) :: state + type(receive_retro_state) :: retro + end type receive_context + + integer, parameter :: MAX_CONTEXTS=8 + type(receive_context), save :: contexts(MAX_CONTEXTS) + + public :: jtty_rx_create, jtty_rx_destroy, jtty_rx_begin, jtty_rx_process + public :: jtty_rx_next_required_sample, jtty_rx_next_search_sample + public :: jtty_rx_take_updates, jtty_rx_end + +contains + + logical function valid_handle(handle) + integer(c_int), intent(in) :: handle + + valid_handle=.false. + if(handle.lt.1 .or. handle.gt.MAX_CONTEXTS) return + valid_handle=contexts(handle)%allocated + end function valid_handle + + ! DSP scratch is shared; exchange only persistent reception state between whole steps. + subroutine exchange_state(state) + type(receive_state), intent(inout) :: state + type(message_assembly) :: active_swap(MAX_ACTIVE_MESSAGES) + type(frame_fingerprint) :: recent_swap(MAX_RECENT_FRAMES) + type(message_update), allocatable :: pending_swap(:) + integer :: value + + active_swap=active_messages + active_messages=state%active + state%active=active_swap + recent_swap=recent_frames + recent_frames=state%recent + state%recent=recent_swap + call move_alloc(pending_updates,pending_swap) + call move_alloc(state%pending,pending_updates) + call move_alloc(pending_swap,state%pending) + value=nactive + nactive=state%active_count + state%active_count=value + value=nrecent + nrecent=state%recent_count + state%recent_count=value + value=npending + npending=state%pending_count + state%pending_count=value + value=pending_first + pending_first=state%pending_head + state%pending_head=value + value=ndecodes + ndecodes=state%decode_count + state%decode_count=value + end subroutine exchange_state + + integer(c_int) function jtty_rx_create() bind(C,name='jtty_rx_create') + integer :: i + + jtty_rx_create=0 + do i=1,MAX_CONTEXTS + if(contexts(i)%allocated) cycle + contexts(i)=receive_context() + contexts(i)%allocated=.true. + jtty_rx_create=i + return + enddo + end function jtty_rx_create + + subroutine jtty_rx_destroy(handle) bind(C,name='jtty_rx_destroy') + integer(c_int), value :: handle + + if(.not.valid_handle(handle)) return + contexts(handle)=receive_context() + end subroutine jtty_rx_destroy + + subroutine jtty_rx_begin(handle,session_id,grid_origin,first_search,nsps) bind(C,name='jtty_rx_begin') + integer(c_int), value :: handle,nsps + integer(c_int64_t), value :: session_id,grid_origin,first_search + integer(int64) :: start,step + + if(.not.valid_handle(handle)) return + call jtty_rx_end(handle,UPDATE_RECEPTION_ENDED) + if(nsps.ne.240 .and. nsps.ne.320 .and. nsps.ne.384 .and. nsps.ne.480) return + step=int(59*nsps/4,int64) + start=max(first_search,grid_origin) + start=start+modulo(grid_origin-start,step) + contexts(handle)%session_id=session_id + contexts(handle)%grid_origin=grid_origin + contexts(handle)%first_search=start + contexts(handle)%next_search=start + contexts(handle)%nsps=nsps + contexts(handle)%state%active_count=0 + contexts(handle)%state%recent_count=0 + contexts(handle)%state%decode_count=0 + contexts(handle)%retro=receive_retro_state() + contexts(handle)%running=.true. + end subroutine jtty_rx_begin + + integer(c_int64_t) function jtty_rx_next_search_sample(handle) bind(C,name='jtty_rx_next_search_sample') + integer(c_int), value :: handle + + jtty_rx_next_search_sample=-1_c_int64_t + if(.not.valid_handle(handle)) return + jtty_rx_next_search_sample=contexts(handle)%next_search + end function jtty_rx_next_search_sample + + integer(c_int64_t) function jtty_rx_next_required_sample(handle) bind(C,name='jtty_rx_next_required_sample') + integer(c_int), value :: handle + integer(int64) :: step + + jtty_rx_next_required_sample=-1_c_int64_t + if(.not.valid_handle(handle)) return + step=int(59*contexts(handle)%nsps/4,int64) + jtty_rx_next_required_sample=max(contexts(handle)%first_search, & + contexts(handle)%next_search-int(MAX_RETRO_STEPS,int64)*step) + end function jtty_rx_next_required_sample + + integer(c_int) function jtty_rx_process(handle,pcm,count,first_sample,stop_sample,max_steps, & + nfa,nfb,f0,ftol) bind(C,name='jtty_rx_process') + integer(c_int), value :: handle,count,max_steps,nfa,nfb + integer(c_int16_t), intent(in) :: pcm(*) + integer(c_int64_t), value :: first_sample,stop_sample + real(c_float), value :: f0,ftol + integer :: nframe,nchunk,step,index,signal,retro_step + integer(int64) :: limit,old_origin,old_first_search,search + logical :: old_explicit,performed + + jtty_rx_process=-1 + if(.not.valid_handle(handle)) return + if(.not.contexts(handle)%running .or. count.lt.0) return + if(first_sample.gt.jtty_rx_next_required_sample(handle)) then + jtty_rx_process=-2 + return + endif + jtty_rx_process=0 + if(max_steps.le.0 .or. count.eq.0) return + nframe=59*contexts(handle)%nsps + nchunk=nframe+nframe/4 + step=nframe/4 + limit=min(stop_sample,first_sample+int(count,int64)) + old_origin=sample_origin + old_first_search=first_search_sample + old_explicit=explicit_receive_context + sample_origin=first_sample + first_search_sample=contexts(handle)%first_search + explicit_receive_context=.true. + call exchange_state(contexts(handle)%state) + + do while(jtty_rx_process.lt.max_steps) + performed=.false. + do while(contexts(handle)%retro%active .and. .not.performed) + signal=contexts(handle)%retro%signal + retro_step=contexts(handle)%retro%step + if(signal.gt.contexts(handle)%retro%count) then + contexts(handle)%retro=receive_retro_state() + contexts(handle)%next_search=contexts(handle)%next_search+int(step,int64) + exit + endif + contexts(handle)%retro%step=retro_step+1 + if(retro_step.gt.MAX_RETRO_STEPS) then + contexts(handle)%retro%signal=signal+1 + contexts(handle)%retro%step=1 + cycle + endif + search=contexts(handle)%next_search-int(retro_step*step,int64) + if(search.lt.contexts(handle)%first_search) cycle + index=int(search-first_sample)+1 + if(index.lt.1 .or. index+nchunk-1.gt.count) then + jtty_rx_process=-2 + exit + endif + interferer_pending=.true. + interferer_f1=contexts(handle)%retro%frequency(signal) + interferer_tsync=contexts(handle)%retro%sync_time(signal) + interferer_payload=contexts(handle)%retro%payload(:,signal) + call jtty_mdecode(index,0,pcm(index),nchunk,contexts(handle)%nsps,-1, & + nfa,nfb,f0,ftol,4.6) + jtty_rx_process=jtty_rx_process+1 + performed=.true. + enddo + if(jtty_rx_process.lt.0) exit + if(performed) cycle + if(contexts(handle)%next_search+int(nchunk,int64).gt.limit) exit + index=int(contexts(handle)%next_search-first_sample)+1 + call prune_receive_state(sample_time(index),real(nframe)/12000.0) + interferer_pending=.false. + call jtty_mdecode(index,0,pcm(index),nchunk,contexts(handle)%nsps,-1, & + nfa,nfb,f0,ftol,4.6) + jtty_rx_process=jtty_rx_process+1 + if(nsubtracted.gt.0) then + contexts(handle)%retro%active=.true. + contexts(handle)%retro%count=nsubtracted + contexts(handle)%retro%signal=1 + contexts(handle)%retro%step=1 + contexts(handle)%retro%frequency(1:nsubtracted)=subtracted_f1(1:nsubtracted) + contexts(handle)%retro%sync_time(1:nsubtracted)=subtracted_tsync(1:nsubtracted) + contexts(handle)%retro%payload(:,1:nsubtracted)=subtracted_payload(:,1:nsubtracted) + else + contexts(handle)%next_search=contexts(handle)%next_search+int(step,int64) + endif + enddo + + call exchange_state(contexts(handle)%state) + sample_origin=old_origin + first_search_sample=old_first_search + explicit_receive_context=old_explicit + end function jtty_rx_process + + subroutine jtty_rx_end(handle,reason) bind(C,name='jtty_rx_end') + integer(c_int), value :: handle,reason + integer :: i,terminal + + if(.not.valid_handle(handle)) return + if(.not.contexts(handle)%running) return + terminal=UPDATE_RECEPTION_ENDED + if(reason.eq.UPDATE_EXPIRED) terminal=UPDATE_EXPIRED + call exchange_state(contexts(handle)%state) + do i=1,nactive + call queue_message_update(active_messages(i),.false.,terminal) + enddo + call reset_decode_search_state() + call exchange_state(contexts(handle)%state) + contexts(handle)%retro=receive_retro_state() + contexts(handle)%running=.false. + end subroutine jtty_rx_end + + integer(c_int) function jtty_rx_take_updates(handle,capacity,text,ids,frequencies,starts,latest,terminals,snrs) & + bind(C,name='jtty_rx_take_updates') + integer(c_int), value :: handle,capacity + character(kind=c_char), intent(out) :: text(*) + integer(c_int64_t), intent(out) :: ids(*) + real(c_float), intent(out) :: frequencies(*) + real(c_double), intent(out) :: starts(*),latest(*) + integer(c_int), intent(out) :: terminals(*) + integer(c_int), intent(out) :: snrs(*) + character(len=80) :: message + integer :: i,j,index + + jtty_rx_take_updates=0 + if(.not.valid_handle(handle) .or. capacity.le.0) return + associate(state=>contexts(handle)%state) + jtty_rx_take_updates=min(capacity,state%pending_count) + do i=1,jtty_rx_take_updates + index=state%pending_head+i-1 + message=display_message_text(state%pending(index)%decoded) + do j=1,80 + text((i-1)*80+j)=message(j:j) + enddo + ids(i)=state%pending(index)%message_id + frequencies(i)=state%pending(index)%f1 + starts(i)=state%pending(index)%start_tsync + latest(i)=state%pending(index)%latest_tsync + terminals(i)=state%pending(index)%terminal + snrs(i)=nint(state%pending(index)%snr) + enddo + state%pending_head=state%pending_head+jtty_rx_take_updates + state%pending_count=state%pending_count-jtty_rx_take_updates + if(state%pending_count.eq.0) then + state%pending_head=1 + if(allocated(state%pending)) then + if(size(state%pending).gt.MAX_ACTIVE_MESSAGES) then + deallocate(state%pending) + allocate(state%pending(MAX_ACTIVE_MESSAGES)) + endif + endif + endif + end associate + end function jtty_rx_take_updates + +end module jtty_receive_context diff --git a/lib/jtty/jtty_source_codec.f90 b/lib/jtty/jtty_source_codec.f90 index e73a62ad..0a3f6193 100644 --- a/lib/jtty/jtty_source_codec.f90 +++ b/lib/jtty/jtty_source_codec.f90 @@ -388,18 +388,22 @@ type(jtty_source_atom) function jtty_text5_atom(text) result(atom) if(n.gt.0) atom%text(1:n)=text(1:n) end function jtty_text5_atom -subroutine pack_jtty_atoms(atoms,natoms,frames,nframes,valid) +subroutine pack_jtty_atoms(atoms,natoms,frames,nframes,valid,is_final) type(jtty_source_atom), intent(in) :: atoms(:) integer, intent(in) :: natoms character(len=34), intent(out) :: frames(:) integer, intent(out) :: nframes logical, intent(out) :: valid + integer, intent(in), optional :: is_final !0/1; absent means final (existing behavior) integer :: i + logical :: final_ok frames=''; nframes=0 valid=natoms.ge.1 .and. natoms.le.16 .and. natoms.le.size(atoms) .and. natoms.le.size(frames) if(.not.valid) return + final_ok=.true. + if(present(is_final)) final_ok=is_final.ne.0 do i=1,natoms - call pack_jtty_atom(atoms(i),frames(i),i.eq.natoms,valid) + call pack_jtty_atom(atoms(i),frames(i),i.eq.natoms .and. final_ok,valid) if(.not.valid) then; frames=''; return; endif enddo nframes=natoms diff --git a/lib/jtty/jtty_source_encoding.txt b/lib/jtty/jtty_source_encoding.txt index efc78c6e..7265e60f 100644 --- a/lib/jtty/jtty_source_encoding.txt +++ b/lib/jtty/jtty_source_encoding.txt @@ -1,5 +1,26 @@ JTTY source encoding +This is the canonical specification for JTTY framing, source encoding, and +source interfaces. It defines the wire grammar and the rules used by automatic +text packing, native function keys, and tagged N1MM actions. For a design +overview and contest examples, see jtty_design.md. N1MM setup and macro +examples are in jtty_n1mm_integration.md. + +Frame and waveform + +A transmission contains one or more 1.888-second frames. Each frame carries +a 34-bit payload. A 12-bit CRC extends this payload to 46 bits. A tail-biting, +rate-1/2 convolutional code with constraint length K=10 produces 92 coded bits. + +The waveform is Gaussian-smoothed four-tone frequency-shift keying (4-GFSK), +with two coded bits per tone symbol. A frame contains a 13-symbol +synchronization sequence followed by 46 coded symbols. At 12000/384 = 31.25 +baud, its duration is (13+46)/31.25 = 1.888 seconds. Nominal half-power +bandwidth is 125 Hz. The occupied bandwidth (99% of transmitted power) is +127 Hz. + +Source bits and validity + Each JTTY frame conveys 34 source bits. Bits are numbered from left to right, most significant first. Bits 1-32 are the message grammar, bit 33 is reserved and shall be zero, and bit 34 is the universal end-of-message (EOM) flag. EOM @@ -183,18 +204,21 @@ Canonical atom sequences Structured atoms are rendered independently and supply one implicit trailing space; TEXT5 characters are appended verbatim. The final trailing space or TEXT5 padding is not part of the displayed message. The receiver truncates -the accumulated display at 80 characters. A sender -sets bit 33 to zero on every atom and bit 34 only on the last atom. Queuing a -second native message does not add a TEXT5 spacing atom. - -Ordinary keyboard text, externally queued strings, and N1MM/MMTTY strings use -the literal source interface. They are normalized to uppercase, leading, -trailing, and repeated ASCII spaces are removed, and unsupported characters -become '#'. The literal wrapper accepts an 80-character input field, so longer -caller strings are truncated before normalization. Automatic packing minimizes -the frame count while preserving this text exactly after any explicit RTTY -Roundup serial normalization described below. The result is -at most sixteen frames because TEXT5 is always available as a fallback. +the accumulated display at 80 characters. A sender sets bit 33 to zero on +every atom and bit 34 only on the last atom. Queuing a second native message +does not add a TEXT5 spacing atom. + +Automatic text packing + +Ordinary keyboard text, sjtty input, externally queued strings, and untagged +N1MM/MMTTY strings use the literal source interface. They are normalized to +uppercase, leading, trailing, and repeated ASCII spaces are removed, and +unsupported characters become '#'. The literal wrapper accepts an 80-character +input field, so longer caller strings are truncated before normalization. +Automatic packing minimizes the frame count while preserving this text exactly +after any explicit RTTY Roundup serial normalization described below. The +result is at most sixteen frames because TEXT5 is always available as a fallback. +Unrecognized "599 ..." text remains available through TEXT5. Candidates at complete token boundaries are: @@ -210,12 +234,11 @@ Candidates at complete token boundaries are: Every candidate must pass codec pack/unpack validation and render exactly as its span in the normalized text. These context-free candidates remain -available under every -exchange profile. The GUI captures Unknown, Field Day, or RTTY Roundup from -the existing special operating activity when a message is submitted. No -activity means Unknown; the native macro default of SERIAL does not apply to -automatic text recognition. Field Day adds no candidates because CLASS_SECTION -is already self-identifying. +available under every exchange profile. The GUI captures Unknown, Field Day, +or RTTY Roundup from the existing special operating activity when a message is +submitted. No activity means Unknown; the native macro default of SERIAL does +not apply to automatic text recognition. Field Day adds no candidates because +CLASS_SECTION is already self-identifying. RTTY Roundup additionally considers full "599 <number>" as SERIAL and full "599 <location>" as STATE_PROVINCE under the existing native exchange rules. @@ -236,14 +259,15 @@ is per-message encoder context, not a new configuration or wire field. A dynamic program over source-character offsets selects a minimum-frame sequence of candidates and TEXT5. An interior TEXT5 atom consumes exactly five -characters; only the final TEXT5 atom may be padded. A structured candidate -consumes its rendering plus one source space when another token follows, -matching the receiver's implicit separator. Equal-cost choices prefer a -structured atom, then the longest consumed span, then ascending atom -kind/subtype/role. Thus equally compact SERIAL and STATE_PROVINCE candidates -win over their generic equivalents under RTTY Roundup. This minimizes frames -under the recognition policy, not -under hypothetical knowledge of the contest exchange's meaning. +characters; only the final TEXT5 atom may be padded. Interior padding cannot +be used to reach a compact candidate because it would change the text. +A structured candidate consumes its rendering plus one source space when +another token follows, matching the receiver's implicit separator. +Equal-cost choices prefer a structured atom, then the longest consumed span, +then ascending atom kind/subtype/role. Thus equally compact SERIAL and +STATE_PROVINCE candidates win over their generic equivalents under RTTY +Roundup. This minimizes frames under the recognition policy, not under +hypothetical knowledge of the contest exchange's meaning. For example, "CQ K1ABC CQ", "599 123", "599 MA", "599 FN42", and "1D EMA" each use one frame. Under Unknown or Field Day, "599 001" and "599 05" need @@ -259,6 +283,8 @@ sjtty defaults to Unknown. The optional leading argument one-message packing and eight-argument waveform invocations. An invalid profile value is an error. +Native function keys + The eight shipped JTTY function-key templates are a separate NativeMacro contract. Current templates and control phrases match after case folding and whitespace normalization, before placeholder expansion. Superseded templates @@ -311,9 +337,10 @@ start of the transmitted text, after the normal {TX} command: [[JTTY:<ACTION>]]<payload> N1MM expands {MYCALL}, ! or {CALL}, and {EXCH}; WSJT-X then parses the expanded -payload under the selected action and active profile. The tag must begin at the -first non-space character; tag and action matching is case-insensitive. The -marker is transport metadata and is not transmitted. Assigned actions are: +payload, normalizing whitespace and case, under the selected action and active +profile. The tag must begin at the first non-space character; tag and action +matching is case-insensitive. The marker is transport metadata and is not +transmitted. Assigned actions are: -------------------------------------------------------------------------------- Action Expanded payload Native meaning @@ -336,13 +363,13 @@ rules as %E, except that tagged values are already expanded: RTTY "DX" is a two-letter location, and the local-configuration "DX" and "#" serial sentinels do not apply. It contains the exchange value only: the action supplies CQ, TU, TU NOW, and canonical full-exchange report text where applicable. GRID requires -a valid four-character Maidenhead locator. CONTROL requires one exact +exactly one valid four-character Maidenhead locator. CONTROL requires one exact registered phrase from the CONTROL table above. An untagged N1MM message uses the literal source interface with automatic packing described above. -A tag-shaped substring later in a message has no -special meaning. An unknown or malformed leading JTTY tag, an unsupported -action, invalid payload, or profile mismatch is rejected rather than put on -the air as literal bracket text. +A tag-shaped substring later in a message has no special meaning. An unknown +or malformed leading JTTY tag, unsupported action, missing field, invalid call, +invalid exchange or grid, unregistered control phrase, or profile mismatch is +rejected rather than put on the air as literal bracket text. Representative 34-bit vectors @@ -366,15 +393,3 @@ CONTROL AGN? 0000000000000000000000000001001001 0x000000049 GRID4 field-only FN42 0001001010000110011000000001001001 0x04A198049 TEXT5 HELLO 0100010011100101010101010110001101 0x11395558D -------------------------------------------------------------------------------- - -Compatibility - -This version deliberately replaces the earlier i2=2 encoding, which meant the -literal prefix "599 " followed by five six-bit characters. There is no version -discriminator: an old receiver will render new STRUCT30 payload bits as -arbitrary text following "599 ", while some old i2=2 frames happen to satisfy -the new STRUCT30 structural rules and will be accepted with a different -meaning by a new receiver. JTTY is unreleased, so this incompatibility is -intentional and no legacy decoder mode is retained. Automatic text packing -uses only the current grammar; unrecognized "599 ..." text remains available -through TEXT5. diff --git a/lib/jtty/jtty_tx_manual_checks.md b/lib/jtty/jtty_tx_manual_checks.md index bcb4ff44..f8eb992a 100644 --- a/lib/jtty/jtty_tx_manual_checks.md +++ b/lib/jtty/jtty_tx_manual_checks.md @@ -3,9 +3,36 @@ These checks cover MainWindow, PTT, and backend behavior that is outside the FIFO unit-test boundary. +- Free entry: Enter queues the whole message. Text longer than the encoder's + 80-character capacity is split at spaces where possible; longer words are + split across messages. Each segment has its own end marker, and the receiver + displays separate messages. The exchange profile and transmit frequency are + captured when the message is submitted. +- Pending text: the existing Send button shows `Send (3 left)` while segments + remain, including the segment currently playing. Its tooltip shows the + pending text. Yellow transmit text appears when the audio source starts + serving each segment; it does not confirm reception. Completion waits for + the backend's final audio drain. +- Status bar: long `Tx:` and `Last Tx:` messages use an ellipsis to leave room + for the other indicators. Hover to read the complete message. +- Drafts: typing while transmitting starts a new draft; Enter appends it after + existing text. Halt Tx or Esc cancels all unfinished submissions and leaves the + new draft alone. Cancellation is reported in the Send tooltip; + partial transmission may already have occurred. No cancelled text is restored + to the input, and nothing is retained across application exit. +- Long entry: send enough text to exceed 60 seconds of encoded audio. Verify + continuous playback, ordered segments, and reception of the final suffix. + Repeat with an exactly 80-character segment appended during playback. +- Cancellation: stop before PTT rises and during playback, then send a fresh + long message. Verify that cancelled text never resumes, deferred text never + appears yellow, and the new message starts normally. Repeat with Esc, a mode + change, and an audio/backend failure. Check that newer draft edits survive. +- Normalization: enter unsupported characters after character 80. Verify the + substitution notice in the Send tooltip and canonical pending text, with no + omitted suffix. - Soundcard: send one JTTY message and verify the full tail plays before PTT drops. - Soundcard: queue two or three messages rapidly and verify playback is contiguous with PTT held. -- Soundcard: press Stop during playback and verify queued audio is abandoned before PTT drops. +- Soundcard: press Halt Tx during playback and verify queued audio is abandoned before PTT drops. - Soundcard: press Esc before PTT comes up and during playback and verify clean aborts. - Soundcard: send again after a natural drain and verify a fresh transmit session starts. - TCI, where available: repeat the same checks and watch for backend enqueue failure warnings. @@ -33,8 +60,8 @@ FIFO unit-test boundary. frame, with the canonical text shown and logged. Verify bare `001` retains its spelling and is not inferred as SERIAL. Verify unsupported serial tokens (over six digits or above 131071) retain their spelling. Verify a - message whose serial normalization expands beyond 80 characters is rejected - rather than truncated. Submit a message, change activity + message whose serial normalization expands beyond 80 characters is split + without omitting the remainder. Submit a message, change activity before it plays, and verify the submitted message retains its captured profile. Repeat through untagged N1MM/MMTTY and customized macro fallback. - sjtty: compare default and leading `--exchange-profile=rtty-roundup` with diff --git a/lib/jtty/rjtty_sub.f90 b/lib/jtty/rjtty_sub.f90 index 333d38b4..2ab3ab25 100644 --- a/lib/jtty/rjtty_sub.f90 +++ b/lib/jtty/rjtty_sub.f90 @@ -54,7 +54,7 @@ subroutine rjtty_core(iwave,kz,nsps,nfa,nfb,f0,ftol,istart0,istop) 999 return end subroutine rjtty_core -subroutine jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) +subroutine jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,snr,count) use iso_fortran_env, only: int64 use jtty_mdec @@ -65,6 +65,7 @@ subroutine jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom, real, intent(out) :: frequencies(BATCH_SIZE) real, intent(out) :: start_tsync(BATCH_SIZE) logical*1, intent(out) :: eom(BATCH_SIZE) + integer, intent(out) :: snr(BATCH_SIZE) integer, intent(out) :: count character(len=MESSAGE_LENGTH) :: msg integer :: i,index,offset @@ -74,6 +75,7 @@ subroutine jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom, frequencies=0.0 start_tsync=0.0 eom=.false. + snr=0 count=min(npending,BATCH_SIZE) do i=1,count @@ -85,6 +87,7 @@ subroutine jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom, frequencies(i)=pending_updates(index)%f1 start_tsync(i)=pending_updates(index)%start_tsync eom(i)=pending_updates(index)%complete + snr(i)=nint(pending_updates(index)%snr) enddo ! Pending membership is the delivery guarantee; remove records only after copying them out. diff --git a/lib/jtty/sjtty.f90 b/lib/jtty/sjtty.f90 index 16d4324a..4c4fd75a 100644 --- a/lib/jtty/sjtty.f90 +++ b/lib/jtty/sjtty.f90 @@ -21,6 +21,7 @@ program sjtty character*80 umsg !User-formatted message character(len=80) :: profile_option integer :: exchange_profile,arg_offset + integer :: ihr,imin,isec,ihhmmss !For clock-like (not raw sequential) output filenames character*40 fname !Output file name character*34 c32(16) complex, allocatable :: cwave(:) !Complex generated waveform (12000 Hz) @@ -238,7 +239,12 @@ program sjtty iwave(1:iz)=nint(wave(1:iz)) ! call jtty_spec(iwave,iz) h=default_header(12000,iz) - write(fname,1102) ifile + ! Format the file counter as elapsed HHMMSS, not a raw sequential integer, so WSJT-X's disk-playback time label parses it (file 60 -> "_000100", not the invalid "_000060"). + ihr=mod(ifile/3600,24) + imin=mod(ifile,3600)/60 + isec=mod(ifile,60) + ihhmmss=10000*ihr + 100*imin + isec + write(fname,1102) ihhmmss 1102 format('000000_',i6.6,'.wav') open(10,file=fname,status='replace',access='stream') write(10) h,iwave(1:iz) !Save to *.wav file diff --git a/lib/jtty/wava/plot_results.py b/lib/jtty/wava/plot_results.py deleted file mode 100644 index 0ef97628..00000000 --- a/lib/jtty/wava/plot_results.py +++ /dev/null @@ -1,57 +0,0 @@ - -import pandas as pd -import matplotlib.pyplot as plt - -# Read data logged from the Fortran testbench suite -try: - df = pd.read_csv('simulation_results.csv') -except FileNotFoundError: - print("Error: 'simulation_results.csv' not found. Execute the Fortran simulation program first.") - exit() - -# Strip whitespace from columns to avoid parsing mismatches -df['channel'] = df['channel'].str.strip() - -# Initialize Figure with high resolution DPI properties -fig, ax1 = plt.subplots(figsize=(10, 6), dpi=120) - -# Set up Primary Axis: Frame Correct-Decode Probability P(Correct) -ax1.set_xlabel('SNR in 2500 Hz Reference Bandwidth [dB]', fontsize=11, fontweight='bold') -ax1.set_ylabel('P(Correct Decode)', color='navy', fontsize=11, fontweight='bold') -ax1.set_xlim(0, -20) # Invert axis view to scan standard drop off descending to -20 dB -ax1.set_ylim(-0.05, 1.05) -ax1.grid(True, which='both', linestyle='--', alpha=0.5) - -# Set up Secondary Axis on the right side for 100 * UER (%) -ax2 = ax1.twinx() -ax2.set_ylabel('Undetected Error Rate: 100 * UER [%]', color='crimson', fontsize=11, fontweight='bold') -ax2.set_ylim(-0.1, 5.0) # Standard percentage visualization window - -# Isolate channel tracking configurations -awgn_data = df[df['channel'] == 'AWGN'].sort_values(by='snr_db', ascending=False) -rayleigh_data = df[df['channel'] == 'RAYLEIGH'].sort_values(by='snr_db', ascending=False) - -# Plot Primary Curves - P(Correct) -line1 = ax1.plot(awgn_data['snr_db'], awgn_data['p_correct'], - 'o-', color='navy', linewidth=2.0, label='AWGN: P(Correct)') -line2 = ax1.plot(rayleigh_data['snr_db'], rayleigh_data['p_correct'], - 's-', color='royalblue', linewidth=1.8, label='Rayleigh: P(Correct)') - -# Plot Secondary Curves - 100 * UER (%) -line3 = ax2.plot(awgn_data['snr_db'], awgn_data['uer_pct'], - '^--', color='crimson', linewidth=1.5, label='AWGN: 100*UER') -line4 = ax2.plot(rayleigh_data['snr_db'], rayleigh_data['uer_pct'], - 'v--', color='orange', linewidth=1.5, label='Rayleigh: 100*UER') - -# Align Legend structures coherently across shared dual axis space -lines = line1 + line2 + line3 + line4 -labels = [l.get_label() for l in lines] -ax1.legend(lines, labels, loc='center left', frameon=True, shadow=True) - -plt.title('TBCC (92,46) Noncoherent 4-FSK Performance Profile\nConstraint Length K=11, List Size L=8, Rate=1/2', - fontsize=12, fontweight='bold', pad=15) - -plt.tight_layout() -plt.savefig('tbcc_performance_curves.png', dpi=300) -print("Plot successfully rendered and saved as 'tbcc_performance_curves.png'") -plt.show() diff --git a/lib/jtty/wava/tbcc_performance_curves.png b/lib/jtty/wava/tbcc_performance_curves.png Binary files differdeleted file mode 100644 index 88d63b07..00000000 --- a/lib/jtty/wava/tbcc_performance_curves.png +++ /dev/null diff --git a/lib/lorentzian.f90 b/lib/lorentzian.f90 index f3f4e14e..03e081fb 100644 --- a/lib/lorentzian.f90 +++ b/lib/lorentzian.f90 @@ -84,7 +84,11 @@ subroutine lorentzian(y,npts,a) endif ! Find minimum of parabola defined by last three points - delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) + if(chisq3.eq.chisq2) then + delta=0.5*delta + else + delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) + endif a(j)=a(j)-delta deltaa(j)=deltaa(j)*fn/3. ! write(*,4000) iter,j,a,chisq2 @@ -99,4 +103,3 @@ subroutine lorentzian(y,npts,a) return end subroutine lorentzian - diff --git a/lib/options.f90 b/lib/options.f90 index bc2cdf97..a6ebd17d 100644 --- a/lib/options.f90 +++ b/lib/options.f90 @@ -180,6 +180,8 @@ contains goto 10 end if + st = 0 + goto 10 end if ! short option diff --git a/lib/prog_args.f90 b/lib/prog_args.f90 index d8caa549..1f18d920 100644 --- a/lib/prog_args.f90 +++ b/lib/prog_args.f90 @@ -1,5 +1,6 @@ MODULE prog_args CHARACTER(len=80) :: shm_key + CHARACTER(len=500) :: ipc_lock_path = '' CHARACTER(len=500) :: exe_dir = '.', data_dir = '.', temp_dir = '.', & share_dir = '.' !ft8md added share_dir LOGICAL :: lquiet = .false. diff --git a/lib/q65_codec.f90 b/lib/q65_codec.f90 new file mode 100644 index 00000000..962c13ff --- /dev/null +++ b/lib/q65_codec.f90 @@ -0,0 +1,154 @@ +module q65_codec + use iso_c_binding + implicit none + private + public :: q65_codec_create, q65_codec_destroy, select_q65_codec, q65_codec_status + public :: q65_enc, q65_intrinsics_ff, q65_dec, q65_dec_fullaplist + + ! Codec selection is scoped to one serialized decoder operation. + type(c_ptr), save :: selected_codec=c_null_ptr + integer, save :: codec_status=0 + + interface + function q65_codec_create() bind(C) result(handle) + import c_ptr + type(c_ptr) :: handle + end function + subroutine q65_codec_destroy(handle) bind(C) + import c_ptr + type(c_ptr), value :: handle + end subroutine + integer(c_int) function codec_encode(handle,x,y) bind(C,name="q65_codec_encode") + import c_ptr,c_int + type(c_ptr), value :: handle + integer(c_int), intent(in) :: x(*) + integer(c_int), intent(out) :: y(*) + end function + integer(c_int) function codec_intrinsics(handle,s3,submode,b90ts,fading,prob) & + bind(C,name="q65_codec_intrinsics") + import c_ptr,c_int,c_float + type(c_ptr), value :: handle + real(c_float), intent(in) :: s3(*) + integer(c_int), value :: submode,fading + real(c_float), value :: b90ts + real(c_float), intent(out) :: prob(*) + end function + integer(c_int) function codec_decode(handle,s3,prob,mask,symbols,maxiters,esnodb,xdec,rc) & + bind(C,name="q65_codec_decode") + import c_ptr,c_int,c_float + type(c_ptr), value :: handle + real(c_float), intent(in) :: s3(*),prob(*) + integer(c_int), intent(in) :: mask(*),symbols(*) + integer(c_int), value :: maxiters + real(c_float), intent(out) :: esnodb + integer(c_int), intent(out) :: xdec(*),rc + end function + integer(c_int) function codec_fullaplist(handle,s3,prob,words,ncw,esnodb,xdec,plog,rc) & + bind(C,name="q65_codec_decode_fullaplist") + import c_ptr,c_int,c_float + type(c_ptr), value :: handle + real(c_float), intent(in) :: s3(*),prob(*) + integer(c_int), intent(in) :: words(*) + integer(c_int), value :: ncw + real(c_float), intent(out) :: esnodb,plog + integer(c_int), intent(out) :: xdec(*),rc + end function + subroutine legacy_encode(x,y) bind(C,name="q65_enc_") + import c_int + integer(c_int), intent(in) :: x(*) + integer(c_int), intent(out) :: y(*) + end subroutine + subroutine legacy_intrinsics(s3,submode,b90ts,fading,prob) bind(C,name="q65_intrinsics_ff_") + import c_int,c_float + real(c_float), intent(in) :: s3(*),b90ts + integer(c_int), intent(in) :: submode,fading + real(c_float), intent(out) :: prob(*) + end subroutine + subroutine legacy_decode(s3,prob,mask,symbols,maxiters,esnodb,xdec,rc) bind(C,name="q65_dec_") + import c_int,c_float + real(c_float), intent(in) :: s3(*),prob(*) + integer(c_int), intent(in) :: mask(*),symbols(*),maxiters + real(c_float), intent(out) :: esnodb + integer(c_int), intent(out) :: xdec(*),rc + end subroutine + subroutine legacy_fullaplist(s3,prob,words,ncw,esnodb,xdec,plog,rc) bind(C,name="q65_dec_fullaplist_") + import c_int,c_float + real(c_float), intent(in) :: s3(*),prob(*) + integer(c_int), intent(in) :: words(*),ncw + real(c_float), intent(out) :: esnodb,plog + integer(c_int), intent(out) :: xdec(*),rc + end subroutine + end interface + +contains + + subroutine select_q65_codec(handle) + type(c_ptr), intent(in) :: handle + selected_codec=handle + codec_status=0 + end subroutine + + integer function q65_codec_status() + q65_codec_status=codec_status + end function + + subroutine q65_enc(x,y) + integer, intent(in) :: x(13) + integer, intent(out) :: y(63) + y=0 + if(codec_status/=0) return + if(c_associated(selected_codec)) then + codec_status=codec_encode(selected_codec,x,y) + else + call legacy_encode(x,y) + endif + end subroutine + + subroutine q65_intrinsics_ff(s3,submode,b90ts,fading,prob) + real, intent(in) :: s3(*) + integer, intent(in) :: submode,fading + real, intent(in) :: b90ts + real, intent(out) :: prob(64,63) + prob=0 + if(codec_status/=0) return + if(c_associated(selected_codec)) then + codec_status=codec_intrinsics(selected_codec,s3,submode,b90ts,fading,prob) + else + call legacy_intrinsics(s3,submode,b90ts,fading,prob) + endif + end subroutine + + subroutine q65_dec(s3,prob,mask,symbols,maxiters,esnodb,xdec,rc) + real, intent(in) :: s3(*),prob(64,63) + integer, intent(in) :: mask(13),symbols(13),maxiters + real, intent(out) :: esnodb + integer, intent(out) :: xdec(13),rc + esnodb=0 + xdec=0 + rc=-1 + if(codec_status/=0) return + if(c_associated(selected_codec)) then + codec_status=codec_decode(selected_codec,s3,prob,mask,symbols,maxiters,esnodb,xdec,rc) + else + call legacy_decode(s3,prob,mask,symbols,maxiters,esnodb,xdec,rc) + endif + end subroutine + + subroutine q65_dec_fullaplist(s3,prob,words,ncw,esnodb,xdec,plog,rc) + real, intent(in) :: s3(*),prob(64,63) + integer, intent(in) :: words(*),ncw + real, intent(out) :: esnodb,plog + integer, intent(out) :: xdec(13),rc + esnodb=0 + plog=0 + xdec=0 + rc=-1 + if(codec_status/=0) return + if(c_associated(selected_codec)) then + codec_status=codec_fullaplist(selected_codec,s3,prob,words,ncw,esnodb,xdec,plog,rc) + else + call legacy_fullaplist(s3,prob,words,ncw,esnodb,xdec,plog,rc) + endif + end subroutine + +end module q65_codec diff --git a/lib/q65_decode.f90 b/lib/q65_decode.f90 index e06d9972..fde300dc 100644 --- a/lib/q65_decode.f90 +++ b/lib/q65_decode.f90 @@ -1,6 +1,26 @@ module q65_decode use q65_workspace, only: q65_workspace_type + use ft8_decode, only: ft8apset + use q65, only: q65_state,q65_work,legacy_work,q65_select,q65_initialize_state,q65_release_state,q65_hist2 + use q65_codec + use packjt77, only: pack77_state,initialize_pack77_state,reset_pack77_state + use types, only: q3list + use q65_callers, only: Q65_MAX_CALLERS,q65_record_caller,q65_expire_callers + use, intrinsic :: iso_c_binding + + private + public :: q65_decoder,q65_options,q65_decode_callback,q65_diagnostic_callback + public :: nsnr0,nfreq0,xdt0,msg0,cq0 + + type q65_options + integer :: utc=0,period=60,submode=0,receive_frequency=1500,tolerance=1000 + integer :: low_frequency=200,high_frequency=4000,effort=1,max_drift=0,qso_progress=0,contest=0,now=0 + logical :: repeat=.false.,single_decode=.false.,average=.false.,auto_clear=.false. + logical :: eme=.false.,pileup=.false.,ap_cq_only=.false. + character(len=12) :: mycall='',hiscall='' + character(len=6) :: hisgrid='' + end type integer nsnr0,nfreq0 real xdt0 @@ -8,12 +28,35 @@ module q65_decode type :: q65_decoder type(q65_workspace_type) :: workspace - procedure(q65_decode_callback), pointer :: callback + type(q65_state), pointer :: state=>null() + type(pack77_state), pointer :: knowledge=>null() + type(c_ptr) :: codec=c_null_ptr + integer(c_int64_t) :: input_id=0 + integer :: period=0,submode=-1,caller_count=0,now=0 + logical :: engine_active=.false.,consumed=.false. + type(q3list), allocatable :: callers(:) + procedure(q65_diagnostic_callback), pointer, nopass :: diagnostic=>null() + procedure(q65_decode_callback), pointer :: callback=>null() contains + procedure :: decode + procedure :: decode_pcm + procedure :: initialize + procedure :: release_input + procedure :: clear_averages + procedure :: reset + procedure :: destroy + procedure :: set_callers + procedure :: get_callers + procedure :: get_curves + final :: finalize end type q65_decoder abstract interface + subroutine q65_diagnostic_callback(line) + character(len=*), intent(in) :: line + end subroutine + subroutine q65_decode_callback (this,nutc,snr1,nsnr,dt,freq, & decoded,idec,nused,ntrperiod,iflagdec) import q65_decoder @@ -34,6 +77,216 @@ module q65_decode contains + subroutine initialize(this) + class(q65_decoder), target, intent(inout) :: this + if(.not.associated(this%state)) then + allocate(this%state) + call q65_initialize_state(this%state) + endif + if(.not.associated(this%knowledge)) then + allocate(this%knowledge) + call initialize_pack77_state(this%knowledge) + endif + if(.not.allocated(this%callers)) allocate(this%callers(Q65_MAX_CALLERS)) + end subroutine + + subroutine release_input(this) + class(q65_decoder), target, intent(inout) :: this + this%input_id=0 + this%consumed=.false. + if(.not.associated(this%state)) return + this%state%spectra_valid=.false. + this%state%analytic_valid=.false. + end subroutine + + subroutine clear_averages(this) + class(q65_decoder), target, intent(inout) :: this + if(.not.associated(this%state)) return + if(associated(this%state%s1a)) this%state%s1a=0. + if(associated(this%state%ccf2_avg)) this%state%ccf2_avg=0. + this%state%navg=0 + end subroutine + + subroutine reset(this) + class(q65_decoder), target, intent(inout) :: this + call this%release_input() + call this%clear_averages() + this%caller_count=0 + this%period=0 + this%submode=-1 + if(associated(this%state)) then + this%state%nhist=0 + this%state%curve_dt=0. + this%state%curve_average_count=0 + if(associated(this%state%ccf2)) this%state%ccf2=0. + endif + if(associated(this%knowledge)) call reset_pack77_state(this%knowledge) + end subroutine + + subroutine destroy(this) + class(q65_decoder), target, intent(inout) :: this + if(associated(this%state)) then + if(associated(q65_work,this%state)) call q65_select(legacy_work) + call q65_release_state(this%state) + deallocate(this%state) + nullify(this%state) + endif + if(associated(this%knowledge)) deallocate(this%knowledge) + nullify(this%knowledge) + if(c_associated(this%codec)) call q65_codec_destroy(this%codec) + this%codec=c_null_ptr + nullify(this%callback,this%diagnostic) + if(allocated(this%callers)) deallocate(this%callers) + call this%workspace%destroy() + this%input_id=0 + this%consumed=.false. + this%period=0 + this%submode=-1 + this%caller_count=0 + this%engine_active=.false. + end subroutine + + subroutine finalize(this) + type(q65_decoder), intent(inout) :: this + call this%destroy() + end subroutine + + subroutine set_callers(this,callers,count) + class(q65_decoder), target, intent(inout) :: this + type(q3list), intent(in) :: callers(:) + integer, intent(in) :: count + call this%initialize() + this%caller_count=max(0,min(count,size(callers),Q65_MAX_CALLERS)) + this%callers(:this%caller_count)=callers(:this%caller_count) + end subroutine + + subroutine get_callers(this,callers,count) + class(q65_decoder), intent(in) :: this + type(q3list), intent(out) :: callers(:) + integer, intent(out) :: count + integer n + count=this%caller_count + n=min(count,size(callers)) + if(n>0) callers(:n)=this%callers(:n) + end subroutine + + subroutine get_curves(this,even,odd,spacing,offset,instant,averaged,count,render_count) + class(q65_decoder), intent(in) :: this + integer, intent(out) :: even,odd,count + integer, optional, intent(out) :: render_count + real, intent(out) :: spacing,offset + real, intent(out) :: instant(:),averaged(:) + integer n + if(present(render_count)) render_count=0 + even=0 + odd=0 + count=0 + spacing=0. + offset=0. + if(.not.associated(this%state)) return + if(present(render_count)) render_count=this%state%curve_average_count + even=this%state%navg(0) + odd=this%state%navg(1) + spacing=this%state%df + offset=this%state%curve_dt + if(.not.associated(this%state%ccf2)) return + count=size(this%state%ccf2) + n=min(count,size(instant),size(averaged)) + instant(:n)=this%state%ccf2(:n) + averaged(:n)=this%state%ccf2_avg(:n) + end subroutine + + subroutine decode_pcm(this,callback,samples,sample_count,options,input_id,status) + class(q65_decoder), target, intent(inout) :: this + procedure(q65_decode_callback) :: callback + integer(c_int16_t), contiguous, intent(in) :: samples(:) + integer, intent(in) :: sample_count + type(q65_options), intent(in) :: options + integer(c_int64_t), intent(in) :: input_id + integer, intent(out) :: status + integer depth,nqf(20),retry(20),navg0,i,npts,nfq,ntol,nqd + logical fresh,clear,again,single + character(len=12) mycall,hiscall + character(len=6) hisgrid + status=-1 + npts=options%period*12000 + ! Engine input preparation supplies a full period with an internally padded tail. + if(sample_count<1.or.sample_count>npts.or.size(samples)<npts) return + call this%initialize() + if(.not.c_associated(this%codec)) this%codec=q65_codec_create() + if(.not.c_associated(this%codec)) return + if(this%period/=options%period.or.this%submode/=options%submode) then + call this%release_input() + call this%clear_averages() + this%period=options%period + this%submode=options%submode + endif + if(this%input_id/=input_id) call this%release_input() + this%input_id=input_id + fresh=.not.this%consumed.and..not.options%repeat + this%now=options%now + if(options%contest==1) call q65_expire_callers(this%callers,this%caller_count,this%now) + this%engine_active=.true. + call select_q65_codec(this%codec) + depth=options%effort + if(options%average) depth=ior(depth,16) + if(options%auto_clear) depth=ior(depth,128) + clear=.false. + again=options%repeat + single=options%single_decode + nqd=1 + nfq=options%receive_frequency + ntol=options%tolerance + mycall=options%mycall + hiscall=options%hiscall + hisgrid=options%hisgrid + ! Legacy Q65 tests only emedelay > 0; its magnitude does not set the search window. + call decode(this,callback,samples,nqd,options%utc,options%period,options%submode,nfq, & + ntol,depth,options%low_frequency,options%high_frequency,clear,single,again,options%max_drift, & + fresh,merge(2.5,0.,options%eme),mycall,hiscall,hisgrid,options%qso_progress,options%contest, & + options%pileup,options%ap_cq_only,navg0,nqf) + this%consumed=.true. + retry=nqf + if(.not.options%repeat.and.options%contest==1.and.options%period==60.and.options%submode==0) then + do i=1,20 + if(retry(i)==0) cycle + hiscall=options%hiscall + hisgrid=options%hisgrid + fresh=.false. + again=.true. + single=.true. + depth=ior(depth,3) + nfq=retry(i) + ntol=5 + nqd=1 + call decode(this,callback,samples,nqd,options%utc,options%period,options%submode,nfq, & + ntol,depth,options%low_frequency,options%high_frequency,clear,single,again,options%max_drift, & + fresh,merge(2.5,0.,options%eme),mycall,hiscall,hisgrid,options%qso_progress,options%contest, & + options%pileup,options%ap_cq_only,navg0,nqf) + enddo + endif + status=q65_codec_status() + call select_q65_codec(c_null_ptr) + call q65_select(legacy_work) + this%engine_active=.false. + end subroutine + + subroutine emit_diagnostic(this,line) + use prog_args, only: data_dir + class(q65_decoder), target, intent(inout) :: this + character(len=*), intent(in) :: line + integer ios + if(associated(this%diagnostic)) then + call this%diagnostic(trim(line)) + else if(.not.this%engine_active) then + open(22,file=trim(data_dir)//'/q65_decodes.txt',status='unknown',position='append',iostat=ios) + if(ios==0) then + write(22,'(a)') trim(line) + close(22) + endif + endif + end subroutine + subroutine decode(this,callback,iwave,nqd0,nutc,ntrperiod,nsubmode,nfqso, & ntol,ndepth,nfa0,nfb0,lclearave,single_decode,lagain,max_drift0, & lnewdat0,emedelay,mycall,hiscall,hisgrid,nQSOprogress,ncontest, & @@ -61,11 +314,11 @@ contains use q65 !Shared variables use prog_args use types + use q65_callers, only: Q65_MAX_CALLERS,q65_load_callers,q65_expire_callers parameter (NMAX=300*12000) !Max TRperiod is 300 s - parameter (MAX_CALLERS=50) !For multiple q3 decodes in NA VHF Contest mode - class(q65_decoder), intent(inout) :: this + class(q65_decoder), target, intent(inout) :: this procedure(q65_decode_callback) :: callback character(len=12) :: mycall, hiscall !Used for AP decoding @@ -77,21 +330,38 @@ contains character*6 cutc character c6*6,c4*4,cmode*4 character*80 fmt - integer*2 iwave(NMAX) !Raw data - real, allocatable :: dd(:) !Raw data + integer(c_int16_t), intent(in) :: iwave(*) real xdtdecodes(100) real f0decodes(100) integer dat4(13) !Decoded message as 12 6-bit integers integer dgen(13) integer nqf(20) integer stageno !Added by W3SZ - integer time + integer time,history_status integer iflagdec !Recovered spare 78th bit logical lclearave,lnewdat0,lq65pileup,lapcqonly,unpk77_success logical single_decode,lagain - complex c00(0:3600000) !Analytic signal, 6000 Sa/s - type(q3list) callers(MAX_CALLERS) - save c00 + complex, pointer :: c00(:) + character(len=512) :: diagnostic_line + type(q3list), pointer :: callers(:) + integer :: effort,display_utc + + + call this%initialize() + call q65_select(this%state) + this%state%legacy_output=.not.this%engine_active + if(this%engine_active) then + this%state%knowledge=>this%knowledge + else + nullify(this%state%knowledge) + this%state%spectra_valid=.false. + this%state%analytic_valid=.false. + endif + callers=>this%callers + nqf=0 + effort=ndepth + display_utc=nutc + if(this%engine_active.and.ntrperiod>=60) display_utc=nutc/100 ! Start by setting some parameters and allocating storage for large arrays call sec0(0,tdecode) @@ -114,41 +384,32 @@ contains nfft1=ntrperiod*12000 nfft2=ntrperiod*6000 npasses=1 - nhist2=0 - if(lagain) ndepth=ior(ndepth,3) !Use 'Deep' for manual Q65 decodes - dxcall13=hiscall ! initialize for use in packjt77 - mycall13=mycall - if(ncontest.eq.1) then + nhist2=this%caller_count + history_status=0 + if(lagain) effort=ior(effort,3) !Use 'Deep' for manual Q65 decodes + if(this%engine_active) then + this%knowledge%dxcall13=hiscall + this%knowledge%mycall13=mycall + else + dxcall13=hiscall + mycall13=mycall + endif + if(ncontest.eq.1.and..not.this%engine_active) then ! NA VHF, WW-Digi, or ARRL Digi Contest - open(24,file=trim(data_dir)//'/tsil.3q',status='unknown', & - form='unformatted') - read(24,end=2) nhist2 - if(nhist2.ge.1 .and. nhist2.le.40) then - read(24,end=2) callers(1:nhist2) - now=time() - do i=1,nhist2 - hours=(now - callers(i)%nsec)/3600.0 - if(hours.gt.24.0) then - callers(i:nhist2-1)=callers(i+1:nhist2) - nhist2=nhist2-1 - endif - enddo - else - nhist2=0 - endif -2 close(24) + call q65_load_callers(trim(data_dir)//'/tsil.3q',callers,nhist2,history_status) + if(history_status.eq.0) call q65_expire_callers(callers,nhist2,time()) endif ! Determine the T/R sequence: iseq=0 (even), or iseq=1 (odd) n=nutc - if(ntrperiod.ge.60 .and. nutc.le.2359) n=100*n + if(.not.this%engine_active.and.ntrperiod.ge.60.and.nutc.le.2359) n=100*n write(cutc,'(i6.6)') n read(cutc,'(3i2)') ih,im,is nsec=3600*ih + 60*im + is iseq=mod(nsec/ntrperiod,2) if(lclearave) call q65_clravg - allocate(dd(npts)) + if(lagain) then call q65_hist(nfqso,dxcall=hiscall,dxgrid=hisgrid) @@ -181,8 +442,8 @@ contains ! ibwb=min(15,ibwa+4) ibwb=min(15,ibwa+6) maxiters=40 - if(iand(ndepth,3).eq.2) maxiters=60 - if(iand(ndepth,3).eq.3) then + if(iand(effort,3).eq.2) maxiters=60 + if(iand(effort,3).eq.3) then ibwa=max(1,ibwa-2) ibwb=min(15,ibwb+2) maxiters=100 @@ -206,7 +467,7 @@ contains iavg=0 ! W3SZ patch: Initialize AP params here, rather than afer the call to ana64(). - call ft8apset(mycall,hiscall,ncontest,apsym0,aph10) ! Generate ap symbols + call ft8apset(mycall,hiscall,ncontest,apsym0,aph10,this%state%knowledge) ! Generate ap symbols where(apsym0.eq.-1) apsym0=0 npasses=2 if(nQSOprogress.eq.5) npasses=3 @@ -224,14 +485,15 @@ contains go to 100 endif - if(ncontest.eq.1 .and. lagain .and. iand(ndepth,16).eq.16) go to 50 - if(ncontest.eq.1 .and. lagain .and. iand(ndepth,16).eq.0) go to 100 + if(ncontest.eq.1 .and. lagain .and. iand(effort,16).eq.16) go to 50 + if(ncontest.eq.1 .and. lagain .and. iand(effort,16).eq.0) go to 100 ! Prepare for a single-period decode with iaptype = 0, 1, 2, or 4 jpk0=(xdt+1.0)*6000 !Index of nominal start of signal if(ntrperiod.le.30) jpk0=(xdt+0.5)*6000 !For shortest sequences if(jpk0.lt.0) jpk0=0 - call ana64(iwave,npts,c00) !Convert to complex c00() at 6000 Sa/s + call q65_analytic(iwave,npts) + c00=>this%state%analytic !Convert to complex c00() at 6000 Sa/s if(lapcqonly) npasses=1 iaptype=0 do ipass=0,npasses !Loop over AP passes @@ -250,7 +512,7 @@ contains endif call timer('q65loop1',0) - call q65_loops(this%workspace,c00,npts/2,nsps/2,nsubmode,ndepth,jpk0, & + call q65_loops(this%workspace,c00,npts/2,nsps/2,nsubmode,effort,jpk0, & xdt,f0,iaptype,xdt1,f1,snr2,dat4,idec) call timer('q65loop1',1) if(idec.ge.0) then @@ -260,7 +522,7 @@ contains endif enddo ! ipass - if(iand(ndepth,16).eq.0 .or. navg(iseq).lt.2) go to 100 + if(iand(effort,16).eq.0 .or. navg(iseq).lt.2) go to 100 ! There was no single-transmission decode. Try for an average 'q3n' decode. 50 iavg=1 @@ -321,7 +583,7 @@ contains iflagdec=iand(dat4(13),1) !Recover the spare 78th bit before it's shifted away write(c77,1000) dat4(1:12),dat4(13)/2 1000 format(12b6.6,b5.5) - call unpack77(c77,1,decoded,unpk77_success) !Unpack to get decoded + call q65_unpack(c77,1,decoded,unpk77_success) !Unpack to get decoded idupe=0 do i=1,ndecodes if(decodes(i).eq.decoded) idupe=1 @@ -336,16 +598,14 @@ contains call this%callback(nutc,snr1,nsnr,dtdec,f0dec,decoded, & idec,nused,ntrperiod,iflagdec) if(ncontest.eq.1) then - call q65_hist2(nint(f0dec),decoded,callers,nhist2) + call record_caller(this,nint(f0dec),decoded,callers,nhist2,history_status.eq.0) else call q65_hist(nint(f0dec),msg0=decoded) endif - if(iand(ndepth,128).ne.0 .and. .not.lagain .and. & + if(iand(effort,128).ne.0 .and. .not.lagain .and. & int(abs(f0dec-nfqso)).le.ntol ) call q65_clravg !AutoClrAvg call sec0(1,tdecode) - open(22,file=trim(data_dir)//'/q65_decodes.txt',status='unknown', & - position='append',iostat=ios) - if(ios.eq.0) then + if(associated(this%diagnostic).or..not.this%engine_active) then ! Save decoding parameters to q65_decoded.dat, for later analysis. write(cmode,'(i3)') ntrperiod cmode(4:4)=char(ichar('A')+nsubmode) @@ -357,10 +617,10 @@ contains '1x,a6,1x,a6,1x,a4,1x,a)' if(ntrperiod.le.30) fmt(5:5)='6' if(idec.eq.3) nrc=0 - write(22,fmt) nutc,cmode,nfqso,nQSOprogress,idec,idfbest,idtbest, & - ibwa,ibwb,ibw,ndistbest,nused,icand,ncand,nrc,ndepth,xdt, & + write(diagnostic_line,fmt) display_utc,cmode,nfqso,nQSOprogress,idec,idfbest,idtbest, & + ibwa,ibwb,ibw,ndistbest,nused,icand,ncand,nrc,effort,xdt, & f0,snr2,plog,tdecode,mycall(1:6),c6,c4,trim(decoded) - close(22) + call emit_diagnostic(this,diagnostic_line) endif endif endif @@ -395,8 +655,9 @@ contains jpk0=(xdt+1.0)*6000 !Index of nominal start of signal if(ntrperiod.le.30) jpk0=(xdt+0.5)*6000 !For shortest sequences if(jpk0.lt.0) jpk0=0 - call ana64(iwave,npts,c00) !Convert to complex c00() at 6000 Sa/s - call ft8apset(mycall,hiscall,ncontest,apsym0,aph10) ! Generate ap symbols + call q65_analytic(iwave,npts) + c00=>this%state%analytic !Convert to complex c00() at 6000 Sa/s + call ft8apset(mycall,hiscall,ncontest,apsym0,aph10,this%state%knowledge) ! Generate ap symbols where(apsym0.eq.-1) apsym0=0 npasses=2 @@ -419,7 +680,7 @@ contains endif call timer('q65loop2',0) - call q65_loops(this%workspace,c00,npts/2,nsps/2,nsubmode,ndepth,jpk0, & + call q65_loops(this%workspace,c00,npts/2,nsps/2,nsubmode,effort,jpk0, & xdt,f0,iaptype,xdt1,f1,snr2,dat4,idec) call timer('q65loop2',1) ! write(*,3001) '=e',nfqso,ntol,ndepth,xdt,f0,idec @@ -435,7 +696,7 @@ contains ! Unpack decoded message for display to user iflagdec=iand(dat4(13),1) !Recover the spare 78th bit before it's shifted away write(c77,1000) dat4(1:12),dat4(13)/2 - call unpack77(c77,1,decoded,unpk77_success) !Unpack to get decoded + call q65_unpack(c77,1,decoded,unpk77_success) !Unpack to get decoded idupe=0 do i=1,ndecodes if(decodes(i).eq.decoded) idupe=1 @@ -449,17 +710,14 @@ contains call this%callback(nutc,snr1,nsnr,dtdec,f0dec,decoded, & idec,nused,ntrperiod,iflagdec) if(ncontest.eq.1) then - call q65_hist2(nint(f0dec),decoded,callers,nhist2) + call record_caller(this,nint(f0dec),decoded,callers,nhist2,history_status.eq.0) else call q65_hist(nint(f0dec),msg0=decoded) endif - if(iand(ndepth,128).ne.0 .and. .not.lagain .and. & + if(iand(effort,128).ne.0 .and. .not.lagain .and. & int(abs(f0dec-nfqso)).le.ntol ) call q65_clravg !AutoClrAvg call sec0(1,tdecode) - ios=1 - open(22,file=trim(data_dir)//'/q65_decodes.txt',status='unknown',& - position='append',iostat=ios) - if(ios.eq.0) then + if(associated(this%diagnostic).or..not.this%engine_active) then ! Save decoding parameters to q65_decoded.dat, for later analysis. write(cmode,'(i3)') ntrperiod cmode(4:4)=char(ichar('A')+nsubmode) @@ -471,17 +729,17 @@ contains '1x,a6,1x,a6,1x,a4,1x,a)' if(ntrperiod.le.30) fmt(5:5)='6' if(idec.eq.3) nrc=0 - write(22,fmt) nutc,cmode,nfqso,nQSOprogress,idec,idfbest, & + write(diagnostic_line,fmt) display_utc,cmode,nfqso,nQSOprogress,idec,idfbest, & idtbest,ibwa,ibwb,ibw,ndistbest,nused,icand,ncand,nrc, & - ndepth,xdt,f0,snr2,plog,tdecode,mycall(1:6),c6,c4, & + effort,xdt,f0,snr2,plog,tdecode,mycall(1:6),c6,c4, & trim(decoded) - close(22) + call emit_diagnostic(this,diagnostic_line) endif endif endif 800 continue enddo ! icand - if(iavg.eq.0 .and.navg(iseq).ge.2 .and. iand(ndepth,16).ne.0) go to 50 + if(iavg.eq.0 .and.navg(iseq).ge.2 .and. iand(effort,16).ne.0) go to 50 900 if(ncontest.ne.1 .or. lagain) go to 999 if(ntrperiod.ne.60 .or. nsubmode.ne.0) go to 999 @@ -505,7 +763,23 @@ contains 990 continue enddo -999 return +999 this%caller_count=nhist2 + return end subroutine decode + + subroutine record_caller(this,frequency,message,callers,count,persist) + class(q65_decoder), target, intent(inout) :: this + integer, intent(in) :: frequency + character(len=*), intent(in) :: message + type(q3list), intent(inout) :: callers(Q65_MAX_CALLERS) + integer, intent(inout) :: count + logical, intent(in) :: persist + if(this%engine_active) then + call q65_record_caller(callers,count,frequency,message,this%now) + else + call q65_hist2(frequency,message,callers,count,persist) + endif + end subroutine + end module q65_decode diff --git a/lib/q65_host_support.f90 b/lib/q65_host_support.f90 new file mode 100644 index 00000000..95e4f2d4 --- /dev/null +++ b/lib/q65_host_support.f90 @@ -0,0 +1,64 @@ +module q65_host_support + use q65_decode, only: q65_decoder,q65_options + use q65_callers, only: Q65_MAX_CALLERS,q65_load_callers,q65_save_callers + use types, only: q3list + use prog_args, only: data_dir,temp_dir + implicit none + private + public :: load_q65_history,save_q65_history,write_q65_curves,write_q65_diagnostic +contains + subroutine load_q65_history(decoder,status) + class(q65_decoder), intent(inout) :: decoder + integer, intent(out) :: status + type(q3list) :: callers(Q65_MAX_CALLERS) + integer :: count + call q65_load_callers(trim(data_dir)//'/tsil.3q',callers,count,status) + call decoder%set_callers(callers,count) + end subroutine + + subroutine save_q65_history(decoder,load_status) + class(q65_decoder), intent(in) :: decoder + integer, intent(in) :: load_status + type(q3list) :: callers(Q65_MAX_CALLERS) + integer :: count,status + if(load_status/=0) return + call decoder%get_callers(callers,count) + call q65_save_callers(trim(data_dir)//'/tsil.3q',callers,count,status) + end subroutine + + subroutine write_q65_diagnostic(line) + character(len=*), intent(in) :: line + integer :: unit,status + open(newunit=unit,file=trim(data_dir)//'/q65_decodes.txt',status='unknown',position='append',iostat=status) + if(status/=0) return + write(unit,'(a)') trim(line) + close(unit) + end subroutine + + subroutine write_q65_curves(decoder,options) + class(q65_decoder), intent(in) :: decoder + type(q65_options), intent(in) :: options + real, allocatable :: current(:),average(:) + real :: df,dt,y0,y0_average,g_average,empty_current(0),empty_average(0) + integer :: even_count,odd_count,count,i1,i2,i,unit,status,active_count + call decoder%get_curves(even_count,odd_count,df,dt,empty_current,empty_average,count) + if(count<=0.or.df<=0) return + allocate(current(count),average(count)) + call decoder%get_curves(even_count,odd_count,df,dt,current,average,count,active_count) + i1=max(1,nint(options%low_frequency/df)) + i2=min(count,int(options%high_frequency/df)) + if(i2<i1) return + y0=minval(current(i1:i2)) + y0_average=minval(average(i1:i2)) + g_average=0 + if(active_count>=2) g_average=0.4 + open(newunit=unit,file=trim(temp_dir)//'/red.dat',status='replace',iostat=status) + if(status/=0) return + write(unit,1000) dt,g_average*minval(average),g_average*maxval(average) + do i=i1,i2 + write(unit,1000) i*df,g_average*(average(i)-y0_average),0.4*(current(i)-y0) + enddo +1000 format(f10.3,2f15.6) + close(unit) + end subroutine +end module q65_host_support diff --git a/lib/qra/q65/genq65.f90 b/lib/qra/q65/genq65.f90 index 1705ce82..4502a2b3 100644 --- a/lib/qra/q65/genq65.f90 +++ b/lib/qra/q65/genq65.f90 @@ -3,6 +3,8 @@ subroutine genq65(msg0,ichk,msgsent,itone,i3,n3,iflag) ! Encodes a Q65 message to yield itone(1:85) use packjt77 + use q65, only: q65_work + use q65_codec, only: q65_enc character*37 msg0 !Message to be generated character*37 msgsent !Message as it will be received character*77 c77 @@ -27,11 +29,27 @@ subroutine genq65(msg0,ichk,msgsent,itone,i3,n3,iflag) n3=-1 c77=' ' unpk77_success=.false. - call pack77_legacy_truncating_fallback(msg0,i3,n3,c77) + if(associated(q65_work)) then + if(associated(q65_work%knowledge)) then + call pack77_legacy_truncating_fallback_for_state(q65_work%knowledge,msg0,i3,n3,c77) + else + call pack77_legacy_truncating_fallback(msg0,i3,n3,c77) + endif + else + call pack77_legacy_truncating_fallback(msg0,i3,n3,c77) + endif if(i3.lt.0 .or. n3.lt.0) go to 998 read(c77(60:74),'(b15)',err=998) ng15 if(ng15.eq.32373) c77(60:74)='111111010010011' !Message is RR73 - call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent + if(associated(q65_work)) then + if(associated(q65_work%knowledge)) then + call unpack77_for_state(q65_work%knowledge,c77,0,msgsent,unpk77_success) + else + call unpack77(c77,0,msgsent,unpk77_success) + endif + else + call unpack77(c77,0,msgsent,unpk77_success) + endif !Unpack to get msgsent read(c77,1001,err=998) dgen 1001 format(12b6.6,b5.5) dgen(13)=2*dgen(13)+iflag !Convert 77-bit to 78-bit payload; iflag is the spare 78th bit diff --git a/lib/qra/q65/q65.f90 b/lib/qra/q65/q65.f90 index 5718243c..37c2e638 100644 --- a/lib/qra/q65/q65.f90 +++ b/lib/qra/q65/q65.f90 @@ -1,32 +1,311 @@ module q65 - parameter (NSTEP=8) !Number of time bins per symbol in s1, s1a, s1b - parameter (PLOG_MIN=-242.0) !List decoding threshold - integer iz0,jz0 -! integer listutc(10) - integer apsym0(58),aph10(10) - integer apmask1(78),apsymbols1(78) - integer apmask(13),apsymbols(13) - integer,dimension(22) :: isync = (/1,9,12,13,15,22,23,26,27,33,35, & - 38,46,50,55,60,62,66,69,74,76,85/) - integer codewords(63,411) !See MAX_NCW in q65_set_list2.f90 - integer ibwa,ibwb,ncw,nsps,mode_q65,nfa,nfb,nqd - integer idfbest,idtbest,ibw,ndistbest,maxiters,max_drift - integer istep,nsmo,lag1,lag2,npasses,iseq,ncand,nrc - integer i0,j0 - integer navg(0:1) - logical lnewdat - real candidates(20,3) !snr, xdt, and f0 of top candidates - real, allocatable :: s1(:,:) !Symbol spectra w/suppressed peaks - real, allocatable :: s1w(:,:) !Symbol spectra w/suppressed peaks (W3SZ) - real, allocatable,save :: s1a(:,:,:) !Cumulative symbol spectra - real, allocatable,save :: ccf2(:) !Max CCF(freq) at any lag (orange curve) - real, allocatable,save :: ccf2_avg(:) !Like ccf2, but for avg (red curve) - real sync(85) !sync vector - real df,dtstep,dtdec,f0dec,ftol,plog,drift + use q65_callers, only: Q65_MAX_CODEWORDS + + use, intrinsic :: iso_c_binding + use fftw3 + use packjt77, only: pack77_state,unpack77_for_state + use q65_codec, only: q65_enc,q65_intrinsics_ff,q65_dec,q65_dec_fullaplist + + integer, parameter :: NSTEP=8 + real, parameter :: PLOG_MIN=-242.0 + integer, parameter :: isync(22) = [1,9,12,13,15,22,23,26,27,33,35, & + 38,46,50,55,60,62,66,69,74,76,85] + type :: q65_state + integer :: iz0=0 + integer :: jz0=0 + integer :: ibwa=0 + integer :: ibwb=0 + integer :: ncw=0 + integer :: nsps=0 + integer :: mode_q65=0 + integer :: nfa=0 + integer :: nfb=0 + integer :: nqd=0 + integer :: idfbest=0 + integer :: idtbest=0 + integer :: ibw=0 + integer :: ndistbest=0 + integer :: maxiters=0 + integer :: max_drift=0 + integer :: istep=0 + integer :: nsmo=0 + integer :: lag1=0 + integer :: lag2=0 + integer :: npasses=0 + integer :: iseq=0 + integer :: ncand=0 + integer :: nrc=0 + integer :: i0=0 + integer :: j0=0 + integer :: LL0=0 + integer :: nhist=0,curve_average_count=0 + real :: df=0. + real :: dtstep=0. + real :: dtdec=0. + real :: f0dec=0. + real :: ftol=0. + real :: plog=0. + real :: drift=0. + real :: curve_dt=0. + integer :: apsym0(58) + integer :: aph10(10) + integer :: apmask1(78) + integer :: apsymbols1(78) + integer :: apmask(13) + integer :: apsymbols(13) + integer :: codewords(63,Q65_MAX_CODEWORDS) + integer :: navg(0:1) + integer :: nf0(100) + real :: candidates(20,3) + real :: sync(85) + real, pointer :: s1(:,:)=>null() + real, pointer :: s1w(:,:)=>null() + real, pointer :: s1a(:,:,:)=>null() + real, pointer :: ccf2(:)=>null() + real, pointer :: ccf2_avg(:)=>null() + logical :: lnewdat=.false.,spectra_valid=.false.,analytic_valid=.false.,legacy_output=.true. + character(len=37) :: history(100) + complex, allocatable :: symbol_fft(:),analytic(:) + real, allocatable :: prepared(:,:),symbol_energies(:,:),correlation(:),list_correlation(:,:),best_list(:) + real, allocatable :: timing(:),spectrum_average(:),snr_spectrum(:) + integer, allocatable :: ordering(:),birdie_histogram(:) + type(pack77_state), pointer :: knowledge=>null() + integer(c_int64_t) :: symbol_plan=0,analytic_forward=0,analytic_inverse=0 + integer :: symbol_length=0,analytic_length=0,planning=-1 + end type + type(q65_state), pointer :: q65_work=>null() + type(q65_state), target, save :: legacy_work + integer, pointer :: iz0=>null() + integer, pointer :: jz0=>null() + integer, pointer :: ibwa=>null() + integer, pointer :: ibwb=>null() + integer, pointer :: ncw=>null() + integer, pointer :: nsps=>null() + integer, pointer :: mode_q65=>null() + integer, pointer :: nfa=>null() + integer, pointer :: nfb=>null() + integer, pointer :: nqd=>null() + integer, pointer :: idfbest=>null() + integer, pointer :: idtbest=>null() + integer, pointer :: ibw=>null() + integer, pointer :: ndistbest=>null() + integer, pointer :: maxiters=>null() + integer, pointer :: max_drift=>null() + integer, pointer :: istep=>null() + integer, pointer :: nsmo=>null() + integer, pointer :: lag1=>null() + integer, pointer :: lag2=>null() + integer, pointer :: npasses=>null() + integer, pointer :: iseq=>null() + integer, pointer :: ncand=>null() + integer, pointer :: nrc=>null() + integer, pointer :: i0=>null() + integer, pointer :: j0=>null() + integer, pointer :: LL0=>null() + integer, pointer :: nhist=>null() + real, pointer :: df=>null() + real, pointer :: dtstep=>null() + real, pointer :: dtdec=>null() + real, pointer :: f0dec=>null() + real, pointer :: ftol=>null() + real, pointer :: plog=>null() + real, pointer :: drift=>null() + real, pointer :: curve_dt=>null() + integer, pointer :: apsym0(:)=>null() + integer, pointer :: aph10(:)=>null() + integer, pointer :: apmask1(:)=>null() + integer, pointer :: apsymbols1(:)=>null() + integer, pointer :: apmask(:)=>null() + integer, pointer :: apsymbols(:)=>null() + integer, pointer :: codewords(:,:)=>null() + integer, pointer :: navg(:)=>null() + integer, pointer :: nf0(:)=>null() + real, pointer :: candidates(:,:)=>null() + real, pointer :: sync(:)=>null() + real, pointer :: s1(:,:)=>null() + real, pointer :: s1w(:,:)=>null() + real, pointer :: s1a(:,:,:)=>null() + real, pointer :: ccf2(:)=>null() + real, pointer :: ccf2_avg(:)=>null() + logical, pointer :: lnewdat=>null() contains + +integer function q65_fft_flags() result(flags) + integer npatience,nthreads + common/patience/npatience,nthreads + flags=FFTW_ESTIMATE + if(npatience==1) flags=FFTW_ESTIMATE_PATIENT + if(npatience==2) flags=FFTW_MEASURE + if(npatience==3) flags=FFTW_PATIENT + if(npatience==4) flags=FFTW_EXHAUSTIVE +end function + +subroutine q65_check_planning() + integer npatience,nthreads + common/patience/npatience,nthreads + if(q65_work%planning==npatience) return + !$omp critical(fftw) + if(q65_work%symbol_plan/=0) call sfftw_destroy_plan(q65_work%symbol_plan) + if(q65_work%analytic_forward/=0) call sfftw_destroy_plan(q65_work%analytic_forward) + if(q65_work%analytic_inverse/=0) call sfftw_destroy_plan(q65_work%analytic_inverse) + !$omp end critical(fftw) + q65_work%symbol_plan=0 + q65_work%analytic_forward=0 + q65_work%analytic_inverse=0 + q65_work%planning=npatience + q65_work%spectra_valid=.false. + q65_work%analytic_valid=.false. +end subroutine + +subroutine q65_analytic(iwave,npts) + integer, intent(in) :: npts + integer(c_int16_t), intent(in) :: iwave(npts) + integer nfft2,flags + real fac + call q65_check_planning() + if(q65_work%analytic_length/=npts) then + !$omp critical(fftw) + if(q65_work%analytic_forward/=0) call sfftw_destroy_plan(q65_work%analytic_forward) + if(q65_work%analytic_inverse/=0) call sfftw_destroy_plan(q65_work%analytic_inverse) + !$omp end critical(fftw) + q65_work%analytic_forward=0 + q65_work%analytic_inverse=0 + if(allocated(q65_work%analytic)) deallocate(q65_work%analytic) + allocate(q65_work%analytic(0:npts-1)) + q65_work%analytic_length=npts + q65_work%analytic_valid=.false. + endif + if(q65_work%analytic_valid) return + nfft2=npts/2 + flags=q65_fft_flags() + if(q65_work%analytic_forward==0) then + !$omp critical(fftw) + call sfftw_plan_dft_1d(q65_work%analytic_forward,npts,q65_work%analytic, & + q65_work%analytic,FFTW_FORWARD,flags) + call sfftw_plan_dft_1d(q65_work%analytic_inverse,nfft2,q65_work%analytic, & + q65_work%analytic,FFTW_BACKWARD,flags) + !$omp end critical(fftw) + endif + fac=2.0/(32767.0*npts) + q65_work%analytic=fac*iwave + call sfftw_execute(q65_work%analytic_forward) + q65_work%analytic(nfft2/2+1:nfft2-1)=0. + q65_work%analytic(0)=0.5*q65_work%analytic(0) + call sfftw_execute(q65_work%analytic_inverse) + q65_work%analytic_valid=.true. +end subroutine + +subroutine q65_unpack(c77,nrx,decoded,success) + use packjt77, only: unpack77 + character(len=77), intent(in) :: c77 + integer, intent(in) :: nrx + character(len=37), intent(out) :: decoded + logical, intent(out) :: success + if(associated(q65_work)) then + if(associated(q65_work%knowledge)) then + call unpack77_for_state(q65_work%knowledge,c77,nrx,decoded,success) + return + endif + endif + call unpack77(c77,nrx,decoded,success) +end subroutine + +subroutine q65_select(state) + type(q65_state), target, intent(inout) :: state + q65_work=>state + iz0=>state%iz0 + jz0=>state%jz0 + ibwa=>state%ibwa + ibwb=>state%ibwb + ncw=>state%ncw + nsps=>state%nsps + mode_q65=>state%mode_q65 + nfa=>state%nfa + nfb=>state%nfb + nqd=>state%nqd + idfbest=>state%idfbest + idtbest=>state%idtbest + ibw=>state%ibw + ndistbest=>state%ndistbest + maxiters=>state%maxiters + max_drift=>state%max_drift + istep=>state%istep + nsmo=>state%nsmo + lag1=>state%lag1 + lag2=>state%lag2 + npasses=>state%npasses + iseq=>state%iseq + ncand=>state%ncand + nrc=>state%nrc + i0=>state%i0 + j0=>state%j0 + LL0=>state%LL0 + nhist=>state%nhist + df=>state%df + dtstep=>state%dtstep + dtdec=>state%dtdec + f0dec=>state%f0dec + ftol=>state%ftol + plog=>state%plog + drift=>state%drift + curve_dt=>state%curve_dt + apsym0=>state%apsym0 + aph10=>state%aph10 + apmask1=>state%apmask1 + apsymbols1=>state%apsymbols1 + apmask=>state%apmask + apsymbols=>state%apsymbols + codewords=>state%codewords + navg=>state%navg + nf0=>state%nf0 + candidates=>state%candidates + sync=>state%sync + s1=>state%s1 + s1w=>state%s1w + s1a=>state%s1a + ccf2=>state%ccf2 + ccf2_avg=>state%ccf2_avg + lnewdat=>state%lnewdat +end subroutine + +subroutine q65_initialize_state(state) + type(q65_state), intent(inout) :: state + state%apsym0=0 + state%aph10=0 + state%apmask1=0 + state%apsymbols1=0 + state%apmask=0 + state%apsymbols=0 + state%codewords=0 + state%navg=0 + state%nf0=0 + state%history='' + state%candidates=0. + state%sync=-22.0/63.0 + state%sync(isync)=1. +end subroutine + +subroutine q65_release_state(state) + type(q65_state), intent(inout) :: state + !$omp critical(fftw) + if(state%symbol_plan/=0) call sfftw_destroy_plan(state%symbol_plan) + if(state%analytic_forward/=0) call sfftw_destroy_plan(state%analytic_forward) + if(state%analytic_inverse/=0) call sfftw_destroy_plan(state%analytic_inverse) + !$omp end critical(fftw) + state%symbol_plan=0 + state%analytic_forward=0 + state%analytic_inverse=0 + if(associated(state%s1)) deallocate(state%s1) + if(associated(state%s1w)) deallocate(state%s1w) + if(associated(state%s1a)) deallocate(state%s1a) + if(associated(state%ccf2)) deallocate(state%ccf2) + if(associated(state%ccf2_avg)) deallocate(state%ccf2_avg) +end subroutine + + subroutine q65_dec0(iavg,iwave,ntrperiod,nfqso,ntol,lclearave, & emedelay,xdt,f0,snr1,width,dat4,snr2,idec,stageno) @@ -62,11 +341,8 @@ subroutine q65_dec0(iavg,iwave,ntrperiod,nfqso,ntol,lclearave, & integer*2 iwave(0:12000*ntrperiod-1) !Raw data integer dat4(13) character*37 decoded - logical first,lclearave - real, allocatable :: s3(:,:) !Data-symbol energies s3(LL,63) - real, allocatable :: ccf1(:) !CCF(freq) at fixed lag (red) - data first/.true./ - save first,LL0 + logical lclearave + real, pointer :: s3(:,:),ccf1(:) integer w3t integer w3f @@ -86,32 +362,34 @@ subroutine q65_dec0(iavg,iwave,ntrperiod,nfqso,ntol,lclearave, & df=12000.0/nfft !Freq resolution = baud istep=nsps/NSTEP iz=5000.0/df !Uppermost frequency bin, at 5000 Hz - txt=85.0*nsps/12000.0 - jz=(txt+1.0)*12000.0/istep !Number of symbol/NSTEP bins - if(nsps.ge.6912) jz=(txt+2.0)*12000.0/istep !For TR 60 s and higher + ! Cover every complete symbol FFT window in the received period. + ! Keep jz odd: q65_symspec interpolates even columns between odd ones. + jz=(ntrperiod*12000-nsps)/istep + 1 ftol=ntol ia=ntol/df ia2=max(ia,10*mode_q65,nint(100.0/df)) ! nsmo=int(0.7*mode_q65*mode_q65) nsmo=int(0.5*mode_q65*mode_q65) if(nsmo.lt.1) nsmo=1 - if(first) then !Generate the sync vector - sync=-22.0/63.0 !Sync tone OFF - do k=1,22 - sync(isync(k))=1.0 !Sync tone ON - enddo - endif - allocate(s3(-64:LL-65,63)) - allocate(ccf1(-ia2:ia2)) + if(allocated(q65_work%symbol_energies)) then + if(size(q65_work%symbol_energies,1)/=LL) deallocate(q65_work%symbol_energies) + endif + if(.not.allocated(q65_work%symbol_energies)) allocate(q65_work%symbol_energies(-64:LL-65,63)) + if(allocated(q65_work%correlation)) then + if(size(q65_work%correlation)/=2*ia2+1) deallocate(q65_work%correlation) + endif + if(.not.allocated(q65_work%correlation)) allocate(q65_work%correlation(-ia2:ia2)) + s3=>q65_work%symbol_energies + ccf1=>q65_work%correlation if(LL.ne.LL0 .or. iz.ne.iz0 .or. jz.ne.jz0 .or. lclearave) then - if(allocated(s1)) deallocate(s1) + if(associated(s1)) deallocate(s1) allocate(s1(iz,jz)) - if(allocated(s1a)) deallocate(s1a) + if(associated(s1a)) deallocate(s1a) allocate(s1a(iz,jz,0:1)) - if(allocated(ccf2)) deallocate(ccf2) + if(associated(ccf2)) deallocate(ccf2) allocate(ccf2(iz)) - if(allocated(ccf2_avg)) deallocate(ccf2_avg) + if(associated(ccf2_avg)) deallocate(ccf2_avg) allocate(ccf2_avg(iz)) s1=0. s1a=0. @@ -119,6 +397,13 @@ subroutine q65_dec0(iavg,iwave,ntrperiod,nfqso,ntol,lclearave, & LL0=LL iz0=iz jz0=jz + q65_work%s1=>s1 + q65_work%s1a=>s1a + q65_work%ccf2=>ccf2 + q65_work%ccf2_avg=>ccf2_avg + ccf2=0. + ccf2_avg=0. + q65_work%spectra_valid=.false. lclearave=.false. endif ccf1=0. @@ -133,10 +418,21 @@ subroutine q65_dec0(iavg,iwave,ntrperiod,nfqso,ntol,lclearave, & s3=0. ! if(iavg.eq.0 .and. lnewdat) then + call q65_check_planning() if(iavg.eq.0) then call timer('q65_syms',0) ! Compute symbol spectra with NSTEP time bins per symbol - call q65_symspec(iwave,ntrperiod*12000,iz,jz,s1) + if(.not.q65_work%spectra_valid) then + call q65_symspec(iwave,ntrperiod*12000,iz,jz,s1) + if(allocated(q65_work%prepared)) then + if(any(shape(q65_work%prepared)/=shape(s1))) deallocate(q65_work%prepared) + endif + if(.not.allocated(q65_work%prepared)) allocate(q65_work%prepared(iz,jz)) + q65_work%prepared=s1 + q65_work%spectra_valid=.true. + else + s1=q65_work%prepared + endif call timer('q65_syms',1) ! lnewdat=.false. else @@ -202,7 +498,11 @@ subroutine q65_dec0(iavg,iwave,ntrperiod,nfqso,ntol,lclearave, & enddo width=df*(i2-i1) if(ncw.eq.0) ccf1=0. - call q65_write_red(iz,xdt,ccf2_avg,ccf2) !### Need this call for WSJT-X + call q65_sync_curve(ccf2_avg,1,iz,rms1) + call q65_sync_curve(ccf2,1,iz,rms2) + curve_dt=xdt + q65_work%curve_average_count=navg(iseq) + if(q65_work%legacy_output) call q65_write_red(iz,xdt,ccf2_avg,ccf2) if(idec.lt.0 .and. (iavg.eq.0 .or. iavg.eq.2)) then call q65_dec_q012(s3,LL,snr2,dat4,idec,decoded) @@ -210,13 +510,17 @@ subroutine q65_dec0(iavg,iwave,ntrperiod,nfqso,ntol,lclearave, & if(idec.lt.0 .and. max_drift.eq.50 .and. stageno.eq.5) then - if(allocated(s1w)) deallocate(s1w) ! w3sz - allocate(s1w(iz,jz)) ! w3sz + if(associated(s1w)) then + if(any(shape(s1w)/=[iz,jz])) deallocate(s1w) + endif + if(.not.associated(s1w)) allocate(s1w(iz,jz)) + q65_work%s1w=>s1w s1w=s1 do w3t=1,jz do w3f=1,iz - mm=w3f + nint(drift*w3t/(jz*df)) + ! Drift is measured over the 85-symbol transmission. + mm=w3f + nint(drift*w3t/(85*NSTEP*df)) if(mm.ge.1 .and. mm.le.iz) then s1w(w3f,w3t)=s1(mm,w3t) endif @@ -256,7 +560,7 @@ subroutine q65_clravg ! Clear the averaging array to start a new average. - if(allocated(s1a)) s1a(:,:,iseq)=0. + if(associated(s1a)) s1a(:,:,iseq)=0. navg(iseq)=0 return @@ -268,23 +572,36 @@ subroutine q65_symspec(iwave,nmax,iz,jz,s1) integer*2 iwave(0:nmax-1) !Raw data real s1(iz,jz) - complex c0(0:41472) !Largest requirement, Q65-300x - save c0 + complex, pointer :: c0(:) + integer flags nfft=nsps + if(.not.allocated(q65_work%symbol_fft)) allocate(q65_work%symbol_fft(0:41472)) + c0=>q65_work%symbol_fft + call q65_check_planning() + if(q65_work%symbol_length/=nfft.or.q65_work%symbol_plan==0) then + !$omp critical(fftw) + if(q65_work%symbol_plan/=0) call sfftw_destroy_plan(q65_work%symbol_plan) + flags=q65_fft_flags() + call sfftw_plan_dft_r2c_1d(q65_work%symbol_plan,nfft,c0,c0,flags) + !$omp end critical(fftw) + q65_work%symbol_length=nfft + endif fac=1/32767.0 do j=1,jz,2 !Compute symbol spectra at 2*step size i1=(j-1)*istep i2=i1+nsps-1 k=-1 do i=i1,i2,2 !Load iwave data into complex array c0, for r2c FFT - xx=iwave(i) - yy=iwave(i+1) + xx=0. + yy=0. + if(i<nmax) xx=iwave(i) + if(i+1<nmax) yy=iwave(i+1) k=k+1 c0(k)=fac*cmplx(xx,yy) enddo c0(k+1:nfft-1)=0. - call four2a(c0,nfft,1,-1,0) !r2c FFT + call sfftw_execute(q65_work%symbol_plan) do i=1,iz s1(i,j)=real(c0(i))**2 + aimag(c0(i))**2 enddo @@ -400,14 +717,18 @@ subroutine q65_ccf_85(s1,iz,jz,nfqso,ia,ia2,ipk,jpk,f0,xdt,imsg_best, & ! attempt at q3 decoding. Return ccf1 for the "red sync curve". real s1(iz,jz) - real, allocatable :: ccf(:,:) !CCF(freq,lag) - real, allocatable :: best(:) !best(imsg) -- for checking 2nd best + real, pointer :: ccf(:,:),best(:) real ccf1(-ia2:ia2) integer ijpk(2) integer itone(85) - allocate(ccf(-ia2:ia2,-53:214)) - allocate(best(ncw)) + if(allocated(q65_work%list_correlation)) then + if(size(q65_work%list_correlation,1)/=2*ia2+1) deallocate(q65_work%list_correlation) + endif + if(.not.allocated(q65_work%list_correlation)) allocate(q65_work%list_correlation(-ia2:ia2,-53:214)) + if(.not.allocated(q65_work%best_list)) allocate(q65_work%best_list(Q65_MAX_CODEWORDS)) + ccf=>q65_work%list_correlation + best=>q65_work%best_list(:ncw) ipk=0 jpk=0 ccf_best=0. @@ -455,11 +776,10 @@ subroutine q65_ccf_85(s1,iz,jz,nfqso,ia,ia2,ipk,jpk,f0,xdt,imsg_best, & best(imsg)=ccfmax enddo ! imsg - deallocate(ccf) better=0. if(imsg_best.gt.0) then best(imsg_best)=0. - better=ccf_best/maxval(best) + if(maxval(best)>0.) better=ccf_best/maxval(best) endif return @@ -473,13 +793,18 @@ subroutine q65_ccf_22(s1,iz,jz,nfqso,ntol,ipk,jpk,f0,xdt,ccf2) real s1(iz,jz) real ccf2(iz) !Orange sync curve real tmp(20,3) - real, allocatable :: xdt2(:) - real, allocatable :: s1avg(:) - integer, allocatable :: indx(:) + real, pointer :: xdt2(:),s1avg(:) + integer, pointer :: indx(:) - allocate(xdt2(iz)) - allocate(s1avg(iz)) - allocate(indx(iz)) + if(allocated(q65_work%timing)) then + if(size(q65_work%timing)<iz) deallocate(q65_work%timing,q65_work%spectrum_average,q65_work%ordering) + endif + if(.not.allocated(q65_work%timing)) then + allocate(q65_work%timing(iz),q65_work%spectrum_average(iz),q65_work%ordering(iz)) + endif + xdt2=>q65_work%timing(:iz) + s1avg=>q65_work%spectrum_average(:iz) + indx=>q65_work%ordering(:iz) ia=max(nfa,100)/df ib=min(nfb,4900)/df @@ -487,7 +812,20 @@ subroutine q65_ccf_22(s1,iz,jz,nfqso,ntol,ipk,jpk,f0,xdt,ccf2) ia=max(nint(100/df),nint((nfqso-ntol)/df)) ib=min(nint(4900/df),nint((nfqso+ntol)/df)) endif - if(ia.ge.ib) ia=ib-ntol/df !Protect against wacky settings + if(ia.ge.ib) ia=ib-ntol/df + ia=max(1,ia) + ib=min(iz,ib) + if(ia>ib) then + ipk=0 + jpk=0 + f0=nfqso + xdt=0. + drift=0. + ncand=0 + candidates=0. + ccf2=0. + return + endif do i=ia,ib s1avg(i)=sum(s1(i,1:jz)) @@ -551,6 +889,8 @@ subroutine q65_ccf_22(s1,iz,jz,nfqso,ntol,ipk,jpk,f0,xdt,ccf2) call pctile(ccf2(ia:ib),jzz,84,base) rms=base-ave ncand=0 + candidates=0. + if(rms<=0.) return maxcand=20 do j=1,20 k=jzz-j+1 @@ -586,7 +926,7 @@ subroutine q65_dec1(s3,nsubmode,b90ts,esnodb,irc,dat4,decoded) ! Attmpt a full-AP list decode. use packjt77 - real s3(1,1) !Silence compiler warning that wants to see a 2D array + real s3(64*(2+2**nsubmode),63) real s3prob(0:63,63) !Symbol-value probabilities integer dat4(13) character c77*77,decoded*37 @@ -594,13 +934,19 @@ subroutine q65_dec1(s3,nsubmode,b90ts,esnodb,irc,dat4,decoded) nFadingModel=1 decoded=' ' + if(ncw<=0.or.maxval(s3)<=0.) then + dat4=0 + esnodb=0. + irc=-1 + return + endif call q65_intrinsics_ff(s3,nsubmode,b90ts,nFadingModel,s3prob) call q65_dec_fullaplist(s3,s3prob,codewords,ncw,esnodb,dat4,plog,irc) if(sum(dat4).le.0) irc=-2 if(irc.ge.0 .and. plog.gt.PLOG_MIN) then write(c77,1000) dat4(1:12),dat4(13)/2 1000 format(12b6.6,b5.5) - call unpack77(c77,0,decoded,unpk77_success) !Unpack to get msgsent + call q65_unpack(c77,0,decoded,unpk77_success) !Unpack to get msgsent else irc=-1 endif @@ -614,7 +960,7 @@ subroutine q65_dec2(s3,nsubmode,b90ts,esnodb,irc,dat4,decoded) ! Attempt a q0, q1, or q2 decode using spcified AP information. use packjt77 - real s3(iz0,jz0) !Silence compiler warning that wants to see a 2D array + real s3(64*(2+2**nsubmode),63) real s3prob(0:63,63) !Symbol-value probabilities integer dat4(13) character c77*77,decoded*37 @@ -622,6 +968,10 @@ subroutine q65_dec2(s3,nsubmode,b90ts,esnodb,irc,dat4,decoded) nFadingModel=1 decoded=' ' + dat4=0 + esnodb=0. + irc=-1 + if(maxval(s3)<=0.) return call q65_intrinsics_ff(s3,nsubmode,b90ts,nFadingModel,s3prob) call q65_dec(s3,s3prob,APmask,APsymbols,maxiters,esnodb,dat4,irc) if(sum(dat4).le.0) irc=-2 @@ -629,7 +979,7 @@ subroutine q65_dec2(s3,nsubmode,b90ts,esnodb,irc,dat4,decoded) if(irc.ge.0) then write(c77,1000) dat4(1:12),dat4(13)/2 1000 format(12b6.6,b5.5) - call unpack77(c77,0,decoded,unpk77_success) !Unpack to get msgsent + call q65_unpack(c77,0,decoded,unpk77_success) !Unpack to get msgsent endif return @@ -669,9 +1019,6 @@ subroutine q65_write_red(iz,xdt,ccf2_avg,ccf2) real ccf2_avg(iz) real ccf2(iz) - call q65_sync_curve(ccf2_avg,1,iz,rms1) - call q65_sync_curve(ccf2,1,iz,rms2) - i1=max(1,nint(nfa/df)) i2=min(iz,int(nfb/df)) y0=minval(ccf2(i1:i2)) @@ -720,9 +1067,13 @@ subroutine q65_bzap(s3,LL) parameter (NBZAP=15) real s3(-64:LL-65,63) integer ipk1(1) - integer, allocatable :: hist(:) + integer, pointer :: hist(:) - allocate(hist(-64:LL-65)) + if(allocated(q65_work%birdie_histogram)) then + if(size(q65_work%birdie_histogram)<LL) deallocate(q65_work%birdie_histogram) + endif + if(.not.allocated(q65_work%birdie_histogram)) allocate(q65_work%birdie_histogram(-64:LL-65)) + hist(-64:)=>q65_work%birdie_histogram(-64:LL-65) hist=0 do j=1,63 ipk1=maxloc(s3(:,j)) @@ -746,9 +1097,13 @@ subroutine q65_snr(dat4,dtdec,f0dec,mode_q65,snr2) integer dat4(13) integer codeword(63) integer itone(85) - real, allocatable :: spec(:) + real, pointer :: spec(:) - allocate(spec(iz0)) + if(allocated(q65_work%snr_spectrum)) then + if(size(q65_work%snr_spectrum)<iz0) deallocate(q65_work%snr_spectrum) + endif + if(.not.allocated(q65_work%snr_spectrum)) allocate(q65_work%snr_spectrum(iz0)) + spec=>q65_work%snr_spectrum(:iz0) call q65_enc(dat4,codeword) i=1 k=0 @@ -799,20 +1154,19 @@ subroutine q65_hist(if0,msg0,dxcall,dxgrid) parameter (MAXHIST=100) integer,intent(in) :: if0 !Audio freq of decode character(len=37),intent(in),optional :: msg0 !Decoded message - character(len=12),intent(out),optional :: dxcall !Second callsign in message - character(len=6),intent(out),optional :: dxgrid !Third word in msg, if grid + character(len=12),intent(inout),optional :: dxcall !Second callsign in message + character(len=6),intent(inout),optional :: dxgrid !Third word in msg, if grid character*6 g1 - character*37 msg(MAXHIST) !Saved messages - integer nf0(MAXHIST) !Saved frequencies + character(len=37), pointer :: msg(:) logical isgrid !Statement function - data nhist/0/ - save nhist,nf0,msg + isgrid(g1)=g1(1:1).ge.'A' .and. g1(1:1).le.'R' .and. g1(2:2).ge.'A' .and. & g1(2:2).le.'R' .and. g1(3:3).ge.'0' .and. g1(3:3).le.'9' .and. & g1(4:4).ge.'0' .and. g1(4:4).le.'9' .and. g1(1:4).ne.'RR73' + msg=>q65_work%history if(present(dxcall)) go to 100 !This is a lookup request if(nhist.eq.MAXHIST) then @@ -844,66 +1198,21 @@ subroutine q65_hist(if0,msg0,dxcall,dxgrid) 900 return end subroutine q65_hist -subroutine q65_hist2(nfreq,msg0,callers,nhist2) - - use types - use prog_args - parameter (MAX_CALLERS=50) !For multiple q3 decodes in NA VHF Contest mode - character*37 msg0,msg - type(q3list) callers(MAX_CALLERS) - character*6 c6 - character*4 g4 - logical newcall,isgrid - - isgrid(g4)=g4(1:1).ge.'A' .and. g4(1:1).le.'R' .and. g4(2:2).ge.'A' .and. & - g4(2:2).le.'R' .and. g4(3:3).ge.'0' .and. g4(3:3).le.'9' .and. & - g4(4:4).ge.'0' .and. g4(4:4).le.'9' .and. g4(1:4).ne.'RR73' - - msg=msg0 - if(index(msg,'/').gt.0) goto 900 !Ignore messages with compound calls - i0=index(msg,' R ') - if(i0.ge.7) msg=msg(1:i0)//msg(i0+3:) - i1=index(msg,' ') - c6=' ' - g4=' ' - if(i1.ge.4 .and. i1.le.13) then - i2=index(msg(i1+1:),' ') + i1 - c6=msg(i1+1:i2-1) !Extract DX call - g4=msg(i2+1:i2+4) !Extract DX grid - endif - - newcall=.true. - do i=1,nhist2 - if(callers(i)%call .eq. c6) then - newcall=.false. - callers(i)%nsec=time() - callers(i)%nfreq=nfreq - exit - endif - enddo - - if(newcall .and. isgrid(g4)) then - if(nhist2.eq.MAX_CALLERS) then -! Purge the oldest caller - callers(1:MAX_CALLERS-1)=callers(2:MAX_CALLERS) - nhist2=nhist2-1 - endif - nhist2=nhist2+1 - callers(nhist2)%call=c6 - callers(nhist2)%grid=g4 - callers(nhist2)%nsec=time() - callers(nhist2)%nfreq=nfreq - endif - - if(nhist2.ge.1 .and. nhist2.le.40) then - open(24,file=trim(data_dir)//'/tsil.3q',status='unknown', & - form='unformatted') - write(24) nhist2 - write(24) callers(1:nhist2) - close(24) - endif - -900 return +subroutine q65_hist2(nfreq,msg0,callers,nhist2,persist) + + use types, only: q3list + use prog_args, only: data_dir + use q65_callers, only: Q65_MAX_CALLERS,q65_record_caller,q65_save_callers + implicit none + integer, intent(in) :: nfreq + character(len=*), intent(in) :: msg0 + type(q3list), intent(inout) :: callers(Q65_MAX_CALLERS) + integer, intent(inout) :: nhist2 + logical, intent(in) :: persist + integer :: status,time + + call q65_record_caller(callers,nhist2,nfreq,msg0,time()) + if(persist) call q65_save_callers(trim(data_dir)//'/tsil.3q',callers,nhist2,status) end subroutine q65_hist2 end module q65 diff --git a/lib/qra/q65/q65.h b/lib/qra/q65/q65.h index ab1b389d..06dd9b27 100644 --- a/lib/qra/q65/q65.h +++ b/lib/qra/q65/q65.h @@ -23,6 +23,7 @@ #define _q65_h #include "qracodes.h" +#include "q65_limits.h" // Error codes returned by q65_decode(...) #define Q65_DECODE_INVPARAMS -1 @@ -34,9 +35,7 @@ // Verify loglikelihood after successful decoding #define Q65_CHECKLLH // Max codeword list size in q65_decode_fullaplist -// See MAX_NCW in q65_set_list2.f90 (not required to be a power of 2 -- -// this value is only ever used in a plain bounds check). -#define Q65_FULLAPLIST_SIZE 411 +#define Q65_FULLAPLIST_SIZE Q65_AP_LIST_CAPACITY // maximum number of weights for the fast-fading metric evaluation #define Q65_FASTFADING_MAXWEIGTHS 65 diff --git a/lib/qra/q65/q65_callers.F90 b/lib/qra/q65/q65_callers.F90 new file mode 100644 index 00000000..224ca60f --- /dev/null +++ b/lib/qra/q65/q65_callers.F90 @@ -0,0 +1,142 @@ +#include "q65_limits.h" +module q65_callers + use types, only: q3list + use, intrinsic :: iso_fortran_env, only: int64 + implicit none + private + integer, parameter, public :: Q65_MAX_CALLERS=Q65_CALLER_CAPACITY + integer, parameter, public :: Q65_ROW_WIDTH=Q65_CALLER_ROW_WIDTH + integer, parameter, public :: Q65_MAX_CODEWORDS=Q65_AP_LIST_CAPACITY + public :: q65_load_callers,q65_save_callers,q65_expire_callers + public :: q65_record_caller,q65_remove_caller + +contains + + subroutine q65_load_callers(filename,callers,count,status) + character(len=*), intent(in) :: filename + type(q3list), intent(out) :: callers(Q65_MAX_CALLERS) + integer, intent(out) :: count,status + type(q3list) :: loaded(Q65_MAX_CALLERS) + integer :: unit,n,close_status,file_size + logical :: exists + + callers=q3list('','',0,0,0) + count=0 + exists=.false. + file_size=-1 + inquire(file=filename,exist=exists,size=file_size,iostat=status) + if(status.ne.0) return + if(.not.exists .or. file_size.eq.0) return + open(newunit=unit,file=filename,status='old',form='unformatted',action='read',iostat=status) + if(status.ne.0) return + loaded=q3list('','',0,0,0) + read(unit,iostat=status) n + if(status.eq.0) then + if(n.lt.0 .or. n.gt.Q65_MAX_CALLERS) then + status=1 + else + read(unit,iostat=status) loaded(1:n) + endif + endif + close(unit,iostat=close_status) + if(status.eq.0) status=close_status + if(status.ne.0) return + callers=loaded + count=n + end subroutine q65_load_callers + + subroutine q65_save_callers(filename,callers,count,status) + character(len=*), intent(in) :: filename + type(q3list), intent(in) :: callers(Q65_MAX_CALLERS) + integer, intent(in) :: count + integer, intent(out) :: status + integer :: unit,close_status + + status=1 + if(count.lt.0 .or. count.gt.Q65_MAX_CALLERS) return + open(newunit=unit,file=filename,status='replace',form='unformatted',action='write',iostat=status) + if(status.ne.0) return + write(unit,iostat=status) count + if(status.eq.0) write(unit,iostat=status) callers(1:count) + close(unit,iostat=close_status) + if(status.eq.0) status=close_status + end subroutine q65_save_callers + + subroutine q65_expire_callers(callers,count,now) + type(q3list), intent(inout) :: callers(Q65_MAX_CALLERS) + integer, intent(inout) :: count + integer, intent(in) :: now + integer :: i,kept + + kept=0 + do i=1,count + if(int(now,int64)-int(callers(i)%nsec,int64).gt.86400_int64) cycle + kept=kept+1 + callers(kept)=callers(i) + enddo + count=kept + callers(count+1:)=q3list('','',0,0,0) + end subroutine q65_expire_callers + + subroutine q65_record_caller(callers,count,freq,msg,now) + type(q3list), intent(inout) :: callers(Q65_MAX_CALLERS) + integer, intent(inout) :: count + integer, intent(in) :: freq,now + character(len=*), intent(in) :: msg + character(len=37) :: text + character(len=6) :: call + character(len=4) :: grid + integer :: i,i0,i1,i2,oldest + + call q65_expire_callers(callers,count,now) + text=msg + if(index(text,'/').gt.0) return + i0=index(text,' R ') + if(i0.ge.7) text=text(1:i0)//text(i0+3:) + i1=index(text,' ') + if(i1.lt.4 .or. i1.gt.13) return + i2=index(text(i1+1:),' ')+i1 + if(i2.le.i1+1 .or. i2+4.gt.len(text)) return + call=text(i1+1:i2-1) + grid=text(i2+1:i2+4) + do i=1,count + if(callers(i)%call.ne.call) cycle + callers(i)%nsec=now + callers(i)%nfreq=freq + return + enddo + if(.not.valid_grid(grid)) return + if(count.eq.Q65_MAX_CALLERS) then + oldest=minloc(callers(1:count)%nsec,dim=1) + callers(oldest:count-1)=callers(oldest+1:count) + count=count-1 + endif + count=count+1 + callers(count)=q3list(call,grid,now,freq,0) + end subroutine q65_record_caller + + subroutine q65_remove_caller(callers,count,call) + type(q3list), intent(inout) :: callers(Q65_MAX_CALLERS) + integer, intent(inout) :: count + character(len=*), intent(in) :: call + character(len=6) :: target + integer :: i + + target=call + do i=1,count + if(callers(i)%call.ne.target) cycle + callers(i:count-1)=callers(i+1:count) + callers(count)=q3list('','',0,0,0) + count=count-1 + return + enddo + end subroutine q65_remove_caller + + logical function valid_grid(grid) + character(len=4), intent(in) :: grid + valid_grid=grid(1:1).ge.'A' .and. grid(1:1).le.'R' .and. & + grid(2:2).ge.'A' .and. grid(2:2).le.'R' .and. & + grid(3:3).ge.'0' .and. grid(3:3).le.'9' .and. & + grid(4:4).ge.'0' .and. grid(4:4).le.'9' .and. grid.ne.'RR73' + end function valid_grid +end module q65_callers diff --git a/lib/qra/q65/q65_limits.h b/lib/qra/q65/q65_limits.h new file mode 100644 index 00000000..533a9399 --- /dev/null +++ b/lib/qra/q65/q65_limits.h @@ -0,0 +1,8 @@ +#ifndef WSJT_Q65_LIMITS_H +#define WSJT_Q65_LIMITS_H + +#define Q65_CALLER_CAPACITY 50 +#define Q65_CALLER_ROW_WIDTH 37 +#define Q65_AP_LIST_CAPACITY (1 + 10 * (Q65_CALLER_CAPACITY + 1)) + +#endif diff --git a/lib/qra/q65/q65_loops.f90 b/lib/qra/q65/q65_loops.f90 index 4a5bc34f..b7e706f2 100644 --- a/lib/qra/q65/q65_loops.f90 +++ b/lib/qra/q65/q65_loops.f90 @@ -18,6 +18,7 @@ subroutine q65_loops(workspace,c00,npts2,nsps2,nsubmode,ndepth,jpk0, & LL=64*(mode_q65+2) call workspace%ensure(npts2,LL) + call workspace%prepare_fft(nsps2) idec=-1 ircbest=9999 irc=-99 @@ -61,8 +62,9 @@ subroutine q65_loops(workspace,c00,npts2,nsps2,nsubmode,ndepth,jpk0, & jpk=max(0,jpk) jpk=min(29000,jpk) call spec64(workspace%c0(0:npts2-1),workspace%cs,npts2,nsps2, & - mode_q65,jpk,workspace%s3(1:LL*NN),LL,NN) + mode_q65,jpk,workspace%s3(1:LL*NN),LL,NN,workspace%plan) call pctile(workspace%s3(1:LL*NN),LL*NN,40,base) + if(base<=0.) cycle workspace%s3(1:LL*NN)=workspace%s3(1:LL*NN)/base where(workspace%s3(1:LL*NN)>s3lim) workspace%s3(1:LL*NN)=s3lim call q65_bzap(workspace%s3(1:LL*NN),LL) !Zap birdies diff --git a/lib/qra/q65/q65_set_list2.f90 b/lib/qra/q65/q65_set_list2.f90 index 433802fb..7043dbad 100644 --- a/lib/qra/q65/q65_set_list2.f90 +++ b/lib/qra/q65/q65_set_list2.f90 @@ -1,17 +1,16 @@ subroutine q65_set_list2(mycall,hiscall,hisgrid,callers,nhist2,codewords,ncw) use types - parameter (MAX_NCW=411) !1 + 40 stored callers plus the current call, 5 kinds, 2 flags - parameter (MAX_CALLERS=50) !For multiple q3 decodes in NA VHF Contest mode + use q65_callers, only: Q65_MAX_CALLERS,Q65_MAX_CODEWORDS character*12 mycall,hiscall character*6 hisgrid,c6 character*4 g4 character*37 msg,msgsent logical std,isgrid - integer codewords(63,MAX_NCW) + integer codewords(63,Q65_MAX_CODEWORDS) integer itone(85) integer isync(22) - type(q3list) callers(MAX_CALLERS) + type(q3list) callers(Q65_MAX_CALLERS) data isync/1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85/ @@ -19,10 +18,13 @@ subroutine q65_set_list2(mycall,hiscall,hisgrid,callers,nhist2,codewords,ncw) g4(2:2).le.'R' .and. g4(3:3).ge.'0' .and. g4(3:3).le.'9' .and. & g4(4:4).ge.'0' .and. g4(4:4).le.'9' .and. g4(1:4).ne.'RR73' + ncw=0 + if(nhist2.lt.0 .or. nhist2.gt.Q65_MAX_CALLERS) return + call stdcall(hiscall,std) jmax=nhist2 if(std .and. isgrid(hisgrid(1:4))) then - jmax=min(MAX_CALLERS,nhist2+1) + jmax=nhist2+1 do j=1,nhist2 if(callers(j)%call .eq. hiscall(1:6)) then jmax=nhist2 @@ -34,11 +36,12 @@ subroutine q65_set_list2(mycall,hiscall,hisgrid,callers,nhist2,codewords,ncw) codewords(:,1)=0 i=1 do j=1,jmax - c6=callers(j)%call - g4=callers(j)%grid if(j.eq.nhist2+1) then c6=hiscall(1:6) g4=hisgrid(1:4) + else + c6=callers(j)%call + g4=callers(j)%grid endif do k=1,5 msg=trim(mycall)//' '//trim(c6) diff --git a/lib/qra/q65/q65_subs.c b/lib/qra/q65/q65_subs.c index 4311ba39..8e9a8481 100644 --- a/lib/qra/q65/q65_subs.c +++ b/lib/qra/q65/q65_subs.c @@ -1,147 +1,130 @@ -// q65_subs.c +/* Owned and legacy Fortran interfaces for the Q65 codec. */ -/* Fortran interface for Q65 codec - - To encode a Q65 message: - - integer x(13) !Message payload, 78 bits as 13 six-bit integers - integer y(63) !Codeword, 63 six-bit integers - call q65_enc(imsg,icodeword) - - To decode a Q65 message: - - parameter (LL=64,NN=63) - real s3(LL,NN) !Received energies - real s3prob(LL,NN) !Symbol-value probabilities - integer APmask(13) - integer APsymbols(13) - real snr2500 - integer xdec(13) !Decoded 78-bit message as 13 six-bit integers - integer irc !Return code from q65_decode() - - call q65_dec(s3,APmask,APsymbols,s3prob,snr2500,xdec,irc) -*/ - -#include "qra15_65_64_irr_e23.h" // QRA code used by Q65 +#include "qra15_65_64_irr_e23.h" #include "q65.h" #include <stdio.h> #include <stdlib.h> +#include <string.h> -static q65_codec_ds codec; - -void q65_enc_(int x[], int y[]) +void *q65_codec_create(void) { - - static int first=1; - if (first) { - // Set the QRA code, allocate memory, and initialize - int rc = q65_init(&codec,&qra15_65_64_irr_e23); - if (rc<0) { - printf("error in q65_init()\n"); - exit(0); - } - first=0; + q65_codec_ds *codec = calloc(1, sizeof(*codec)); + if (!codec) return NULL; + if (q65_init(codec, &qra15_65_64_irr_e23) < 0) { + free(codec); + return NULL; } - // Encode message x[13], producing codeword y[63] - q65_encode(&codec,y,x); + return codec; } -void q65_intrinsics_ff_(float s3[], int* submode, float* B90Ts, - int* fadingModel, float s3prob[]) +void q65_codec_destroy(void *handle) { + if (!handle) return; + q65_free(handle); + free(handle); +} -/* Input: s3[LL,NN] Received energies - * submode 0=A, 4=E - * B90 Spread bandwidth, 90% fractional energy - * fadingModel 0=Gaussian, 1=Lorentzian - * Output: s3prob[LL,NN] Symbol-value intrinsic probabilities - */ +int q65_codec_encode(void *handle, const int *x, int *y) +{ + memset(y, 0, 63 * sizeof(*y)); + if (!handle) return -1; + return q65_encode(handle, y, x) < 0 ? -1 : 0; +} - int rc; - static int first=1; +int q65_codec_intrinsics(void *handle, const float *s3, int submode, + float b90ts, int fading_model, float *prob) +{ + memset(prob, 0, 64 * 63 * sizeof(*prob)); + if (!handle) return -1; + return q65_intrinsics_fastfading(handle, prob, s3, submode, b90ts, + fading_model) < 0 ? -1 : 0; +} - if (first) { - // Set the QRA code, allocate memory, and initialize - int rc = q65_init(&codec,&qra15_65_64_irr_e23); - if (rc<0) { - printf("error in q65_init()\n"); - exit(0); - } - first=0; - } - rc = q65_intrinsics_fastfading(&codec,s3prob,s3,*submode,*B90Ts,*fadingModel); - if(rc<0) { - printf("error in q65_intrinsics()\n"); - exit(0); +int q65_codec_decode(void *handle, const float *s3, const float *prob, + const int *mask, const int *symbols, int maxiters, + float *esnodb, int *xdec, int *decode_rc) +{ + int ydec[63]; + *esnodb = 0; + *decode_rc = Q65_DECODE_INVPARAMS; + memset(xdec, 0, 13 * sizeof(*xdec)); + if (!handle) return -1; + *decode_rc = q65_decode(handle, ydec, xdec, prob, mask, symbols, maxiters); + if (*decode_rc == Q65_DECODE_INVPARAMS) return -1; + if (*decode_rc < 0) return 0; + if (q65_esnodb_fastfading(handle, esnodb, ydec, s3) < 0) { + *decode_rc = Q65_DECODE_INVPARAMS; + *esnodb = 0; + return -1; } + return 0; } - -void q65_dec_(float s3[], float s3prob[], int APmask[], int APsymbols[], - int* maxiters0, float* esnodb0, int xdec[], int* rc0) -{ -/* Input: s3[LL,NN] Symbol spectra - * s3prob[LL,NN] Symbol-value intrinsic probabilities - * APmask[13] AP information to be used in decoding - * APsymbols[13] Available AP informtion - * Output: - * esnodb0 Estimated Es/No (dB) - * xdec[13] Decoded 78-bit message as 13 six-bit integers - * rc0 Return code from q65_decode() - */ - - int rc; +int q65_codec_decode_fullaplist(void *handle, const float *s3, const float *prob, + const int *codewords, int ncw, float *esnodb, + int *xdec, float *plog, int *decode_rc) +{ int ydec[63]; - float esnodb; - int maxiters=*maxiters0; + *esnodb = 0; + *plog = 0; + *decode_rc = Q65_DECODE_INVPARAMS; + memset(xdec, 0, 13 * sizeof(*xdec)); + if (!handle) return -1; + *decode_rc = q65_decode_fullaplist(handle, ydec, xdec, prob, codewords, ncw); + if (*decode_rc == Q65_DECODE_INVPARAMS) return -1; + *plog = q65_llh; + if (*decode_rc < 0) return 0; + if (q65_esnodb_fastfading(handle, esnodb, ydec, s3) < 0) { + *decode_rc = Q65_DECODE_INVPARAMS; + *esnodb = 0; + return -1; + } + return 0; +} - rc = q65_decode(&codec,ydec,xdec,s3prob,APmask,APsymbols,maxiters); - *rc0=rc; - // rc = -1: Invalid params - // rc = -2: Decode failed - // rc = -3: CRC mismatch - *esnodb0 = 0.0; //Default Es/No for a failed decode - if(rc<0) return; +static q65_codec_ds *legacy_codec(void) +{ + static q65_codec_ds *codec; + if (!codec) { + codec = q65_codec_create(); + if (!codec) { + fputs("Unable to initialize Q65 codec\n", stderr); + exit(EXIT_FAILURE); + } + } + return codec; +} - rc = q65_esnodb_fastfading(&codec,&esnodb,ydec,s3); - if(rc<0) { - printf("error in q65_esnodb_fastfading()\n"); - exit(0); +static void check_legacy_status(int status) +{ + if (status < 0) { + fputs("Q65 codec operation failed\n", stderr); + exit(EXIT_FAILURE); } - *esnodb0 = esnodb; } -void q65_dec_fullaplist_(float s3[], float s3prob[], int codewords[], - int* ncw, float* esnodb0, int xdec[], float* plog, int* rc0) +void q65_enc_(int x[], int y[]) { -/* Input: s3[LL,NN] Symbol spectra - * s3prob[LL,NN] Symbol-value intrinsic probabilities - * codewords[63,ncw] Full codewords to search for - * ncw Number of codewords - * Output: - * esnodb0 Estimated Es/No (dB) - * xdec[13] Decoded 78-bit message as 13 six-bit integers - * rc0 Return code from q65_decode() - */ + check_legacy_status(q65_codec_encode(legacy_codec(), x, y)); +} - int rc; - int ydec[63]; - float esnodb; +void q65_intrinsics_ff_(float s3[], int *submode, float *b90ts, + int *fading_model, float prob[]) +{ + check_legacy_status(q65_codec_intrinsics(legacy_codec(), s3, *submode, + *b90ts, *fading_model, prob)); +} - rc = q65_decode_fullaplist(&codec,ydec,xdec,s3prob,codewords,*ncw); - *plog=q65_llh; - *rc0=rc; - - // rc = -1: Invalid params - // rc = -2: Decode failed - // rc = -3: CRC mismatch - *esnodb0 = 0.0; //Default Es/No for a failed decode - if(rc<0) return; +void q65_dec_(float s3[], float prob[], int mask[], int symbols[], + int *maxiters, float *esnodb, int xdec[], int *rc) +{ + q65_codec_decode(legacy_codec(), s3, prob, mask, symbols, + *maxiters, esnodb, xdec, rc); +} - rc = q65_esnodb_fastfading(&codec,&esnodb,ydec,s3); - if(rc<0) { - printf("error in q65_esnodb_fastfading()\n"); - exit(0); - } - *esnodb0 = esnodb; +void q65_dec_fullaplist_(float s3[], float prob[], int codewords[], + int *ncw, float *esnodb, int xdec[], float *plog, int *rc) +{ + q65_codec_decode_fullaplist(legacy_codec(), s3, prob, codewords, + *ncw, esnodb, xdec, plog, rc); } diff --git a/lib/qra/q65/q65_workspace.f90 b/lib/qra/q65/q65_workspace.f90 index 321bdfd4..00af36c0 100644 --- a/lib/qra/q65/q65_workspace.f90 +++ b/lib/qra/q65/q65_workspace.f90 @@ -1,5 +1,7 @@ module q65_workspace + use iso_c_binding, only: c_int64_t + use fftw3 implicit none integer, parameter :: Q65_NN=63 @@ -9,8 +11,13 @@ module q65_workspace complex, allocatable :: c0(:) real, allocatable :: s3(:) complex, allocatable :: cs(:) + integer(c_int64_t) :: plan=0 + integer :: plan_length=0,planning=-1 contains procedure :: ensure => ensure_q65_workspace + procedure :: prepare_fft + procedure :: destroy + final :: finalize end type q65_workspace_type contains @@ -40,4 +47,39 @@ contains if(.not.allocated(this%cs)) allocate(this%cs(0:Q65_MAXFFT-1)) end subroutine ensure_q65_workspace + subroutine prepare_fft(this,length) + class(q65_workspace_type), intent(inout) :: this + integer, intent(in) :: length + integer npatience,nthreads,flags + common/patience/npatience,nthreads + if(this%plan/=0.and.this%plan_length==length.and.this%planning==npatience) return + !$omp critical(fftw) + if(this%plan/=0) call sfftw_destroy_plan(this%plan) + flags=FFTW_ESTIMATE + if(npatience==1) flags=FFTW_ESTIMATE_PATIENT + if(npatience==2) flags=FFTW_MEASURE + if(npatience==3) flags=FFTW_PATIENT + if(npatience==4) flags=FFTW_EXHAUSTIVE + call sfftw_plan_dft_1d(this%plan,length,this%cs,this%cs,FFTW_FORWARD,flags) + !$omp end critical(fftw) + this%plan_length=length + this%planning=npatience + end subroutine + + subroutine destroy(this) + class(q65_workspace_type), intent(inout) :: this + !$omp critical(fftw) + if(this%plan/=0) call sfftw_destroy_plan(this%plan) + !$omp end critical(fftw) + this%plan=0 + if(allocated(this%c0)) deallocate(this%c0) + if(allocated(this%s3)) deallocate(this%s3) + if(allocated(this%cs)) deallocate(this%cs) + end subroutine + + subroutine finalize(this) + type(q65_workspace_type), intent(inout) :: this + call this%destroy() + end subroutine + end module q65_workspace diff --git a/lib/shmem.cpp b/lib/shmem.cpp index 7d1783d6..113babfc 100644 --- a/lib/shmem.cpp +++ b/lib/shmem.cpp @@ -1,18 +1,50 @@ -#include <QSharedMemory> -#include <QLatin1String> +#include "NativeSharedMemory.hpp" +#include "DecoderWorkerLock.hpp" +#include <memory> +#include <cstdio> +#include <exception> -// Multiple instances: KK1D, 17 Jul 2013 -QSharedMemory shmem; - -struct jt9com; +namespace +{ + // Release the mapping before the lifetime lock, after all Fortran cleanup. + std::unique_ptr<DecoderWorkerLock> worker_lock; + NativeSharedMemory shmem; +} -// C wrappers for a QSharedMemory class instance extern "C" { - bool shmem_create (int nsize) {return shmem.create(nsize);} - void shmem_setkey (char * const mykey) {shmem.setKey(QLatin1String{mykey});} - bool shmem_attach () {return shmem.attach();} - int shmem_size () {return static_cast<int> (shmem.size());} - struct jt9com * shmem_address () {return reinterpret_cast<struct jt9com *>(shmem.data());} - bool shmem_detach () {return shmem.detach();} + bool shmem_lock_worker (char const * path) noexcept + { + try + { + worker_lock.reset (new DecoderWorkerLock {path}); + if (worker_lock->tryLock ()) return true; + std::fprintf (stderr, "Decoder worker lock: %s\n", worker_lock->errorString ().c_str ()); + } + catch (...) + { + std::fputs ("Decoder worker lock: initialization failed\n", stderr); + } + return false; + } + + bool shmem_attach (char const * name) noexcept + { + try + { + if (shmem.attach (name)) return true; + std::fprintf (stderr, "Decoder shared memory: %s\n", shmem.errorString ().c_str ()); + } + catch (std::exception const& error) + { + std::fprintf (stderr, "Decoder shared memory: %s\n", error.what ()); + } + catch (...) + { + std::fputs ("Decoder shared memory: unexpected attachment failure\n", stderr); + } + return false; + } + std::size_t shmem_size () noexcept {return shmem.size ();} + void * shmem_address () noexcept {return shmem.data ();} } diff --git a/lib/shmem.f90 b/lib/shmem.f90 index 853f67e9..058916bc 100644 --- a/lib/shmem.f90 +++ b/lib/shmem.f90 @@ -1,19 +1,8 @@ module shmem - ! external routines wrapping the Qt QSharedMemory class interface - function shmem_create (size) bind(C, name="shmem_create") - use iso_c_binding, only: c_bool, c_int - logical(c_bool) :: shmem_create - integer(c_int), value, intent(in) :: size - end function shmem_create - - subroutine shmem_setkey (key) bind(C, name="shmem_setkey") + function shmem_attach (key) bind(C, name="shmem_attach") use iso_c_binding, only: c_bool, c_char character(kind=c_char), intent(in) :: key(*) - end subroutine shmem_setkey - - function shmem_attach () bind(C, name="shmem_attach") - use iso_c_binding, only: c_bool logical(c_bool) :: shmem_attach end function shmem_attach @@ -23,13 +12,14 @@ module shmem end function shmem_address function shmem_size() bind(C, name="shmem_size") - use, intrinsic :: iso_c_binding, only: c_int - integer(c_int) :: shmem_size + use, intrinsic :: iso_c_binding, only: c_size_t + integer(c_size_t) :: shmem_size end function shmem_size - function shmem_detach () bind(C, name="shmem_detach") - use iso_c_binding, only: c_bool - logical(c_bool) :: shmem_detach - end function shmem_detach + function shmem_lock_worker (path) bind(C, name="shmem_lock_worker") + use iso_c_binding, only: c_bool, c_char + character(kind=c_char), intent(in) :: path(*) + logical(c_bool) :: shmem_lock_worker + end function shmem_lock_worker end interface end module shmem diff --git a/lib/softsym.f90 b/lib/softsym.f90 index 4b7f9bc2..c7de27bf 100644 --- a/lib/softsym.f90 +++ b/lib/softsym.f90 @@ -1,12 +1,21 @@ -subroutine softsym(id2,npts8,nsps8,newdat,fpk,syncpk,snrdb,xdt, & +module jt9_soft_symbols + use jt9_downsample, only: jt9_downsample_workspace, downsam9 + implicit none + private + public :: softsym +contains + +subroutine softsym(workspace,id2,npts8,nsps8,fpk,syncpk,snrdb,xdt, & freq,drift,a3,schk,i1SoftSymbols) ! Compute the soft symbols use timer_module, only: timer + implicit real(a-h,o-z), integer(i-n) parameter (NZ2=1512,NZ3=1360) - logical, intent(inout) :: newdat + type(jt9_downsample_workspace), intent(inout) :: workspace + integer*2, intent(in) :: id2(*) complex c2(0:NZ2-1) complex c3(0:NZ3-1) complex c5(0:NZ3-1) @@ -20,8 +29,19 @@ subroutine softsym(id2,npts8,nsps8,newdat,fpk,syncpk,snrdb,xdt, & ! Mix, low-pass filter, and downsample to 16 samples per symbol call timer('downsam9',0) - call downsam9(id2,npts8,nsps8,newdat,nspsd,fpk,c2) + call downsam9(workspace,id2,npts8,fpk,c2) call timer('downsam9',1) + if(all(c2.eq.(0.,0.))) then + syncpk=-1. + snrdb=-99. + xdt=0. + freq=fpk + drift=0. + a3=0. + schk=0. + i1SoftSymbols=0 + return + endif call peakdt9(c2,nsps8,nspsd,c3,xdt) !Find DT @@ -52,3 +72,5 @@ subroutine softsym(id2,npts8,nsps8,newdat,fpk,syncpk,snrdb,xdt, & return end subroutine softsym + +end module jt9_soft_symbols diff --git a/lib/softsym9w.f90 b/lib/softsym9w.f90 index c9b1d0a8..f83dd940 100644 --- a/lib/softsym9w.f90 +++ b/lib/softsym9w.f90 @@ -1,4 +1,4 @@ -subroutine softsym9w(id2,npts,xdt0,f0,width,nsubmode,xdt1,snrdb,i1softsymbols) +subroutine softsym9w(id2,npts,xdt0,f0,width,nsubmode,xdt1,snrdb,i1softsymbols,valid) parameter (NFFT=6912,NH=NFFT/2,NQ=NH/2) real s(NQ) @@ -9,18 +9,23 @@ subroutine softsym9w(id2,npts,xdt0,f0,width,nsubmode,xdt1,snrdb,i1softsymbols) integer*2 id2(60*12000) integer*1 i1SoftSymbolsScrambled(207) integer*1 i1softsymbols(207) + logical, intent(out) :: valid include 'jt9sync.f90' equivalence (x,cx) if(npts.eq.-99) stop !Silence compiler warning + valid=.false. + xdt1=0. + snrdb=-99. + i1softsymbols=0 df=12000.0/NFFT i0a=max(1.0,(xdt0-1.0)*12000.0) i0b=(xdt0+1.0)*12000.0 k1=max(1,nint((f0-0.5*width)/df)) k2=min(NQ,nint((f0+0.5*width)/df)) + if(k1.gt.k2) return smax=0. - i0pk=1 - i1softsymbols=0 + i0pk=0 do i0=i0a,i0b,432 s=0. @@ -42,10 +47,9 @@ subroutine softsym9w(id2,npts,xdt0,f0,width,nsubmode,xdt1,snrdb,i1softsymbols) if(ssum.lt.0.7*smax) exit endif end do + if(i0pk.le.0) return xdt1=(i0pk-1)/12000.0 - if(i0pk.le.0) go to 999 - m=0 do j=1,85 ia=i0pk + (j-1)*nfft @@ -86,6 +90,7 @@ subroutine softsym9w(id2,npts,xdt0,f0,width,nsubmode,xdt1,snrdb,i1softsymbols) enddo ave=ss/(69*7) !Baseline call pctile(s2,9*85,35,xmed) + if(ave.le.0. .or. xmed.le.0.) return s3=s3/ave sig=sig/69. !Signal snrdb=db(sig/xmed) - 28.0 @@ -121,5 +126,6 @@ subroutine softsym9w(id2,npts,xdt0,f0,width,nsubmode,xdt1,snrdb,i1softsymbols) ! Remove interleaving call interleave9(i1SoftSymbolsScrambled,-1,i1SoftSymbols) -999 return + valid=.true. + return end subroutine softsym9w diff --git a/lib/spec64.f90 b/lib/spec64.f90 index 1fd732bb..cedc10fa 100644 --- a/lib/spec64.f90 +++ b/lib/spec64.f90 @@ -1,6 +1,8 @@ -subroutine spec64(c0,cs,npts,nsps,mode_q65,jpk,s3,LL,NN) +subroutine spec64(c0,cs,npts,nsps,mode_q65,jpk,s3,LL,NN,plan) use q65_workspace, only: Q65_MAXFFT + use iso_c_binding, only: c_int64_t + integer(c_int64_t), intent(in) :: plan complex c0(0:npts-1) !Complex spectrum of dd() complex cs(0:Q65_MAXFFT-1) !Complex symbol spectrum @@ -28,7 +30,7 @@ subroutine spec64(c0,cs,npts,nsps,mode_q65,jpk,s3,LL,NN) cs(0:nz)=c0(ja:jb) ! if(nz.lt.nfft-1) cs(nz+1:)=0. if(nz.lt.nfft-1 .and. nz.ge.0) cs(nz+1:)=0. !Avoid a potential bounds error with Q65-15 EME - call four2a(cs,nsps,1,-1,1) !c2c FFT to frequency + call sfftw_execute(plan) do ii=1,LL i=ii-65+mode_q65 !mode_q65 = 1 2 4 8 16 for Q65 A B C D E if(i.lt.0) i=i+nsps diff --git a/lib/streaming_apply.f90 b/lib/streaming_apply.f90 index 72feda74..0a507481 100644 --- a/lib/streaming_apply.f90 +++ b/lib/streaming_apply.f90 @@ -281,7 +281,16 @@ contains ! Per-period UTC. Producer sends a fresh nutc in each ! period's configure frame so streaming_emit_decode can format the time ! field correctly (instead of "000000"). - if (in_cfg%nutc_set) params%nutc = in_cfg%nutc + if (in_cfg%nutc_set) then + params%nutc = in_cfg%nutc + ! Long-period FST4 numeric UTC also accepts legacy HHMM; ISO UTC is always HHMMSS. + if ((io_mode.eq.240.or.io_mode.eq.241.or.io_mode.eq.242).and.io_TRperiod.ge.60.and. & + params%nutc.le.2359) & + params%nutc=100*params%nutc + ! Legacy numeric Q65 times may be HHMM. + if (io_mode.eq.66.and.io_TRperiod.ge.60.and.params%nutc.le.2359) & + params%nutc=100*params%nutc + endif ! Phase 8 (RFC v1 §6.3/§4.1): utc (ISO "HH:MM:SS") is a SECOND route to nutc, ! kept alongside the legacy int nutc above. Applied AFTER nutc so utc WINS when ! a frame carries both (the richer ISO form). The apply order encodes the diff --git a/lib/streaming_emit.f90 b/lib/streaming_emit.f90 index fc86246a..b3346926 100644 --- a/lib/streaming_emit.f90 +++ b/lib/streaming_emit.f90 @@ -13,8 +13,6 @@ ! error (version) {"v":1,"t":"error","code":"unknown_schema_version","got":N} ! error (type) {"v":1,"t":"error","code":"configure_type_error", ! "key":"depth","expected":"int","got":"string"} -! warning {"v":1,"t":"warning","code":"period_boundary_discard", -! "discarded_samples":N} ! ! Activation: program jt9 calls streaming_emit_set_enabled(.true.) when ! --stream is parsed. Decoder per-mode sites in lib/decoder.f90 query @@ -38,7 +36,6 @@ module streaming_emit public :: streaming_emit_error_code public :: streaming_emit_error_version public :: streaming_emit_error_type - public :: streaming_emit_warning_samples contains @@ -70,13 +67,14 @@ contains ! dt : DT seconds (float) ! freq : decode frequency offset in Hz (integer) ! msg : decoded message text (gets JSON-escaped + trimmed) - subroutine streaming_emit_decode(mode_str, nutc, snr, dt, freq, msg) + subroutine streaming_emit_decode(mode_str, nutc, snr, dt, freq, msg, utc_is_hhmmss) character(len=*), intent(in) :: mode_str integer, intent(in) :: nutc integer, intent(in) :: snr real, intent(in) :: dt integer, intent(in) :: freq character(len=*), intent(in) :: msg + logical, optional, intent(in) :: utc_is_hhmmss character(len=8) :: time_str character(len=320) :: msg_escaped @@ -85,7 +83,7 @@ contains if (.not. enabled_) return - call format_utc_(nutc, time_str) + call format_utc_(nutc, time_str, utc_is_hhmmss) call json_escape_(msg, msg_escaped, msg_len) call format_dt_(dt, dt_str) @@ -100,11 +98,12 @@ contains flush(output_unit) end subroutine streaming_emit_decode - subroutine streaming_emit_decode_finished(nutc) + subroutine streaming_emit_decode_finished(nutc, utc_is_hhmmss) integer, intent(in) :: nutc + logical, optional, intent(in) :: utc_is_hhmmss character(len=8) :: time_str if (.not. enabled_) return - call format_utc_(nutc, time_str) + call format_utc_(nutc, time_str, utc_is_hhmmss) write(output_unit, '(3a)') & '{"v":1,"t":"decode_finished","period_end":"', trim(time_str), & '"}' @@ -166,16 +165,6 @@ contains flush(output_unit) end subroutine streaming_emit_error_type - subroutine streaming_emit_warning_samples(code, discarded_samples) - character(len=*), intent(in) :: code - integer(int64), intent(in) :: discarded_samples - if (.not. enabled_) return - write(output_unit, '(3a,i0,a)') & - '{"v":1,"t":"warning","code":"', trim(code), & - '","discarded_samples":', discarded_samples, '}' - flush(output_unit) - end subroutine streaming_emit_warning_samples - ! Internals ------------------------------------------------------------- ! Format dt (real seconds) as a JSON-safe number. gfortran's f0.x format @@ -198,12 +187,16 @@ contains ! Format the integer nutc time as 6 chars. 4-digit HHMM gets ! zero-extended to HHMM00 so consumers always see a 6-char field. - subroutine format_utc_(nutc, str) + subroutine format_utc_(nutc, str, utc_is_hhmmss) integer, intent(in) :: nutc character(len=*), intent(out) :: str + logical, optional, intent(in) :: utc_is_hhmmss integer :: hh, mm, ss + logical :: full_time + full_time=.false. + if(present(utc_is_hhmmss)) full_time=utc_is_hhmmss str = '000000' - if (nutc .ge. 100000) then + if (full_time.or.nutc.ge.100000) then hh = nutc / 10000 mm = mod(nutc/100, 100) ss = mod(nutc, 100) diff --git a/lib/streaming_io.f90 b/lib/streaming_io.f90 index 98c9a13e..a2c9fa28 100644 --- a/lib/streaming_io.f90 +++ b/lib/streaming_io.f90 @@ -18,19 +18,16 @@ ! See lib/streaming_control.f90 for the parser + schema. ! ! Apply policy: -! configure : applied immediately at receive. If mode changes, the -! in-flight sample accumulator is discarded (k=0) — the -! buffered audio is wrong-format for the new mode anyway. -! Producers should send `configure` FIRST, before any -! audio frames; subsequent audio is interpreted under the -! most recent configure. -! halt : drain current period (call decoder if k>0), exit clean. +! configure : applied at receive. A change of mode or period starts a +! new period; what was in flight is discarded. Producers +! send `configure` first; audio is interpreted under the +! most recent one. +! halt : drain the current period (decode if it has samples), exit. ! -! Period boundary: when k accumulates to `npts` samples (mode-dependent), -! we run the decoder. Audio frames that overflow `npts` have the excess -! discarded — producers should chunk audio so that any single frame fits -! within one period, OR send exactly `npts` samples per period. An -! external producer should honor this. +! A period is TRperiod * 12 kHz samples (lib/streaming_period.f90). Keep a +! frame remainder for the next period; retain only the first npts samples +! for decoding. The reader's phase is that of the first audio after +! `configure`; send every sample. ! ! Format support: fmt=0x00 (int16 PCM) only. Other formats may be ! added later. @@ -55,10 +52,12 @@ subroutine jt9_stream(shared_data, mode, TRperiod) use streaming_emit, only: streaming_emit_ready, & streaming_emit_decode_finished, streaming_emit_error, & streaming_emit_error_code, streaming_emit_error_version, & - streaming_emit_error_type, streaming_emit_warning_samples + streaming_emit_error_type use streaming_control, only: parse_control_frame, configure_fields, & control_type_error, CTRL_CONFIGURE, CTRL_HALT, CTRL_PARSE_ERR use streaming_apply, only: apply_configure_fields + use streaming_period, only: period_state, period_begin, period_room, & + period_take, period_full, period_ready include 'jt9com.f90' @@ -81,12 +80,16 @@ subroutine jt9_stream(shared_data, mode, TRperiod) integer(int64) :: frame_len_wide, max_audio_frame_bytes integer :: frame_len - integer :: nsps, kstep, npts, k, nhsym, nhsym0 + integer :: nsps, kstep, nhsym, nhsym0 + ! The period's sample accounting; `body_left` carries a straddling + ! frame's remainder into the next period. + type(period_state) :: period + ! This period's decode has run. + logical :: decoded integer :: ingain, nminw, ihsym, npts8 real :: pxdb, df3, pxdbmax, s(NSMAX) integer :: npct_unused integer :: body_left, take_bytes, take_samples - integer(int64) :: discarded_samples integer(int16) :: chunk(4096) integer(int8) :: byte_sink(4096) ! FT8 progressive-decode working buffer (mirrors jt9.f90:19's id2a) — the @@ -97,6 +100,7 @@ subroutine jt9_stream(shared_data, mode, TRperiod) character(len=CTL_BUF_LEN) :: ctl_buf integer(int8) :: ctl_bytes(CTL_BUF_LEN) integer :: i_ctl, prev_mode + real(8) :: prev_TRperiod ! Session-baseline nfa/nfb stashed after jt9.f90's init_streaming_extra_fields ! returned. apply_configure_fields restores these on mode change with no ! explicit consumer override; passed in as dummy args. @@ -195,25 +199,27 @@ subroutine jt9_stream(shared_data, mode, TRperiod) call streaming_emit_ready() max_audio_frame_bytes = 2_int64 * int(size(shared_data%id2), int64) + body_left = 0 ! ===== Outer period loop =========================================== do - ! Compute per-period sample target. (Same multi-mode logic.) - npts = int(TRperiod * NFSAMPLE) - if (mode .eq. 5) npts = 21 * 3456 - if (npts > size(shared_data%id2)) npts = size(shared_data%id2) - if (npts < 1) npts = NFSAMPLE - if (mode .eq. 8 .and. npts .gt. 50 * 3456) npts = 50 * 3456 - + call period_begin(period, TRperiod, mode, size(shared_data%id2)) shared_data%id2 = 0 - k = 0 nhsym = 0 nhsym0 = 0 ! seed at 0 so the symspec catch-up loop is O(nhsym) eof_period = .false. halt_req = .false. + decoded = .false. + + ! The previous period ended inside an audio frame: its remainder is + ! this period's first audio. + if (body_left .gt. 0) then + call consume_audio_body() + if (.not. decoded .and. period_ready(period)) call run_period_decode() + end if - ! Inner frame loop: read frames until period full, halt, or EOF. - do while (k .lt. npts .and. .not. halt_req .and. .not. eof_period) + ! Inner frame loop: read frames until the period is full, halt, or EOF. + do while (.not. period_full(period) .and. .not. halt_req .and. .not. eof_period) call stdin_read(type_byte, 1, ios) if (ios /= 0) then eof_period = .true.; exit @@ -250,51 +256,9 @@ subroutine jt9_stream(shared_data, mode, TRperiod) end do cycle end if - discarded_samples = max(0_int64, frame_len_wide / 2_int64 & - - int(npts - k, int64)) - if (discarded_samples .gt. 0_int64) then - call streaming_emit_warning_samples('period_boundary_discard', & - discarded_samples) - end if body_left = frame_len - do while (body_left .gt. 0) - if (k .lt. npts) then - take_bytes = min(body_left, 2 * size(chunk)) - take_samples = take_bytes / 2 - call stdin_read(chunk, 2*take_samples, ios) - if (ios /= 0) then - eof_period = .true.; exit - end if - if (k + take_samples .gt. npts) take_samples = npts - k - shared_data%id2(k+1 : k+take_samples) = & - chunk(1:take_samples) - k = k + take_samples - body_left = body_left - take_bytes - ! Incremental symspec for JT9-family at kstep boundaries. - ! Cap at nhsym=181 to match the WAV-path exit condition - ! (jt9.f90:442-443) — exceeding it overruns ss(184,*). - do while ((k - 2048) / kstep .gt. nhsym0 .and. nhsym0 .lt. 181) - nhsym0 = nhsym0 + 1 - if (nhsym0 .lt. 1) cycle - nhsym = nhsym0 - if (mode .eq. 9 .or. mode .eq. 74) then - call timer('symspec ', 0) - call symspec(shared_data, nhsym*kstep + 2048, nsps, & - ingain, bLowSidelobes, nminw, pxdb, s, df3, & - ihsym, npts8, pxdbmax, npct_unused) - call timer('symspec ', 1) - end if - end do - else - ! Period full: drain the rest of this audio frame. - take_bytes = min(body_left, size(byte_sink)) - call stdin_read(byte_sink, take_bytes, ios) - if (ios /= 0) then - eof_period = .true.; exit - end if - body_left = body_left - take_bytes - end if - end do + call consume_audio_body() + if (.not. decoded .and. period_ready(period)) call run_period_decode() else if (iand(int(type_byte(1)), 255) .eq. FRAME_CONTROL) then ! Read JSON body into char buffer (cap at CTL_BUF_LEN) @@ -359,28 +323,19 @@ subroutine jt9_stream(shared_data, mode, TRperiod) 'trperiod must be finite and between 0 and 1800 seconds') cycle end if - prev_mode = mode + prev_mode = mode + prev_TRperiod = TRperiod call apply_configure_fields(cfg, mode, TRperiod, & shared_data%params, baseline_nfa, baseline_nfb) - ! Mode changed: in-flight samples are wrong format. Discard - ! and recompute npts. Producer should configure FIRST so - ! this branch is rare/diagnostic. - if (cfg%mode_set .and. mode .ne. prev_mode) then - npts = int(TRperiod * NFSAMPLE) - if (mode .eq. 5) npts = 21 * 3456 - if (npts .gt. size(shared_data%id2)) npts = size(shared_data%id2) - if (npts .lt. 1) npts = NFSAMPLE - if (mode .eq. 8 .and. npts .gt. 50 * 3456) npts = 50 * 3456 + ! A configure that changes the applied mode or period starts a + ! new period; what was in flight is discarded. Repeating the + ! current configuration leaves the period alone. + if (mode .ne. prev_mode .or. TRperiod .ne. prev_TRperiod) then + call period_begin(period, TRperiod, mode, size(shared_data%id2)) shared_data%id2 = 0 - k = 0 nhsym = 0 nhsym0 = 0 - else if (cfg%trperiod_set) then - ! TRperiod-only change: recompute npts but keep accumulated samples. - npts = int(TRperiod * NFSAMPLE) - if (mode .eq. 5) npts = 21 * 3456 - if (mode .eq. 8 .and. npts .gt. 50 * 3456) npts = 50 * 3456 - if (npts .gt. size(shared_data%id2)) npts = size(shared_data%id2) + decoded = .false. end if case (CTRL_PARSE_ERR) call streaming_emit_error_code('configure_parse_error', & @@ -401,55 +356,99 @@ subroutine jt9_stream(shared_data, mode, TRperiod) end if end do - ! Run decoder if we accumulated any samples this period. - if (k .gt. 0) then - shared_data%params%newdat = .true. - shared_data%params%nzhsym = nhsym - ! FT8 override: decoder is tuned for nzhsym=50 (cf. jt9.f90:552). - if (mode .eq. 8) shared_data%params%nzhsym = 50 - ! Non-FT8/FST4/Q65: cap at 181 to match WAV-path exit (ss array bound). - if (mode .ne. 8 .and. mode .ne. 240 .and. mode .ne. 241 .and. & - mode .ne. 242 .and. mode .ne. 66 .and. shared_data%params%nzhsym .gt. 181) then - shared_data%params%nzhsym = 181 - end if - shared_data%params%kin = 64800 - if (mode .eq. 240) shared_data%params%kin = 720000 - if (mode .eq. 241) shared_data%params%kin = 720000 - if (mode .eq. 242) shared_data%params%kin = 720000 - - if (mode .eq. 144) then - call decode_msk144(shared_data%id2, shared_data%params, data_dir) - else if (mode .eq. 8 .and. .not. shared_data%params%lmultift8) then - ! FT8 progressive 41/47/50 sequence (mirrors jt9.f90:562-581). - ! Without the early calls, ft8_decode.f90's saved `dd` array stays - ! unset and the final nzhsym=50 call decodes silence. With the - ! sequence, dd is populated on the nzhsym=41/47 passes and the - ! nzhsym=50 final pass produces real decodes. - shared_data%params%nzhsym = 41 - id2a(1:41*3456) = shared_data%id2(1:41*3456) - id2a(41*3456+1:) = 0 - call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE) - - shared_data%params%nzhsym = 47 - id2a(1:47*3456) = shared_data%id2(1:47*3456) - id2a(47*3456+1:) = 0 - call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE) - - shared_data%params%nzhsym = 50 - id2a(1:50*3456) = shared_data%id2(1:50*3456) - id2a(50*3456+1:) = 0 - call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE) - else - call multimode_decoder(shared_data%ss, shared_data%id2, & - shared_data%params, NFSAMPLE) - end if - end if + ! A period cut short (halt, or the producer closed the pipe) still + ! decodes what it has — once. + if (.not. decoded .and. period%k .gt. 0) call run_period_decode() if (halt_req .or. eof_period) return end do contains + ! This period's decode, on the `npts` samples in `id2`. Runs once per + ! period: when the decoder's share is in, or from the drain when the + ! period ends short of it. + subroutine run_period_decode() + decoded = .true. + shared_data%params%newdat = .true. + shared_data%params%ntr = int(TRperiod) + shared_data%params%nzhsym = nhsym + ! FT8 override: decoder is tuned for nzhsym=50 (cf. jt9.f90:552). + if (mode .eq. 8) shared_data%params%nzhsym = 50 + ! Non-FT8/FST4/Q65: cap at 181 to match WAV-path exit (ss array bound). + if (mode .ne. 8 .and. mode .ne. 240 .and. mode .ne. 241 .and. & + mode .ne. 242 .and. mode .ne. 66 .and. shared_data%params%nzhsym .gt. 181) then + shared_data%params%nzhsym = 181 + end if + shared_data%params%kin = 64800 + if (mode .eq. 5 .or. mode .eq. 9 .or. mode .eq. 65 .or. mode .eq. 66 .or. & + mode .eq. 240 .or. mode .eq. 241 .or. mode .eq. 242) & + shared_data%params%kin = period%k + + if (mode .eq. 144) then + call decode_msk144(shared_data%id2, shared_data%params, data_dir) + else if (mode .eq. 8 .and. .not. shared_data%params%lmultift8) then + ! FT8 progressive 41/47/50 sequence (mirrors jt9.f90:562-581). + ! Without the early calls, ft8_decode.f90's saved `dd` array stays + ! unset and the final nzhsym=50 call decodes silence. With the + ! sequence, dd is populated on the nzhsym=41/47 passes and the + ! nzhsym=50 final pass produces real decodes. + shared_data%params%nzhsym = 41 + id2a(1:41*3456) = shared_data%id2(1:41*3456) + id2a(41*3456+1:) = 0 + call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE) + + shared_data%params%nzhsym = 47 + id2a(1:47*3456) = shared_data%id2(1:47*3456) + id2a(47*3456+1:) = 0 + call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE) + + shared_data%params%nzhsym = 50 + id2a(1:50*3456) = shared_data%id2(1:50*3456) + id2a(50*3456+1:) = 0 + call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE) + else + call multimode_decoder(shared_data%ss, shared_data%id2, & + shared_data%params, NFSAMPLE) + end if + if(mode==66) shared_data%params%nclearave=.false. + end subroutine run_period_decode + + ! Stop at the period boundary; body_left carries the remaining frame + ! forward. + subroutine consume_audio_body() + integer :: k0, nacc + do while (body_left .gt. 0 .and. .not. period_full(period)) + take_samples = period_room(period, min(body_left / 2, size(chunk))) + take_bytes = 2 * take_samples + call stdin_read(chunk, take_bytes, ios) + if (ios /= 0) then + eof_period = .true.; return + end if + body_left = body_left - take_bytes + k0 = period%k + call period_take(period, take_samples, nacc) + if (nacc .gt. 0) then + shared_data%id2(k0+1 : k0+nacc) = chunk(1:nacc) + ! Incremental symspec for JT9-family at kstep boundaries. + ! Cap at nhsym=181 to match the WAV-path exit condition + ! (jt9.f90:442-443) — exceeding it overruns ss(184,*). + do while ((period%k - 2048) / kstep .gt. nhsym0 .and. nhsym0 .lt. 181) + nhsym0 = nhsym0 + 1 + if (nhsym0 .lt. 1) cycle + nhsym = nhsym0 + if (mode .eq. 74) then + call timer('symspec ', 0) + call symspec(shared_data, nhsym*kstep + 2048, nsps, & + ingain, bLowSidelobes, nminw, pxdb, s, df3, & + ihsym, npts8, pxdbmax, npct_unused) + call timer('symspec ', 1) + end if + end do + end if + end do + end subroutine consume_audio_body + ! Read exactly nbytes from stdin via the C helper; ios=0 on success, ! ios=1 on end-of-stream (short delivery — the producer closed the ! pipe). Every caller treats nonzero ios as end-of-stream, matching diff --git a/lib/streaming_period.f90 b/lib/streaming_period.f90 new file mode 100644 index 00000000..7036eeeb --- /dev/null +++ b/lib/streaming_period.f90 @@ -0,0 +1,70 @@ +! Period bookkeeping for the streaming reader. A period is TRperiod * 12 kHz +! samples; the decoder takes the first npts of them; a frame that straddles +! the boundary carries its remainder into the next period. +module streaming_period + implicit none + private + public :: period_state, period_begin, period_room, period_take, & + period_full, period_ready + + integer, parameter, public :: PERIOD_NFSAMPLE = 12000 + + type period_state + integer :: nperiod = 0 ! samples in the period + integer :: npts = 0 ! of them, the samples the decoder takes + integer :: kperiod = 0 ! consumed so far this period + integer :: k = 0 ! handed to the decoder so far + end type period_state + +contains + + ! Begin a period of trperiod seconds in jt9 mode number `mode`, with a + ! decoder buffer of nmax samples. The decoder's share is mode-dependent + ! (21*3456 for FT4, at most 50*3456 for FT8); the period is never shorter + ! than that share. + subroutine period_begin(st, trperiod, mode, nmax) + type(period_state), intent(out) :: st + real(8), intent(in) :: trperiod + integer, intent(in) :: mode, nmax + st%npts = int(trperiod * PERIOD_NFSAMPLE) + if (mode .eq. 5) st%npts = 21 * 3456 + if (mode .eq. 8 .and. st%npts .gt. 50 * 3456) st%npts = 50 * 3456 + if (st%npts .gt. nmax) st%npts = nmax + if (st%npts .lt. 1) st%npts = PERIOD_NFSAMPLE + st%nperiod = max(int(trperiod * PERIOD_NFSAMPLE), st%npts) + st%kperiod = 0 + st%k = 0 + end subroutine period_begin + + ! Of navail samples on offer, how many the period takes — never past its + ! end, so what is left of a straddling frame is the next period's. + pure integer function period_room(st, navail) + type(period_state), intent(in) :: st + integer, intent(in) :: navail + period_room = max(0, min(navail, st%nperiod - st%kperiod)) + end function period_room + + ! Account for ntake samples consumed into the period; the first nacc of + ! them are the decoder's. + subroutine period_take(st, ntake, nacc) + type(period_state), intent(inout) :: st + integer, intent(in) :: ntake + integer, intent(out) :: nacc + nacc = max(0, min(ntake, st%npts - st%k)) + st%kperiod = st%kperiod + ntake + st%k = st%k + nacc + end subroutine period_take + + ! Every sample of the period is in. + pure logical function period_full(st) + type(period_state), intent(in) :: st + period_full = st%kperiod .ge. st%nperiod + end function period_full + + ! The decoder's samples are in. + pure logical function period_ready(st) + type(period_state), intent(in) :: st + period_ready = st%k .ge. st%npts + end function period_ready + +end module streaming_period diff --git a/lib/subtract65.f90 b/lib/subtract65.f90 index 7469472c..507b7a0f 100644 --- a/lib/subtract65.f90 +++ b/lib/subtract65.f90 @@ -8,16 +8,17 @@ subroutine subtract65(dd,npts,f0,dt) ! Subtract : dd(t) = dd(t) - 2*REAL{cref*cfilt} use packjt + use jt65_mod, only: jt65_work,ensure_jt65_workspace + use FFTW3 + use, intrinsic :: iso_c_binding use timer_module, only: timer integer correct(63) parameter (NMAX=60*12000) !Samples per 60 s parameter (NFILT=1600) real*4 dd(NMAX), window(-NFILT/2:NFILT/2) - complex cref,camp,cfilt,cw integer nprc(126) real*8 dphi,phi - logical first data nprc/ & 1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & @@ -26,10 +27,14 @@ subroutine subtract65(dd,npts,f0,dt) 1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1, & 0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1, & 1,1,1,1,1,1/ - data first/.true./ common/chansyms65/correct - common/heap1/cref(NMAX),camp(NMAX),cfilt(NMAX),cw(NMAX) - save first + common/patience/npatience,nthreads + + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%cref)) then + allocate(jt65_work%cref(NMAX),jt65_work%camp(NMAX),jt65_work%cfilt(NMAX),jt65_work%cw(NMAX)) + endif + associate(cref=>jt65_work%cref,camp=>jt65_work%camp,cfilt=>jt65_work%cfilt,cw=>jt65_work%cw) pi=4.0*atan(1.0) @@ -44,6 +49,7 @@ subroutine subtract65(dd,npts,f0,dt) nsym=126 ns=4458 nref=nsym*ns + camp(1:nref)=0. nend=nstart+nref-1 phi=0.0 iref=1 @@ -74,7 +80,25 @@ subroutine subtract65(dd,npts,f0,dt) nfft=564480 - if(first) then + if(.not.c_associated(jt65_work%subtract_forward).or. & + jt65_work%sub_patience/=npatience.or.jt65_work%sub_threads/=nthreads) then + nflags=FFTW_ESTIMATE + if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT + if(npatience.eq.2) nflags=FFTW_MEASURE + if(npatience.eq.3) nflags=FFTW_PATIENT + if(npatience.eq.4) nflags=FFTW_EXHAUSTIVE + !$omp critical(fftw) + if(c_associated(jt65_work%subtract_forward)) call fftwf_destroy_plan(jt65_work%subtract_forward) + if(c_associated(jt65_work%subtract_inverse)) call fftwf_destroy_plan(jt65_work%subtract_inverse) + if(c_associated(jt65_work%window_plan)) call fftwf_destroy_plan(jt65_work%window_plan) + call fftwf_plan_with_nthreads(nthreads) + jt65_work%subtract_forward=fftwf_plan_dft_1d(nfft,cfilt,cfilt,-1,nflags) + jt65_work%subtract_inverse=fftwf_plan_dft_1d(nfft,cfilt,cfilt,1,nflags) + jt65_work%window_plan=fftwf_plan_dft_1d(nfft,cw,cw,-1,nflags) + call fftwf_plan_with_nthreads(1) + !$omp end critical(fftw) + jt65_work%sub_patience=npatience + jt65_work%sub_threads=nthreads ! Create and normalize the filter sum=0.0 do j=-NFILT/2,NFILT/2 @@ -87,17 +111,16 @@ subroutine subtract65(dd,npts,f0,dt) if(j.lt.1) j=j+nfft cw(j)=window(i)/sum enddo - call four2a(cw,nfft,1,-1,1) - first=.false. + call fftwf_execute_dft(jt65_work%window_plan,cw,cw) endif nz=561708 cfilt(1:nz)=camp(1:nz) cfilt(nz+1:nfft)=0. - call four2a(cfilt,nfft,1,-1,1) + call fftwf_execute_dft(jt65_work%subtract_forward,cfilt,cfilt) fac=1.0/float(nfft) cfilt(1:nfft)=fac*cfilt(1:nfft)*cw(1:nfft) - call four2a(cfilt,nfft,1,1,1) + call fftwf_execute_dft(jt65_work%subtract_inverse,cfilt,cfilt) call timer('subtr_2 ',1) ! Subtract the reconstructed signal @@ -108,5 +131,6 @@ subroutine subtract65(dd,npts,f0,dt) enddo call timer('subtr_3 ',1) + end associate return end subroutine subtract65 diff --git a/lib/superfox/qpc_sync.f90 b/lib/superfox/qpc_sync.f90 index 9c80b390..d24b7be1 100644 --- a/lib/superfox/qpc_sync.f90 +++ b/lib/superfox/qpc_sync.f90 @@ -2,15 +2,17 @@ subroutine qpc_sync(crcvd0,fsample,isync,fsync,ftol,f2,t2,snrsync) parameter(N9SEC=9*12000,NMAX=15*12000,NDOWN=16,NZ=N9SEC/NDOWN) complex crcvd0(NMAX) !Signal as received - complex c0(0:N9SEC-1) !For long FFT + complex, allocatable :: c0(:) !For long FFT complex c1(0:NZ-1) complex c1sum(0:NZ-1) complex z - real s(N9SEC/4) + real, allocatable :: s(:) real p(-1125:1125) integer ipk(1) integer isync(24) + allocate(c0(0:N9SEC-1),s(N9SEC/4)) + baud=12000.0/1024.0 df2=fsample/N9SEC fac=1.0/N9SEC diff --git a/lib/superfox/sfox_gen_gfsk.f90 b/lib/superfox/sfox_gen_gfsk.f90 index 3f682b9a..bd3d8c4c 100644 --- a/lib/superfox/sfox_gen_gfsk.f90 +++ b/lib/superfox/sfox_gen_gfsk.f90 @@ -13,12 +13,14 @@ subroutine sfox_gen_gfsk(idat,f0,isync,itone,cdat) integer isync(NS) integer itone(NDS) real*8 dt,twopi,phi,dphi_peak - real*8 dphi(0:NPTS-1) + real*8, allocatable :: dphi(:) real pulse(3*NSPS) logical first/.true./ save first,twopi,dt,hmod,dphi_peak,pulse + allocate(dphi(0:NPTS-1)) + if(first) then twopi=8.d0*atan(1.0) fsample=12000.0 diff --git a/lib/superfox/sfox_pack.f90 b/lib/superfox/sfox_pack.f90 index 1a482422..0b9a6457 100644 --- a/lib/superfox/sfox_pack.f90 +++ b/lib/superfox/sfox_pack.f90 @@ -1,8 +1,16 @@ -subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) +module sfox_pack_module + implicit none + private + public :: sfox_pack_for_state +contains +subroutine sfox_pack_for_state(knowledge,line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) use qpc_mod use packjt use packjt77 + implicit real(a-h,o-z) + implicit integer(i-n) + type(pack77_state), intent(inout) :: knowledge parameter (NQU1RKS=203514677) integer*8 n47,n58 integer*1 xin(0:49) !Packed message as 7-bit symbols @@ -86,7 +94,7 @@ subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) pack_error=SFOX_PACK_BAD_CALL return endif - call pack28(w1,n28) !Fox call + call pack28_for_state(knowledge,w1,n28) !Fox call write(msgbits(1:28),'(b28.28)') n28 nrr73_total=0 @@ -141,7 +149,7 @@ subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) pack_error=SFOX_PACK_BAD_CALL return endif - call pack28(w(i),n28) + call pack28_for_state(knowledge,w(i),n28) write(msgbits(j:j+27),1002) n28 !Insert this call for RR73 message 1002 format(b28.28) j=j+28 @@ -165,7 +173,7 @@ subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) pack_error=SFOX_PACK_BAD_CALL return endif - call pack28(w(i),n28) + call pack28_for_state(knowledge,w(i),n28) write(msgbits(j:j+27),1002) n28 !Insert this call if(.not.valid_sfox_report(w(i1),n)) then pack_error=SFOX_PACK_BAD_REPORT @@ -292,8 +300,8 @@ contains integer n28 valid_sfox_call=.false. - call pack28(call,n28) - call unpack28(n28,decoded,success) + call pack28_for_state(knowledge,call,n28) + call unpack28_for_state(knowledge,n28,decoded,success) if(.not.success) return valid_sfox_call=trim(decoded).eq.trim(call) return @@ -352,4 +360,22 @@ contains enddo return end function valid_sfox_free_text +end subroutine sfox_pack_for_state +end module sfox_pack_module + +subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) + use sfox_pack_module, only: sfox_pack_for_state + use ft8_codec_context, only: get_ft8_codec_state + use packjt77, only: pack77_state + implicit none + character*120 line + character*10 ckey + character*26 freeTextMsg + logical*1 bMoreCQs,bSendMsg + integer*1 xin(0:49) + integer pack_error + type(pack77_state), pointer :: knowledge + + knowledge => get_ft8_codec_state() + call sfox_pack_for_state(knowledge,line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) end subroutine sfox_pack diff --git a/lib/superfox/sfox_remove_ft8.f90 b/lib/superfox/sfox_remove_ft8.f90 index 75687659..ef3c9fe1 100644 --- a/lib/superfox/sfox_remove_ft8.f90 +++ b/lib/superfox/sfox_remove_ft8.f90 @@ -1,5 +1,13 @@ -subroutine sfox_remove_ft8(dd,npts) +module sfox_remove_ft8_module + implicit none + private + public :: sfox_remove_ft8_for_state +contains +subroutine sfox_remove_ft8_for_state(knowledge,dd,npts) use packjt77 + implicit real(a-h,o-z) + implicit integer(i-n) + type(pack77_state), optional, intent(inout) :: knowledge include 'ft8_params.f90' parameter (MAXCAND=100) parameter (NP2=2812) @@ -194,7 +202,11 @@ subroutine sfox_remove_ft8(dd,npts) if(i3.gt.5 .or. (i3.eq.0.and.n3.gt.6)) cycle if(i3.eq.0 .and. n3.eq.2) cycle - call unpack77(c77,1,msg37,unpk77_success) + if(present(knowledge)) then + call unpack77_for_state(knowledge,c77,1,msg37,unpk77_success) + else + call unpack77(c77,1,msg37,unpk77_success) + endif ! write(77,*) 'FT8 interference: ',msg37 if(.not.unpk77_success) cycle ! Message structure: S7 D29 S7 D29 S7 @@ -213,4 +225,14 @@ subroutine sfox_remove_ft8(dd,npts) ! return enddo return +end subroutine sfox_remove_ft8_for_state +end module sfox_remove_ft8_module + +subroutine sfox_remove_ft8(dd,npts) + use sfox_remove_ft8_module, only: sfox_remove_ft8_for_state + implicit none + integer npts + real dd(npts) + + call sfox_remove_ft8_for_state(dd=dd,npts=npts) end subroutine sfox_remove_ft8 diff --git a/lib/superfox/sfox_unpack.f90 b/lib/superfox/sfox_unpack.f90 index fd940347..b86f6bb2 100644 --- a/lib/superfox/sfox_unpack.f90 +++ b/lib/superfox/sfox_unpack.f90 @@ -1,12 +1,34 @@ -subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) +module sfox_unpack_module + use iso_c_binding, only: c_ptr, c_null_ptr + use decoder_engine_types, only: superfox_observation, sf_kind_cq, sf_kind_exchange, & + sf_kind_free_text, sf_kind_verification + use packjt77, only: pack77_state + implicit none + private + public :: sfox_unpack_for_state, superfox_callback, sfox_render_legacy + abstract interface + subroutine superfox_callback(user_context,record) + import superfox_observation, c_ptr + type(c_ptr), intent(in) :: user_context + type(superfox_observation), intent(in) :: record + end subroutine superfox_callback + end interface +contains +subroutine sfox_unpack_for_state(knowledge,callback,user_context,nutc,x,nsnr,f0,dt0,foxcall,notp) use packjt77 + implicit real(a-h,o-z) + implicit integer(i-n) + type(pack77_state), optional, intent(inout) :: knowledge + procedure(superfox_callback) :: callback + type(c_ptr), intent(in) :: user_context + integer child_index parameter (NQU1RKS=203514677) integer*1 x(0:49) integer*8 n58 logical success character*336 msgbits - character*22 msg(10) !### only msg(1) is used ??? ### + character*22 msg(10) character*13 foxcall,c13 character*10 ssignature character*4 crpt(5),grid4 @@ -15,6 +37,7 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) logical use_otp data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/ + child_index=0 ncq=0 if (notp.eq.0) then use_otp = .FALSE. @@ -25,7 +48,11 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) 1000 format(47b7.7) read(msgbits(327:329),'(b3)') i3 !Message type read(msgbits(1:28),'(b28)') n28 !Standard Fox call - call unpack28(n28,foxcall,success) + if(present(knowledge)) then + call unpack28_for_state(knowledge,n28,foxcall,success) + else + call unpack28(n28,foxcall,success) + endif if(i3.eq.1) then ! Type i3=1 is documented for a compound-Fox c58 layout, but the @@ -40,8 +67,7 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) if(freeTextMsg(i:i).ne.'.') exit freeTextMsg(i:i)=' ' enddo - write(*,1100) nutc,nsnr,dt0,nint(f0),freeTextMsg -1100 format(i6.6,i4,f5.1,i5,1x,"~",2x,a) + call emit(sf_kind_free_text,freeTextMsg) else if(i3.eq.3) then !CQ FoxCall Grid read(msgbits(1:58),'(b58)') n58 !FoxCall do i=11,1,-1 @@ -53,7 +79,7 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) read(msgbits(59:73),'(b15)') n15 call unpackgrid(n15,grid4) msg(1)='CQ '//trim(foxcall)//' '//grid4 - write(*,1100) nutc,nsnr,dt0,nint(f0),trim(msg(1)) + call emit(sf_kind_cq,trim(msg(1))) allz=1 do i=0,6 read(msgbits(74+32*i:105+32*i),'(b32)') n32 @@ -66,8 +92,7 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) if(freeTextMsg(i:i).ne.'.') exit freeTextMsg(i:i)=' ' enddo - if(len(trim(freeTextMsg)).gt.0) write(*,1100) nutc,nsnr,dt0,& - nint(f0),freeTextMsg + if(len(trim(freeTextMsg)).gt.0) call emit(sf_kind_free_text,freeTextMsg) go to 100 endif @@ -92,7 +117,11 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) do i=1,iz j=28*i + 1 read(msgbits(j:j+27),'(b28)') n28 - call unpack28(n28,c13,success) + if(present(knowledge)) then + call unpack28_for_state(knowledge,n28,c13,success) + else + call unpack28(n28,c13,success) + endif if(n28.eq.0 .or. n28.eq.NQU1RKS) cycle msg(i)=trim(c13)//' '//trim(foxcall) if(msg(i)(1:3).eq.'CQ ') then @@ -106,19 +135,60 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) endif endif if(ncq.le.1 .or. msg(i)(1:3).ne.'CQ ') then - write(*,1100) nutc,nsnr,dt0,nint(f0),trim(msg(i)) + if(msg(i)(1:3).eq.'CQ ') then + call emit(sf_kind_cq,trim(msg(i))) + else + call emit(sf_kind_exchange,trim(msg(i))) + endif endif enddo if(msgbits(306:306).eq.'1' .and. ncq.lt.1) then - write(*,1100) nutc,nsnr,dt0,nint(f0),'CQ '//foxcall + call emit(sf_kind_cq,'CQ '//foxcall) endif 100 read(msgbits(307:326),'(b20)') notp if (use_otp) then write(ssignature,'(I6.6)') notp - write(*,1100) nutc,nsnr,dt0,nint(f0),'$VERIFY$ '//trim(foxcall)// & - ' '//trim(ssignature) + call emit(sf_kind_verification,'$VERIFY$ '//trim(foxcall)//' '//trim(ssignature)) endif 900 return +contains + subroutine emit(kind,text) + integer, intent(in) :: kind + character(len=*), intent(in) :: text + type(superfox_observation) :: record + + child_index=child_index+1 + record%symbols=x + record%kind=kind + record%child_index=child_index + record%frequency_hz=f0 + record%dt_seconds=dt0 + record%snr_db=nsnr + record%message=text + write(record%legacy_line,'(i6.6,i4,f5.1,i5,1x,"~",2x,a)') nutc,nsnr,dt0,nint(f0),text + record%legacy_line_length=24+len(text) + call callback(user_context,record) + end subroutine emit +end subroutine sfox_unpack_for_state + +subroutine sfox_render_legacy(user_context,record) + type(c_ptr), intent(in) :: user_context + type(superfox_observation), intent(in) :: record + write(*,'(a)') record%legacy_line(:record%legacy_line_length) +end subroutine sfox_render_legacy +end module sfox_unpack_module + +subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp) + use iso_c_binding, only: c_null_ptr + use sfox_unpack_module, only: sfox_unpack_for_state, sfox_render_legacy + implicit none + integer nutc,nsnr,notp + integer*1 x(0:49) + real f0,dt0 + character*13 foxcall + + call sfox_unpack_for_state(callback=sfox_render_legacy,user_context=c_null_ptr,nutc=nutc,x=x,nsnr=nsnr, & + f0=f0,dt0=dt0,foxcall=foxcall,notp=notp) end subroutine sfox_unpack diff --git a/lib/superfox/sfrx_sub.f90 b/lib/superfox/sfrx_sub.f90 index fed03461..3031ce56 100644 --- a/lib/superfox/sfrx_sub.f90 +++ b/lib/superfox/sfrx_sub.f90 @@ -1,7 +1,21 @@ -subroutine sfrx_sub(nyymmdd,nutc,nfqso,ntol,iwave) +module sfrx_engine + use iso_c_binding, only: c_ptr + use packjt77, only: pack77_state + use sfox_unpack_module, only: superfox_callback, sfox_unpack_for_state, sfox_render_legacy + use sfox_remove_ft8_module, only: sfox_remove_ft8_for_state + implicit none + private + public :: sfrx_decode, superfox_callback +contains +subroutine sfrx_decode(knowledge,callback,user_context,nyymmdd,nutc,nfqso,ntol,iwave) use sfox_mod use julian + implicit real(a-h,o-z) + implicit integer(i-n) + type(pack77_state), optional, intent(inout) :: knowledge + procedure(superfox_callback) :: callback + type(c_ptr), intent(in) :: user_context integer*2 iwave(NMAX) integer*8 secday,ntime8 @@ -33,7 +47,7 @@ subroutine sfrx_sub(nyymmdd,nutc,nfqso,ntol,iwave) allocate(c0(NMAX),dd(NMAX)) dd=iwave - call sfox_remove_ft8(dd,npts) + call sfox_remove_ft8_for_state(knowledge,dd,npts) call sfox_ana(dd,npts,c0,npts) @@ -48,8 +62,22 @@ subroutine sfrx_sub(nyymmdd,nutc,nfqso,ntol,iwave) if(crc_ok) then nsnr=nint(snr) nsignature = 1 - call sfox_unpack(nutc,xdec,nsnr,fbest-750.0,tbest,foxcall,nsignature) + call sfox_unpack_for_state(knowledge,callback,user_context,nutc,xdec,nsnr,fbest-750.0,tbest,foxcall,nsignature) endif return +end subroutine sfrx_decode +end module sfrx_engine + +subroutine sfrx_sub(nyymmdd,nutc,nfqso,ntol,iwave) + use iso_c_binding, only: c_null_ptr + use sfrx_engine, only: sfrx_decode + use sfox_unpack_module, only: sfox_render_legacy + use sfox_mod, only: NMAX + implicit none + integer nyymmdd,nutc,nfqso,ntol + integer*2 iwave(NMAX) + + call sfrx_decode(callback=sfox_render_legacy,user_context=c_null_ptr,nyymmdd=nyymmdd,nutc=nutc, & + nfqso=nfqso,ntol=ntol,iwave=iwave) end subroutine sfrx_sub diff --git a/lib/symspec65.f90 b/lib/symspec65.f90 index b0dc2844..c65d57df 100644 --- a/lib/symspec65.f90 +++ b/lib/symspec65.f90 @@ -1,6 +1,7 @@ -!subroutine symspec65(dd,npts,ss,nqsym,savg) subroutine symspec65(dd,npts,nqsym,savg) + use jt65_mod, only: jt65_work,ensure_jt65_workspace + ! Compute JT65 symbol spectra at quarter-symbol steps parameter (NFFT=8192) @@ -10,7 +11,6 @@ subroutine symspec65(dd,npts,nqsym,savg) real*8 hstep real*4 dd(npts) ! real*4 ss(MAXHSYM,NSZ) - real*4 ss(MAXQSYM,NSZ) real*4 savg(NSZ) real*4 x(NFFT) real*4 w(NFFT) @@ -20,14 +20,22 @@ subroutine symspec65(dd,npts,nqsym,savg) equivalence (x,c) data first/.true./ save /refspec/,first,w - common/sync/ss + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%spectra)) allocate(jt65_work%spectra(552,3413)) + associate(ss=>jt65_work%spectra) hstep=2048.d0*12000.d0/11025.d0 !half-symbol = 2229.116 samples qstep=hstep/2.0 !quarter-symbol = 1114.558 samples nsps=nint(2*hstep) df=12000.0/NFFT nhsym=(npts-NFFT)/hstep - nqsym=(npts-NFFT)/qstep + nqsym=min(MAXQSYM,max(0,int((npts-NFFT)/qstep))) + if(nhsym<=0.or.nqsym==0) then + nqsym=0 + savg=0. + ref=1. + return + endif savg=0. fac1=1.e-3 @@ -58,11 +66,18 @@ subroutine symspec65(dd,npts,nqsym,savg) ! call flat65(ss,nhsym,MAXQSYM,NSZ,ref) !Flatten the 2d spectrum, saving call flat65(ss,nqsym,MAXQSYM,NSZ,ref) !Flatten the 2d spectrum, saving dfref=df ! the reference spectrum ref() + do i=1,NSZ + if(ref(i)>0.) cycle + ss(1:nqsym,i)=0. + savg(i)=0. + ref(i)=1. + enddo savg=savg/ref ! do j=1,nhsym do j=1,nqsym ss(j,1:NSZ)=ss(j,1:NSZ)/ref enddo + end associate return end subroutine symspec65 diff --git a/lib/sync65.f90 b/lib/sync65.f90 index cfb3accb..1c343056 100644 --- a/lib/sync65.f90 +++ b/lib/sync65.f90 @@ -1,7 +1,8 @@ subroutine sync65(nfa,nfb,ntol,nqsym,ca,ncand,nrobust,bVHF) + use jt65_mod, only: jt65_work,ensure_jt65_workspace + parameter (NSZ=3413,NFFT=8192,MAXCAND=300) - real ss(552,NSZ) real ccfblue(-32:82) !CCF with pseudorandom sequence real ccfred(NSZ) !Peak of ccfblue, as function of freq logical bVHF @@ -15,14 +16,18 @@ subroutine sync65(nfa,nfb,ntol,nqsym,ca,ncand,nrobust,bVHF) type(candidate) ca(MAXCAND) common/steve/thresh0 - common/sync/ss + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%spectra)) allocate(jt65_work%spectra(552,3413)) + associate(ss=>jt65_work%spectra) if(ntol.eq.-99) stop !Silence compiler warning call setup65 df=12000.0/NFFT !df = 12000.0/8192 = 1.465 Hz ia=max(2,nint(nfa/df)) ib=min(NSZ-1,nint(nfb/df)) + ncand=0 + if(ib<ia) return ! lag1=-11 ! lag2=59 ! lag1=-22 @@ -90,5 +95,6 @@ subroutine sync65(nfa,nfb,ntol,nqsym,ca,ncand,nrobust,bVHF) if(ncand.eq.MAXCAND) exit enddo + end associate return end subroutine sync65 diff --git a/lib/sync9.f90 b/lib/sync9.f90 index 80560382..0c4be41e 100644 --- a/lib/sync9.f90 +++ b/lib/sync9.f90 @@ -17,11 +17,13 @@ subroutine sync9(ss,nzhsym,lag1,lag2,ia,ib,ccfred,red2,ipkbest) ipkbest=0 sbest=0. ccfred=0. + red2=0. do i=ia,ib !Loop over freq range ss1=ss(1:184,i) call pctile(ss1,nzhsym,40,xmed) + if(xmed.le.0.) cycle ss1=ss1/xmed - 1.0 do j=1,nzhsym if(ss1(j).gt.3.0) ss1(j)=3.0 @@ -29,27 +31,20 @@ subroutine sync9(ss,nzhsym,lag1,lag2,ia,ib,ccfred,red2,ipkbest) call pctile(ss1,nzhsym,45,sbase) ss1=ss1-sbase - sq0=dot_product(ss1(1:nzhsym),ss1(1:nzhsym)) - rms=sqrt(sq0/(nzhsym-1)) smax=0. do lag=lag1,lag2 !DT = 2.5 to 5.0 s sum1=0. - sq2=sq0 - nsum=nzhsym do j=1,16 !Sum over 16 sync symbols k=ii2(j) + lag if(k.ge.1 .and. k.le.nzhsym) then sum1=sum1 + ss1(k) - sq2=sq2 - ss1(k)*ss1(k) - nsum=nsum-1 endif enddo if(sum1.gt.smax) then smax=sum1 ipk=i endif - rms=sqrt(sq2/(nsum-1)) enddo ccfred(i)=smax !Best at this freq, over all lags if(smax.gt.sbest) then @@ -81,10 +76,10 @@ subroutine sync9(ss,nzhsym,lag1,lag2,ia,ib,ccfred,red2,ipkbest) enddo call pctile(sq(ia:ib),ib-ia+1,20,sq0) + if(sq0.le.0.) return rms=sqrt(sq0) savg2(ia:ib)=savg2(ia:ib)/(5.0*rms) - red2=0. do i=ia+11,ib-10 ref=max(savg2(i-10),savg2(i+10)) red2(i)=savg2(i)-ref diff --git a/lib/sync9w.f90 b/lib/sync9w.f90 index e25afab0..cb9d4597 100644 --- a/lib/sync9w.f90 +++ b/lib/sync9w.f90 @@ -1,4 +1,4 @@ -subroutine sync9w(ss,nzhsym,lag1,lag2,ia,ib,ccfred,ccfblue,ipkbest,lagpk,nadd) +subroutine sync9w(ss,nzhsym,lag1,lag2,ia,ib,icandidatea,icandidateb,ccfred,ccfblue,ipkbest,lagpk,nadd) include 'constants.f90' real ss(184,NSMAX) @@ -12,10 +12,12 @@ subroutine sync9w(ss,nzhsym,lag1,lag2,ia,ib,ccfred,ccfblue,ipkbest,lagpk,nadd) do j=1,nzhsym sa=ss(j,1:NSMAX) call smo(sa,NSMAX,sb,nadd) - call smo(sb,NSMAX,sa,nadd) + call smo(sa,NSMAX,sb,nadd) ss(j,1:NSMAX)=sa enddo + lagpk=0 + ccfblue=0. ipk=0 ipkbest=0 sbest=0. @@ -23,9 +25,11 @@ subroutine sync9w(ss,nzhsym,lag1,lag2,ia,ib,ccfred,ccfblue,ipkbest,lagpk,nadd) df=12000.0/16384.0 do i=ia,ib !Loop over specified freq range - ss1=ss(1:184,i) !Symbol amplitudes at this freq + ss1=0. + ss1(1:nzhsym)=ss(1:nzhsym,i) !Available symbol amplitudes at this freq call pctile(ss1,nzhsym,50,xmed) !Median level at this freq - ss1=ss1/xmed - 1.0 + if(xmed.le.0.) cycle + ss1(1:nzhsym)=ss1(1:nzhsym)/xmed - 1.0 smax=0. !Find DT in specified range do lag=lag1,lag2 @@ -45,13 +49,14 @@ subroutine sync9w(ss,nzhsym,lag1,lag2,ia,ib,ccfred,ccfblue,ipkbest,lagpk,nadd) enddo ccfred(i)=smax !Best at this freq, over all lags - if(smax.gt.sbest) then + if(i.ge.icandidatea .and. i.le.icandidateb .and. smax.gt.sbest) then sbest=smax ipkbest=ipk ss1save=ss1 endif enddo + if(ipkbest.eq.0) return call pctile(ccfred(ia),ib-ia+1,50,xmed) if(xmed.le.0.0) xmed=1.0 ccfred=ccfred/xmed diff --git a/lib/tmoonsub.c b/lib/tmoonsub.c index 98e1e19d..a53dec79 100644 --- a/lib/tmoonsub.c +++ b/lib/tmoonsub.c @@ -56,7 +56,7 @@ void getargs(int argc, char *argv[], int *y, int *m, double *tz, /* if not right number of arguments, then print example command line */ if (argc !=5) { - fprintf(stderr, usage); + fputs(usage, stderr); exit(EXIT_FAILURE); } diff --git a/lib/xcor.f90 b/lib/xcor.f90 index 84273b85..9895e5f1 100644 --- a/lib/xcor.f90 +++ b/lib/xcor.f90 @@ -9,13 +9,14 @@ subroutine xcor(ipk,nsteps,nsym,lag1,lag2,ccf,ccf0,lagpk,flip,fdot,nrobust) use jt65_mod parameter (NHMAX=3413) !Max length of power spectra parameter (NSMAX=552) !Max number of quarter-symbol steps - real ss(NSMAX,NHMAX) !2d spectrum, stepped by half-symbols real a(NSMAX) ! real ccf(-44:118) real ccf(lag1:lag2) ! save - common/sync/ss + call ensure_jt65_workspace() + if(.not.allocated(jt65_work%spectra)) allocate(jt65_work%spectra(552,3413)) + associate(ss=>jt65_work%spectra) df=12000.0/8192. ! dtstep=0.5/df dtstep=0.25/df @@ -73,5 +74,6 @@ subroutine xcor(ipk,nsteps,nsym,lag1,lag2,ccf,ccf0,lagpk,flip,fdot,nrobust) flip=-1.0 endif + end associate return end subroutine xcor |
