diff options
| author | hibby <d@vehibberd.com> | 2026-10-06 21:24:40 +0100 |
|---|---|---|
| committer | hibby <d@vehibberd.com> | 2026-10-06 21:24:40 +0100 |
| commit | c25cbdf6fb6d946175f4335fab77bfea601b56db (patch) | |
| tree | 6f7a94b7b81f999e434f61b73d47e337dfd26bf2 /lib/jtty | |
| parent | 71f5689252c9f13e70e1c24856904475b2307809 (diff) | |
| parent | 0685fcada9f95fe90f70b387cd7d757da8209624 (diff) | |
Merge tag 'debian/3.2.0_rc1+dfsg-2' into debian/trixie-backportsdebian/trixie-backports
tagging wsjtx 3.2.0~rc1+dfsg-2
Diffstat (limited to 'lib/jtty')
44 files changed, 9455 insertions, 0 deletions
diff --git a/lib/jtty/JTTY Messages.mc b/lib/jtty/JTTY Messages.mc new file mode 100644 index 00000000..7b0b91ea --- /dev/null +++ b/lib/jtty/JTTY Messages.mc @@ -0,0 +1,44 @@ +# +# Digital Function Key File Example for JTTY use +# +# See the discussion in the accompanying jtty_n1mm_integration.md file +# The leading [[JTTY:ACTION]] marker opts into native Call8/STRUCT30 encoding. +# Untagged N1MM text uses automatic packing after exchange-profile normalization. +# +# S&P F1 calls CQ and automatically places the program in RUN Mode +# F2 F3 F4 F5 use "!" macro for his callsign +# Exchange actions use the active JTTY profile; do not hardcode 599. +# Run F11 remains spare until N1MM call-stack TXTEXT ordering is validated. +# +################### +# RUN Messages +################### +F1 Run CQ,{TX}[[JTTY:CQ]]{MYCALL}{RX} +F2 Run Exch,{TX}[[JTTY:CALL_EXCH]]! {EXCH}{RX} +F3 Run TU,{TX}[[JTTY:CALL_TU_CQ]]! {MYCALL}{RX} +F4 {MYCALL},{TX}[[JTTY:MYCALL]]{MYCALL}{RX} +F5 His Call,{TX}[[JTTY:HISCALL]]!{RX} +F6 NR?,{TX}[[JTTY:CONTROL]]NR?{RX} +F7 Spare, +F8 Agn?,{TX}[[JTTY:CONTROL]]AGN?{RX} +F9 Spare, +F10 Spare, +F11 Spare, +F12 Wipe,{WIPE} +# +################### +# S&P Messages +################### +# "&" doubled, displays one "&" in the button label +F1 S&&P CQ,{TX}[[JTTY:CQ]]{MYCALL}{RX} +F2 S&&P Exch,{TX}[[JTTY:CALL_EXCH]]! {EXCH}{RX} +F3 S&&P TU,{TX}[[JTTY:CALL_TU_MY]]! {MYCALL}{RX} +F4 S&&P Call Him,{TX}[[JTTY:CALL_MY]]! {MYCALL}{RX} +F5 His Call,{TX}[[JTTY:HISCALL]]!{RX} +F6 {MYCALL},{TX}[[JTTY:MYCALL]]{MYCALL}{RX} +F7 My Exch,{TX}[[JTTY:EXCH]]{EXCH}{RX} +F8 Agn?,{TX}[[JTTY:CONTROL]]AGN?{RX} +F9 Spare, +F10 Spare, +F11 Spare, +F12 Wipe,{WIPE} diff --git a/lib/jtty/ana64a.f90 b/lib/jtty/ana64a.f90 new file mode 100644 index 00000000..fe7c7fb8 --- /dev/null +++ b/lib/jtty/ana64a.f90 @@ -0,0 +1,19 @@ +subroutine ana64a(iwave,npts,c0,nfft1) + implicit none + integer*2, intent(in) :: iwave(npts) !Raw data at 12000 Hz + integer, intent(in) :: npts, nfft1 + integer :: nfft2 + real :: fac + complex, intent(out) :: c0(0:nfft1-1) + + nfft2=nfft1/2 + fac=2.0/(32767.0*NFFT1) + c0(0:npts-1)=fac*iwave(1:npts) + c0(npts:)=0. + call four2a(c0,NFFT1,1,-1,1) !Forward c2c FFT + c0(nfft2/2+1:nfft2-1)=0. !Set negative freqs to 0. + c0(0)=0.5*c0(0) + call four2a(c0,nfft2,1,1,1) !Inverse c2c FFT; c0 is the analytic sig + c0(npts:)=0. + return +end subroutine ana64a diff --git a/lib/jtty/c_funcs.f90 b/lib/jtty/c_funcs.f90 new file mode 100644 index 00000000..3c21cf16 --- /dev/null +++ b/lib/jtty/c_funcs.f90 @@ -0,0 +1,13 @@ +MODULE c_funcs + + USE, INTRINSIC :: ISO_C_BINDING + IMPLICIT NONE + + INTERFACE + ! Use BIND(C, name="putc") to link to the C library function + FUNCTION c_putc(character) BIND(C, name="putchar") + INTEGER(C_INT) :: c_putc + END FUNCTION c_putc + END INTERFACE + + END MODULE C_Funcs diff --git a/lib/jtty/cdatetime.f90 b/lib/jtty/cdatetime.f90 new file mode 100644 index 00000000..33deaf30 --- /dev/null +++ b/lib/jtty/cdatetime.f90 @@ -0,0 +1,6 @@ +character*17 function cdatetime() + character cdate*8,ctime*10 + call date_and_time(cdate,ctime) + cdatetime=cdate(3:8)//'_'//ctime + return +end function cdatetime diff --git a/lib/jtty/decodes.txt b/lib/jtty/decodes.txt new file mode 100644 index 00000000..ed82f996 --- /dev/null +++ b/lib/jtty/decodes.txt @@ -0,0 +1,463 @@ + 0 1 1 1 F 1501.2 0.264 1.536 -11 ~~~~~ + 0 2 2 2 F 1501.7 0.101 15.789 0 CQ K1JT CQ + 0 3 3 3 F 1502.2 0.315 24.483 6 K1JT + 0 4 3 3 T 1502.2 0.313 26.177 5 599 0004~ + 0 5 4 4 F 1502.2 0.202 30.730 8 AA5AU + 0 6 5 5 F 1502.2 0.061 73.413 4 AA5AU + 0 7 6 6 F 1502.2 0.352 84.728 7 AA5AU + 0 8 7 7 F 1502.2 0.259 109.227 5 AA5AU + 0 9 8 8 F 1518.3 0.271 135.527 -8 CQ W1UE CQ + 0 10 9 9 F 1502.2 0.169 151.113 4 ONLY~ + 0 11 9 9 T 1502.2 0.168 152.808 12 DECOD + 0 12 9 9 T 1502.2 0.168 154.504 10 ED~YO + 0 13 9 9 T 1502.2 0.169 156.201 16 UR~FI + 0 14 9 9 T 1502.2 0.168 157.896 8 RST~C + 0 15 9 9 T 1502.2 0.167 159.591 14 Q~~~~ + 0 16 10 10 F 1502.2 0.157 172.301 13 DID~N + 0 17 10 10 T 1502.2 0.156 173.996 14 OT~DE + 0 18 10 10 T 1502.2 0.159 175.695 1 CODE~ + + 0 1 1 1 F 1515.4 0.173 8.229 -7 CQ W1UE CQ + 0 2 2 2 F 1502.2 0.347 16.035 14 NO~DE + 0 3 2 2 T 1502.2 0.347 17.731 13 CODE~ + 14 4 3 3 F 2705.6 0.380 48.716 -14 + 0 5 4 4 F 1502.2 0.117 60.325 2 CQ AA5AU CQ + 0 6 5 5 F 1517.9 0.199 65.919 -11 IS~TH + 0 7 5 5 T 1515.4 0.199 67.615 -7 IS~DE + 0 8 5 5 T 1515.8 0.199 69.311 -8 CODIN + 0 9 6 6 F 1502.2 0.392 74.592 7 YES~~ + 0 10 7 7 F 1515.8 0.163 84.539 -9 CQ W1UE CQ + 0 11 8 8 F 1502.7 0.155 92.587 5 AA5AU + 0 12 2 8 T 1502.2 0.346 102.530 12 W1UE + 0 13 2 8 T 1502.2 0.345 104.225 13 599 0004~ + 0 14 9 9 F 1518.3 0.220 118.940 -11 599 0008~ + 0 15 10 10 F 1502.2 0.203 124.011 12 TU NOW W1UE + 0 16 10 10 T 1502.7 0.203 125.707 8 599 0004~ + 0 17 11 11 F 1516.8 0.254 128.726 -9 TU W1UE CQ + + 0 1 1 1 F 1514.3 0.357 30.037 -10 CQ W1UE CQ + 0 2 2 2 F 1502.7 0.227 35.419 1 AA5AU + 0 3 3 3 F 1516.8 0.186 39.194 -9 CQ W1UE CQ + 0 4 4 4 F 1502.7 0.191 47.255 7 AGN?~ + 0 5 5 5 F 1502.2 0.405 55.525 -13 AGN?~ + 0 6 6 6 F 1514.9 0.196 70.580 -9 AA5AU + 0 7 7 7 F 1502.7 0.017 79.305 11 599 0005~ + 0 8 8 8 F 1502.7 0.321 97.841 12 I~HAV + 0 9 8 8 T 1502.2 0.320 99.536 14 E~STR + 0 10 8 8 T 1502.7 0.319 101.231 10 ONG~S + 0 11 8 8 T 1502.7 0.320 102.928 12 SB~QR + 0 12 8 8 T 1502.2 0.319 104.623 12 M~~~~ + 0 13 9 9 F 1514.8 0.123 124.355 -7 R~IT~ + 0 14 9 9 T 1517.4 0.127 126.055 -11 BUT~N + 0 15 9 9 T 1515.8 0.128 127.752 -6 OT~ST + 0 16 10 10 F 1502.7 0.159 138.807 -3 NOT~B + 0 17 10 10 T 1502.7 0.160 140.504 15 OTHER + 0 18 10 10 T 1502.7 0.160 142.200 16 NING~ + 0 19 10 10 T 1502.7 0.160 143.896 16 DECOD + 0 20 10 10 T 1502.7 0.161 145.593 15 E~NOW + 0 21 11 11 F 1515.4 0.267 152.059 -11 Y~YOU + 0 22 11 11 T 1517.8 0.266 153.754 -10 ~CAN' + 0 23 11 11 T 1514.8 0.267 155.451 -12 T~COP + 0 24 12 12 F 1502.7 0.283 161.403 10 NOT~S + 0 25 12 12 T 1502.7 0.281 163.097 1 URE~~ + 0 26 13 13 F 1519.3 0.129 168.033 -10 CQ W1UE CQ + + 0 1 1 1 F 1517.8 0.175 9.927 -11 W1UE + 0 2 2 2 F 1501.7 0.358 17.742 6 AA5AU + 0 3 2 2 T 1501.7 0.357 19.437 14 599 0001~ + 0 4 3 3 F 1502.7 0.415 25.855 14 599 0005~ + 0 5 4 4 F 1497.4 0.000 25.864 -10 599 0005~ + 0 6 5 5 F 1501.7 0.125 37.013 2 TU WV4P CQ + 0 7 6 6 F 1502.2 0.215 45.583 4 U~QTC + 0 8 6 6 T 1501.7 0.214 47.278 10 ~FOR~ + 0 9 6 6 T 1501.7 0.214 48.974 16 ME~?~ + 0 10 7 7 F 1501.7 0.107 76.427 12 CQ WV4P CQ + 0 11 8 8 F 1515.8 0.404 80.540 -11 W1UE + 0 12 9 9 F 1501.7 0.026 86.098 3 CQ WV4P CQ + 0 13 2 9 T 1501.7 0.359 100.423 1 CQ WV4P CQ + 0 14 10 10 F 1517.9 0.069 104.797 -13 W1UE + 0 15 11 11 F 1517.3 0.267 116.867 -10 WV4P + 0 16 11 11 T 1516.8 0.264 118.560 -7 W1UE~ + 0 17 12 12 F 1502.2 0.178 125.258 2 ~~~~~ + 0 18 13 13 F 1516.8 0.296 134.704 -13 CODE~ + 0 19 14 14 F 1502.7 0.101 141.717 5 CQ AA5AU CQ + 0 20 5 14 T 1502.2 0.121 144.705 1 YOU~Q + 0 21 5 14 T 1502.2 0.121 146.401 15 TC~FO + 0 22 5 14 T 1502.2 0.121 148.097 16 R~ME~ + 0 23 5 14 T 1502.2 0.121 149.793 16 ?~~~~ + 0 24 15 15 F 1502.7 0.086 165.022 15 CQ AA5AU CQ + 0 25 16 16 F 1515.8 0.393 169.993 -7 W1UE + + 0 1 1 1 F 1517.8 0.164 21.364 -11 BE~BA + 0 2 1 1 T 1513.9 0.162 23.058 -9 CK~IN + 0 3 1 1 T 1517.8 0.164 26.452 -11 NUTE~ + 0 4 2 2 F 1502.2 0.067 39.075 14 AWESO + 0 5 2 2 T 1502.2 0.066 40.770 15 ME~ME + 0 6 2 2 T 1502.2 0.066 42.466 15 ~TOO~ + 0 7 2 2 T 1502.2 0.066 44.162 16 !~~~~ + 0 8 3 3 F 1502.7 0.377 52.529 8 73~AA + 0 9 3 3 T 1503.2 0.377 54.225 14 5AU~~ + 0 10 2 3 T 1503.2 0.068 102.676 14 TU AA5AU CQ + 0 11 4 4 F 1516.8 0.157 112.093 -11 W1UE + 0 12 5 5 F 1503.2 0.144 118.440 1 W1UE + 0 13 5 5 T 1503.2 0.144 120.136 13 599 0007~ + 0 14 6 6 F 1515.3 0.339 125.419 -11 599 010~~ + 0 15 7 7 F 1503.2 0.351 128.823 16 TU AA5AU CQ + 0 16 8 8 F 1503.2 0.262 143.150 4 AA5AU + + 0 1 1 1 F 1515.9 0.215 7.847 -12 CQ W1UE CQ + 0 2 2 2 F 1503.2 0.353 17.737 16 AA5AU + 0 3 3 3 F 1503.2 0.064 45.432 17 AGN?~ + 0 4 4 4 F 1503.2 0.321 55.441 16 AGN?~ + 0 5 5 5 F 1503.2 0.315 76.211 4 NO~DE + 0 6 5 5 T 1503.2 0.315 77.907 15 CODE~ + 0 7 5 5 T 1503.2 0.315 79.603 16 QRX~W + 0 8 5 5 T 1503.2 0.315 81.299 16 ILL~R + 0 9 5 5 T 1503.2 0.315 82.995 15 ESTAR + 0 10 5 5 T 1503.2 0.315 84.691 16 T~~~~ + 0 11 6 6 F 1503.2 0.161 135.417 14 CQ AA5AU CQ + 0 12 7 7 F 1515.3 0.334 149.158 -11 W1UE + 0 13 8 8 F 1503.2 0.020 156.900 16 W1UE + 0 14 8 8 T 1503.2 0.020 158.596 16 599 0008~ + 0 15 9 9 F 1516.8 0.240 165.176 -10 599 010~~ + 0 16 10 10 F 1503.2 0.190 172.334 5 TU AA5AU CQ + + 0 1 1 1 F 1503.2 0.133 3.101 8 AA5AU + 0 2 2 2 F 1514.8 0.093 11.965 -11 599 011~~ + 0 3 3 3 F 1503.2 0.362 15.626 15 W1UE + 0 4 3 3 T 1503.7 0.361 17.321 16 599 0009~ + 0 5 4 4 F 1517.4 0.273 21.897 -12 TU W1UE CQ + 0 6 5 5 F 1517.4 0.019 30.971 -13 CQ W1UE CQ + 0 7 6 6 F 1515.8 0.071 45.439 -10 CQ W1UE CQ + 0 8 7 7 F 1503.7 0.343 63.943 16 WHEN~ + 0 9 7 7 T 1503.7 0.343 65.639 16 I~STO + 0 10 7 7 T 1503.2 0.343 67.335 16 P~DEC + 0 11 7 7 T 1503.7 0.343 69.031 15 ODING + 0 12 7 7 T 1503.7 0.343 70.727 16 ~I~HA + 0 13 7 7 T 1503.7 0.343 72.423 16 VE~TO + 0 14 7 7 T 1503.7 0.343 74.119 16 ~REST + 0 15 7 7 T 1503.7 0.343 75.815 16 ART~P + 0 16 7 7 T 1503.7 0.343 77.511 16 GM~~~ + 0 17 8 8 F 1515.4 0.259 92.691 -12 W1UE + 0 18 9 9 F 1513.9 0.352 95.752 -10 W1UE + 0 19 6 9 T 1515.8 0.074 98.442 -12 W1UE + 0 20 10 10 F 1515.3 0.305 110.969 -10 CQ W1UE CQ + 0 21 3 10 T 1503.7 0.361 118.233 4 AA5AU + 0 22 11 11 F 1518.3 0.136 129.456 -8 AA5AU + 0 23 11 11 T 1515.4 0.136 131.152 -10 599 012~~ + 0 24 12 12 F 1503.7 0.051 136.155 14 599 0009~ + 0 25 13 13 F 1516.3 0.110 141.726 -11 TU W1UE CQ + 0 26 14 14 F 1503.7 0.083 169.683 6 AA5AU + 0 27 8 14 T 1517.8 0.257 174.945 -8 AA5AU + 0 28 8 14 T 1515.3 0.255 176.639 -12 599 013~~ + + 0 1 1 1 F 1503.7 0.146 0.994 13 W1UE + 0 2 1 1 T 1503.7 0.145 2.689 15 599 0009~ + 0 3 2 2 F 1516.8 0.124 6.484 -7 TU W1UE CQ + 0 4 3 3 F 1516.8 0.000 32.224 -9 DID~U + 0 5 3 3 T 1519.3 0.002 33.922 -13 ~DECO + 0 6 4 4 F 1514.3 0.415 37.303 -11 L~3~M + 0 7 3 4 T 1516.4 0.000 39.008 -12 ESSAG + 0 8 3 4 T 1516.9 0.004 40.708 -9 ES~FO + 0 9 5 5 F 1503.7 0.059 47.123 11 YES~~ + 0 10 6 6 F 1519.3 0.085 58.173 -12 GOOD! + 0 11 7 7 F 1503.7 0.219 66.363 10 TU AA5AU CQ + 0 12 8 8 F 1517.9 0.007 70.815 -12 W1UE + 0 13 9 9 F 1503.7 0.315 78.755 14 599 010~~ + 0 14 10 10 F 1503.7 0.347 86.843 13 TU AA5AU CQ + 0 15 11 11 F 1517.3 0.354 91.090 -10 AA5AU + 0 16 12 12 F 1503.7 0.202 102.386 14 CQ AA5AU CQ + 0 17 6 12 T 1517.3 0.083 106.931 -9 W1UE + 0 18 13 13 F 1503.7 0.192 110.432 4 W1UE + 0 19 13 13 T 1503.7 0.192 112.128 16 599 011~~ + 0 20 14 14 F 1515.3 0.246 115.574 -9 599 014~~ + 0 21 12 14 T 1503.7 0.201 118.073 10 TU AA5AU CQ + 0 22 15 15 F 1514.3 0.213 124.021 -12 W1UE + 0 23 16 16 F 1503.7 0.231 129.127 3 AA5AU + 0 24 17 17 F 1516.4 0.138 135.394 -10 W1UE + 0 25 18 18 F 1503.7 0.116 145.972 14 DID~G + 0 26 18 18 T 1503.7 0.115 147.667 13 ET~TH + 0 27 18 18 T 1503.7 0.115 149.363 14 AT~LA + 0 28 18 18 T 1503.2 0.116 151.060 13 ST~TX + 0 29 19 19 F 1517.9 0.062 156.518 -13 GETTI + 0 30 20 20 F 1517.3 0.055 159.903 -11 ~CLIC + 0 31 20 20 T 1514.9 0.054 161.598 -8 K~ON~ + 0 32 20 20 T 1515.3 0.054 163.294 -8 YOUR~ + 0 33 12 20 T 1503.7 0.206 170.230 7 RRR~~ + + 0 1 1 1 F 1503.2 0.219 4.883 6 YOUR~ + 0 2 1 1 T 1503.7 0.219 6.579 16 CALL~ + 0 3 1 1 T 1503.2 0.219 8.275 16 STAYS + 0 4 1 1 T 1502.7 0.220 9.972 14 ~IN~D + 0 5 1 1 T 1503.7 0.219 11.667 14 X~CAL + 0 6 1 1 T 1503.2 0.219 13.363 16 L~BOX + 0 7 2 2 F 1514.3 0.334 25.350 -11 NOT~I + 0 8 2 2 T 1516.8 0.335 27.047 -10 F~YOU + 0 9 3 3 F 1516.9 0.343 28.751 -9 ~LOG~ + 0 10 2 3 T 1515.8 0.334 30.438 -11 IT~~~ + 0 11 4 4 F 1502.7 0.062 36.526 13 HOW~D + 0 12 4 4 T 1502.7 0.061 38.221 16 O~YOU + 0 13 4 4 T 1503.2 0.061 39.917 16 ~LOG~ + 0 14 5 5 F 1503.2 0.306 41.434 -5 IT~~~ + 0 15 6 6 F 1517.3 0.357 53.357 -14 WHEN~ + 0 16 6 6 T 1514.9 0.357 55.053 -8 LOGGI + 0 17 6 6 T 1517.3 0.362 56.754 -13 NG~WI + 0 18 7 7 F 1518.3 0.350 58.438 -11 NDOW~ + 0 19 6 7 T 1517.9 0.356 60.140 -8 POPS~ + 0 20 7 7 T 1516.8 0.349 63.525 -10 OG~IT + 0 21 8 8 F 1516.9 0.287 66.855 -9 AFTER + 0 22 8 8 T 1518.3 0.287 68.551 -8 ~F3~~ + 0 23 9 9 F 1502.2 0.410 82.666 15 LOGGI + 0 24 9 9 T 1502.2 0.409 84.361 16 NG~WI + 0 25 9 9 T 1502.2 0.409 86.057 16 NDOW~ + 0 26 9 9 T 1502.2 0.409 87.753 15 DOES~ + 0 27 9 9 T 1502.2 0.410 89.450 14 NOT~P + 0 28 9 9 T 1502.2 0.410 91.146 16 OP~UP + 0 29 9 9 T 1502.2 0.409 92.841 16 ~AFTE + 0 30 9 9 T 1502.2 0.410 94.538 16 R~F3~ + + 0 1 1 1 F 1517.9 0.370 0.370 -10 IN~~~ + 0 2 2 2 F 1502.2 0.375 8.007 5 LOG~Q + 0 3 2 2 T 1502.2 0.375 9.703 16 SO~DO + 0 4 2 2 T 1502.2 0.375 11.399 15 ES~NO + 0 5 2 2 T 1502.2 0.375 13.095 12 THING + + 0 1 1 1 F 1518.3 0.284 0.708 -9 OG~QS + 0 2 2 2 F 1515.8 0.277 2.397 -6 O.~MI + 0 3 2 2 T 1520.8 0.277 4.093 -10 NE~PO + 0 4 1 2 T 1517.3 0.283 5.795 -7 PS~UP + 0 5 3 3 F 1502.2 0.305 16.417 15 DOES~ + 0 6 3 3 T 1502.2 0.305 18.113 12 NOT~W + 0 7 3 3 T 1502.2 0.305 19.809 16 ORK~H + 0 8 3 3 T 1502.2 0.305 21.505 16 ERE~~ + 0 9 4 4 F 1514.8 0.260 49.020 -6 SOMEO + 0 10 4 4 T 1516.8 0.261 50.717 -6 NE~EL + 0 11 4 4 T 1515.8 0.263 52.415 -3 SE~IS + 0 12 4 4 T 1516.4 0.262 54.110 -8 ~IN~T + 0 13 4 4 T 1515.8 0.263 55.807 -9 HERE~ + + 0 1 1 1 F 1502.7 0.035 5.971 2 AGN?~ + + 0 1 1 1 F 1516.8 0.293 4.957 -11 JOE~~ + 0 2 2 2 F 1502.7 0.037 14.029 1 AA5AU + + 0 1 1 1 F 1502.7 0.175 3.143 4 AA5AU + + 0 1 1 1 F 1502.7 0.097 8.577 1 AGN?~ + + 0 1 1 1 F 1502.2 0.369 4.185 6 AGN?~ + + 0 1 1 1 F 1503.7 0.328 8.808 5 NOT~D + 0 2 1 1 T 1503.2 0.327 10.503 12 ECODI + 0 3 1 1 T 1503.2 0.328 12.200 11 NG~DE + 0 4 1 1 T 1503.2 0.328 13.896 13 ~AA5A + 0 5 1 1 T 1503.2 0.327 15.591 11 U~~~~ + 0 6 2 2 F 1503.2 0.126 42.950 -11 WILL~ + 0 7 2 2 T 1503.2 0.125 44.645 11 RESTA + 0 8 2 2 T 1503.2 0.125 46.341 14 RT~PG + 0 9 2 2 T 1503.2 0.126 48.038 7 M~DE~ + 0 10 2 2 T 1503.7 0.125 49.733 6 AA5AU + 0 11 3 3 F 1502.2 0.316 87.660 5 AA5AU + + 0 1 1 1 F 1502.2 0.415 1.263 4 599 012~~ + 0 2 2 2 F 1497.4 0.000 1.272 -8 599 012~~ + + 0 1 1 1 F 1502.2 0.338 5.850 12 W2PU + 0 2 1 1 T 1501.7 0.337 7.545 12 599 012~~ + + 0 1 1 1 F 1517.3 0.076 3.892 -13 W1UE + + 0 1 1 1 F 1514.3 0.270 5.782 -10 TU W1UE CQ + + 0 1 1 1 F 1514.3 0.270 5.782 -10 TU W1UE CQ + + 0 1 1 1 F 1519.3 0.029 3.421 -10 W2PU + 0 2 1 1 T 1518.3 0.027 5.115 -12 599 016~~ + + 0 1 1 1 F 1516.8 0.371 3.339 -8 W2PU + 0 2 1 1 T 1514.8 0.373 5.037 -7 599 016~~ + + 0 1 1 1 F 1502.7 0.003 2.547 11 AA5AU + + 0 1 1 1 F 1502.7 0.240 1.512 14 W2PU + 0 2 1 1 T 1502.7 0.239 3.207 13 599 012~~ + + 0 1 1 1 F 1518.3 0.032 5.120 -10 W1UE + + 0 1 1 1 F 1515.8 0.253 5.341 -8 599 016~~ + + 0 1 1 1 F 1502.2 0.372 6.732 5 CQ AA5AU CQ + 0 2 2 2 F 1502.7 0.037 23.357 8 CQ AA5AU CQ + 0 3 3 3 F 1503.2 0.321 32.969 3 K9AN + 0 4 3 3 T 1502.7 0.320 34.664 13 599 013~~ + 0 5 4 4 F 1502.7 0.265 43.513 9 TU AA5AU CQ + 0 6 5 5 F 1516.3 0.113 48.025 -9 W1UE + 0 7 6 6 F 1502.7 0.071 53.495 12 W1UE + 0 8 6 6 T 1503.2 0.071 55.191 2 599 014~~ + 0 9 7 7 F 1517.3 0.126 59.062 -11 AA5AU + 0 10 7 7 T 1517.4 0.124 60.756 -11 599 016~~ + 0 11 8 8 F 1502.7 0.352 64.376 3 TU AA5AU CQ + + 0 1 1 1 F 1502.7 0.105 2.225 9 W2PU + 0 2 1 1 T 1502.7 0.104 3.920 8 599 015~~ + + 0 1 1 1 F 1503.2 0.137 2.681 13 TU AA5AU CQ + 0 2 2 2 F 1516.8 0.346 8.826 -9 W1UE + 0 3 3 3 F 1503.2 0.366 16.478 4 W1UE + 0 4 3 3 T 1502.7 0.366 18.174 7 599 016~~ + 0 5 4 4 F 1514.3 0.275 21.475 -7 AA5AU + 0 6 4 4 T 1514.8 0.272 23.168 -9 599 016~~ + 0 7 5 5 F 1503.2 0.395 26.259 9 TU AA5AU CQ + 0 8 6 6 F 1503.2 0.005 34.773 8 K9AN + 0 9 6 6 T 1503.2 0.003 36.467 6 599 017~~ + 0 10 5 6 T 1503.2 0.398 45.766 5 TU AA5AU CQ + 0 11 7 7 F 1502.7 0.042 55.586 12 W1UE + 0 12 7 7 T 1502.7 0.041 57.281 11 599 018~~ + 0 13 8 8 F 1516.8 0.251 61.731 -7 599 016~~ + 0 14 9 9 F 1502.2 0.106 64.554 12 TU AA5AU CQ + + 0 1 1 1 F 1502.2 0.377 5.041 13 WOW~D + 0 2 1 1 T 1502.2 0.377 6.737 15 E~AA5 + 0 3 1 1 T 1502.2 0.377 8.433 12 AU~~~ + 0 4 2 2 F 1517.3 0.181 21.381 -10 CQ W1UE CQ + + 0 1 1 1 F 1515.8 0.301 6.661 -12 CQ W1UE CQ + 0 2 2 2 F 1502.2 0.156 12.876 5 AA5AU + + 0 1 1 1 F 1502.2 0.347 0.771 2 CQ WV4P CQ + 0 2 1 1 T 1502.2 0.351 7.983 14 AA5AU + 0 3 2 2 F 1502.2 0.389 16.501 4 CQ WV4P CQ + + 0 1 1 1 F 1502.2 0.201 3.593 5 CQ WV4P CQ + + 0 1 1 1 F 1502.2 0.301 3.269 3 W1UE + 0 2 1 1 T 1502.2 0.300 4.964 11 599 0003~ + 0 3 2 2 F 1515.8 0.272 8.328 -9 WV4P + 0 4 3 3 F 1502.2 0.051 14.891 14 TU WV4P CQ + + 0 1 1 1 F 1502.2 0.395 5.483 -3 W2PU + 0 2 1 1 T 1502.2 0.393 7.177 16 599 0004~ + + 0 1 1 1 F 1502.2 0.067 2.611 14 TU WV4P CQ + 0 2 2 2 F 1502.7 0.307 5.819 -1 AA5AU + 0 3 3 3 F 1502.2 0.231 11.679 4 AA5AU + 0 4 3 3 T 1502.2 0.231 13.375 16 599 0005~ + 0 5 4 4 F 1502.2 0.380 16.068 12 WV4P + 0 6 4 4 T 1502.2 0.380 17.764 8 599 019~~ + 0 7 5 5 F 1502.2 0.179 24.347 11 TU WV4P CQ + 0 8 6 6 F 1502.2 0.354 26.642 5 U~QTC + 0 9 6 6 T 1502.2 0.353 28.337 15 ~FOR~ + 0 10 6 6 T 1502.2 0.353 30.033 15 ME~?~ + + 0 1 1 1 F 1502.2 0.067 2.611 14 TU WV4P CQ + 0 2 2 2 F 1502.7 0.307 5.819 -1 AA5AU + 0 3 3 3 F 1502.2 0.231 11.679 4 AA5AU + 0 4 3 3 T 1502.2 0.231 13.375 16 599 0005~ + 0 5 4 4 F 1502.2 0.380 16.068 12 WV4P + 0 6 4 4 T 1502.2 0.380 17.764 8 599 019~~ + 0 7 5 5 F 1502.2 0.179 24.347 11 TU WV4P CQ + 0 8 6 6 F 1502.2 0.354 26.642 5 U~QTC + 0 9 6 6 T 1502.2 0.353 28.337 15 ~FOR~ + 0 10 6 6 T 1502.2 0.353 30.033 15 ME~?~ + + 0 1 1 1 F 1502.2 0.185 5.273 11 599 0006~ + + + 0 1 1 1 F 1501.7 0.092 1.788 11 K1JT + 0 2 1 1 T 1501.7 0.092 3.484 17 599 0006~ + + 0 1 1 1 F 1501.7 0.063 3.031 4 TU WV4P CQ + 0 2 2 2 F 1501.7 0.121 11.993 5 599 0007~ + 0 3 3 3 F 1501.7 0.172 15.012 4 W1UE + 0 4 3 3 T 1502.2 0.172 16.708 9 599 0007~ + + 0 1 1 1 F 1503.2 0.240 6.600 5 AA5AU + 0 2 2 2 F 1501.7 0.201 14.617 4 599 0008~ + 0 3 3 3 F 1501.2 0.343 17.727 1 599 0008~ + 0 4 4 4 F 1501.2 0.333 20.261 13 AA5AU + 0 5 4 4 T 1501.7 0.334 21.958 13 599 0008~ + 0 6 5 5 F 1503.7 0.269 24.861 -3 WV4P + 0 7 5 5 T 1503.2 0.270 26.558 4 599 019~~ + 0 8 6 6 F 1501.7 0.261 30.789 2 TU WV4P CQ + + 0 1 1 1 F 1501.7 0.135 3.103 8 W2ZQ + 0 2 1 1 T 1501.2 0.134 4.798 15 599 0009~ + + + + 0 1 1 1 F 1501.2 0.023 2.991 8 W3CCX + 0 2 1 1 T 1501.7 0.023 4.687 14 599 010~~ + + 0 1 1 1 F 1501.7 0.184 2.728 5 TU WV4P CQ + 0 2 2 2 F 1516.8 0.122 7.754 -11 W1UE + 0 3 3 3 F 1501.2 0.124 12.844 4 W1UE + 0 4 3 3 T 1501.2 0.123 14.539 16 599 011~~ + 0 5 4 4 F 1517.8 0.105 17.489 -10 WV4P + 0 6 5 5 F 1501.7 0.307 23.203 13 TU WV4P CQ + + 0 1 1 1 F 1503.2 0.111 10.711 6 CQ AA5AU CQ + + 0 1 1 1 F 1515.8 0.130 6.490 -8 CQ W1UE CQ + 0 2 2 2 F 1501.2 0.199 17.583 2 WV4P + 0 3 3 3 F 1516.8 0.251 23.147 -10 WV4P + 0 4 3 3 T 1518.3 0.254 24.846 -9 599 016~~ + 0 5 4 4 F 1501.2 0.307 29.987 9 TU WV4P CQ + 0 6 5 5 F 1501.2 0.406 37.294 2 599 013~~ + 0 7 6 6 F 1503.7 0.246 49.854 2 AA5AU + 0 8 7 7 F 1517.3 0.007 77.599 -9 W1UE + 0 9 8 8 F 1503.7 0.301 110.541 2 AA5AU + 0 10 9 9 F 1518.8 0.261 117.285 -9 AA5AU + 0 11 9 9 T 1514.3 0.256 118.976 -9 599 017~~ + 0 12 10 10 F 1503.7 0.230 121.918 12 WV4P + 0 13 10 10 T 1503.7 0.230 123.614 13 599 019~~ + 0 14 11 11 F 1516.8 0.353 128.825 -12 TU W1UE CQ + + 0 1 1 1 F 1517.3 0.132 22.604 -13 W1UE + 0 2 2 2 F 1501.2 0.215 38.375 3 I~AM~ + 0 3 2 2 T 1501.2 0.215 40.071 17 USING + 0 4 2 2 T 1501.2 0.215 41.767 16 ~IN~N + 0 5 2 2 T 1501.2 0.215 43.463 16 1MM~R + 0 6 2 2 T 1501.2 0.215 45.159 14 IGHT~ + 0 7 2 2 T 1501.2 0.215 46.855 13 NOW~~ + + 0 1 1 1 F 1501.2 0.019 19.099 14 I~JUS + 0 2 1 1 T 1501.2 0.018 20.794 15 T~TYP + 0 3 1 1 T 1501.2 0.018 22.490 15 ED~FT + 0 4 1 1 T 1501.7 0.018 24.186 9 8~ENT + 0 5 1 1 T 1501.2 0.018 25.882 16 ER~TH + 0 6 1 1 T 1501.2 0.019 27.579 15 EN~CH + 0 7 1 1 T 1501.2 0.019 29.275 15 ANGED + 0 8 1 1 T 1501.2 0.019 30.971 16 ~MODE + 0 9 1 1 T 1501.2 0.019 32.667 15 ,~WOR + 0 10 1 1 T 1501.2 0.019 34.363 11 KS~WE + 0 11 1 1 T 1501.2 0.019 36.059 15 LL~~~ + + 0 1 1 1 F 1501.2 0.263 7.471 9 YES~~ + + 0 1 1 1 F 1516.8 0.271 20.623 -6 W1UE + 0 2 2 2 F 1474.4 0.203 29.035 -10 CQ N9ADG CQ + + 0 1 1 1 F 1503.7 0.219 9.123 11 IM~GO + 0 2 1 1 T 1504.2 0.218 10.818 15 OD~HE + 0 3 1 1 T 1504.2 0.218 12.514 14 RE~DE + 0 4 1 1 T 1504.2 0.218 14.210 15 ~AA5A + 0 5 1 1 T 1504.2 0.218 15.906 16 U~~~~ + 0 6 2 2 F 1519.8 0.037 25.901 -9 GOOD~ + 0 7 2 2 T 1520.8 0.035 27.595 -9 HERE~ + 0 8 3 3 F 1517.8 0.028 29.284 -7 W1UE~ + 0 9 4 4 F 1472.9 0.391 38.975 -9 CQ N9ADG CQ + 0 10 5 5 F 1504.2 0.327 60.111 13 DE~AA + 0 11 5 5 T 1504.2 0.327 61.807 16 5AU~Q + 0 12 5 5 T 1504.2 0.327 63.503 16 RT~~~ + 0 13 6 6 F 1517.3 0.367 66.511 -7 9AN~B + 0 14 6 6 T 1518.3 0.367 68.207 -7 ARELY + 10 15 7 7 F 1983.4 0.260 68.100 -1 CQ N9ADG CQ + 0 16 6 7 T 1515.8 0.365 69.901 -7 ~SHOW + 0 17 6 7 T 1515.8 0.364 71.596 -9 ~ON~W + 0 18 6 7 T 1517.8 0.363 73.291 -6 ATERF + 0 19 6 7 T 1514.8 0.369 74.993 -9 ALL~B + 10 20 8 8 F 1981.9 0.024 74.648 -15 CQ N9ADG CQ + 0 21 6 8 T 1518.3 0.363 76.683 -9 UT~SO + 0 22 6 8 T 1519.3 0.366 78.382 -12 LID~C + 0 23 6 8 T 1515.3 0.366 80.078 -8 OPY~~ + diff --git a/lib/jtty/gen_jttywave.f90 b/lib/jtty/gen_jttywave.f90 new file mode 100644 index 00000000..88c7eafb --- /dev/null +++ b/lib/jtty/gen_jttywave.f90 @@ -0,0 +1,110 @@ +subroutine gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave) + +! Generate JT2 waveform using Gaussian-filtered frequency pulses. + +! Input: integer*4 itone(1:nsym) !Tones for channel symbols +! integer*4 nsym !Number of channel symbols +! integer*4 nsps !Number of samples per symbol +! real*4 bt !BT product for Gaussian smoothing +! real*4 fsample !Sample rate, Hz +! real*4 f0 !Nominal carrier frequency (lowest tone) +! integer*4 icmplx !0 for real waveford, 1 for complex +! integer*4 nwave !Length of output waveform + +! Output: complex*8 cwave(nwave) !Complex waveform +! read*4 wave(nwave) !Real waveform + + parameter(NTAB=65536) + real wave(nwave) + complex cwave(nwave),ctab(0:NTAB-1) + real, allocatable :: pulse(:) + real, allocatable :: dphi(:) + integer itone(nsym) + data fchk0/0.0/ + save pulse,twopi,dt,hmod,fchk0,ctab + + if(nsym.le.0 .or. nwave.le.0) then + nwave=0 + return + endif + + ibt=nint(10*bt) + fchk=nsym+nsps+bt+fsample + if(fchk.ne.fchk0) then !Execute again only when params change + if( allocated(pulse) ) then + deallocate(pulse) + endif + allocate(pulse(1:3*nsps)) + + twopi=8.0*atan(1.0) + dt=1.0/fsample + hmod=1.0 +! Compute the frequency-smoothing pulse + do i=1,3*nsps + tt=(i-1.5*nsps)/real(nsps) + pulse(i)=gfsk_pulse(bt,tt) + enddo + do i=0,NTAB-1 !Tabulate the trig-functiion values + phi=i*twopi/NTAB + ctab(i)=cmplx(cos(phi),sin(phi)) + enddo + fchk0=fchk + endif + +! Compute the smoothed frequency waveform. +! Length = (nsym+2)*nsps samples, first and last symbols extended + + allocate(dphi(0:(nsym+2)*nsps-1)) + + dphi_peak=twopi*hmod/real(nsps) + dphi=0.0 + do j=1,nsym + ib=(j-1)*nsps + ie=ib+3*nsps-1 + dphi(ib:ie) = dphi(ib:ie) + dphi_peak*pulse(1:3*nsps)*itone(j) + enddo + +! Add dummy symbols at beginning and end with tone values equal to 1st and +! last symbol, respectively + + dphi(0:2*nsps-1)=dphi(0:2*nsps-1)+dphi_peak*itone(1)*pulse(nsps+1:3*nsps) + dphi(nsym*nsps:(nsym+2)*nsps-1)=dphi(nsym*nsps:(nsym+2)*nsps-1) + & + dphi_peak*itone(nsym)*pulse(1:2*nsps) + +! Calculate and insert the audio waveform + phi=0.0 + dphi = dphi + twopi*f0*dt !Shift frequency up by f0 + if(icmplx .eq. 0) wave=0. + if(icmplx .ne. 0) cwave=0. !Avoid writing to memory we may not have access to + + k=0 + do j=nsps,nsps+nwave-1 !Don't include dummy symbols + k=k+1 + if(icmplx.eq.0) then + wave(k)=sin(phi) + else + i=min(NTAB-1,int(phi*float(NTAB)/twopi)) + cwave(k)=ctab(i) + endif + phi=modulo(phi+dphi(j),twopi) + enddo + +! Apply envelope shaping to the first and last symbols + nramp=nint(nsps/8.0) + if(icmplx.eq.0) then + wave(1:nramp)=wave(1:nramp) * & + (1.0-cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0 + k1=nsym*nsps-nramp+1 + wave(k1:k1+nramp-1)=wave(k1:k1+nramp-1) * & + (1.0+cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0 + else + cwave(1:nramp)=cwave(1:nramp) * & + (1.0-cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0 + k1=nsym*nsps-nramp+1 + cwave(k1:k1+nramp-1)=cwave(k1:k1+nramp-1) * & + (1.0+cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0 + endif + + deallocate(dphi) + return +end subroutine gen_jttywave diff --git a/lib/jtty/gen_syncwave.f90 b/lib/jtty/gen_syncwave.f90 new file mode 100644 index 00000000..07c0ae43 --- /dev/null +++ b/lib/jtty/gen_syncwave.f90 @@ -0,0 +1,26 @@ +subroutine gen_syncwave(csync,nss) + use jtty_fec, only: is13 ! sync sequence + implicit none + integer, intent(in) :: nss ! samples/symbol at 6000 samples/sec + integer :: i,j,k + real :: twopi, fsample, dt, baud, phi, dphi + complex, intent(out) :: csync(13*nss) + + twopi=8.0*atan(1.0) + fsample = 6000.0 + dt=1.0/fsample + baud=fsample/nss + csync=cmplx(0.,0.) + k=1 + phi=0.0 + do i=1,13 + dphi=twopi*baud*is13(i)*dt + do j=1,nss + csync(k)=cmplx(cos(phi),sin(phi)) + k=k+1 + phi=phi+dphi + enddo + enddo + + return +end subroutine gen_syncwave diff --git a/lib/jtty/genjtty.f90 b/lib/jtty/genjtty.f90 new file mode 100644 index 00000000..80be9c02 --- /dev/null +++ b/lib/jtty/genjtty.f90 @@ -0,0 +1,161 @@ +subroutine genjtty(umsg,itone,nsym) + +! Input: character*80 umsg !User message +! Output: integer*4 itone(1:nsym) !Tones for channel symbols +! integer*4 nsym !Number of channel symbols + + use jtty_mod, only: JTTY_EXCHANGE_UNKNOWN + 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 + call genjtty_profile(umsg,JTTY_EXCHANGE_UNKNOWN,itone,nsym) + + return +end subroutine genjtty + +subroutine genjtty_profile(umsg,exchange_profile,itone,nsym) + + 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 + character(len=34) :: frames(MAX_FRAMES) + integer :: nframes + + nsym=0 + call pack_jtty(umsg,frames,nframes,exchange_profile) + if(nframes.le.0) return + call genjtty_frames(frames,nframes,itone,nsym) +end subroutine genjtty_profile + +subroutine genjtty_atoms(atoms,natoms,itone,nsym) + + use jtty_mod, only: jtty_source_atom,pack_jtty_atoms,MAX_FRAMES + type(jtty_source_atom), intent(in) :: atoms(:) + integer, intent(in) :: natoms + integer, intent(out) :: itone(*) + integer, intent(out) :: nsym + character(len=34) :: frames(MAX_FRAMES) + integer :: nframes + logical :: valid + + call pack_jtty_atoms(atoms,natoms,frames,nframes,valid) + nsym=0 + if(.not.valid) return + call genjtty_frames(frames,nframes,itone,nsym) +end subroutine genjtty_atoms + +subroutine genjtty_frames(frames,nframes,itone,nsym) + + use jtty_fec, only: PAYLOAD_BITS,tbcc_encode,is13 + use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F + implicit none + character(len=34), intent(in) :: frames(*) + integer, intent(in) :: nframes + integer, intent(out) :: itone(*),nsym + integer :: payload(PAYLOAD_BITS),tone_symbols(46),i,ib + + nsym=0 + do i=1,nframes + read(frames(i),'(34i1)') payload + call tbcc_encode(payload,tone_symbols,JTTY_TBCC_PROFILE_1167_1545_80F) + ib=(i-1)*59+1 + itone(ib:ib+12)=is13 + itone(ib+13:ib+58)=tone_symbols + nsym=nsym+59 + enddo +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 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, & + jtty_exch_loc_atom,jtty_class_section_atom,jtty_control_atom, & + jtty_grid4_atom,MAX_FRAMES,JTTY_ENCODE_OK,JTTY_ENCODE_INVALID_DESCRIPTOR, & + JTTY_ENCODE_UNKNOWN_SECTION + type(jtty_source_atom_c), intent(in) :: c_atoms(*) + integer(c_int), value, intent(in) :: natoms + integer(c_int), intent(out) :: itone(*) + integer(c_int), intent(out) :: nsym + integer(c_int), intent(out) :: status + type(jtty_source_atom) :: atoms(MAX_FRAMES) + character(len=13) :: descriptor_text + integer :: i,section_index + logical :: text_valid + + interface + subroutine genjtty_atoms(atoms,natoms,itone,nsym) + use jtty_mod, only: jtty_source_atom + type(jtty_source_atom), intent(in) :: atoms(:) + integer, intent(in) :: natoms + integer, intent(out) :: itone(*) + integer, intent(out) :: nsym + end subroutine genjtty_atoms + end interface + + nsym=0; status=JTTY_ENCODE_INVALID_DESCRIPTOR + if(natoms.lt.1 .or. natoms.gt.MAX_FRAMES) return + do i=1,natoms + if(c_atoms(i)%reserved.ne.0) return + call unpack_descriptor_text(c_atoms(i)%text,descriptor_text,text_valid) + if(.not.text_valid) return + select case(int(c_atoms(i)%kind)) + case(JTTY_ATOM_CALL) + if(c_atoms(i)%role.ne.0 .or. c_atoms(i)%value.ne.0) return + atoms(i)=jtty_call_atom(int(c_atoms(i)%subtype),descriptor_text) + case(JTTY_ATOM_EXCH_NUM) + if(len_trim(descriptor_text).ne.0) return + atoms(i)=jtty_exch_num_atom(int(c_atoms(i)%role), & + int(c_atoms(i)%subtype),int(c_atoms(i)%value)) + case(JTTY_ATOM_EXCH_LOC) + if(c_atoms(i)%value.ne.0) return + atoms(i)=jtty_exch_loc_atom(int(c_atoms(i)%role), & + int(c_atoms(i)%subtype),descriptor_text) + case(JTTY_ATOM_EXCH_PAIR) + 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 + status=JTTY_ENCODE_UNKNOWN_SECTION + return + endif + atoms(i)=jtty_class_section_atom(int(c_atoms(i)%value), & + char(ichar('A')+int(c_atoms(i)%role)),section_index) + case(JTTY_ATOM_CONTROL) + if(c_atoms(i)%role.ne.0 .or. c_atoms(i)%value.ne.0 .or. & + len_trim(descriptor_text).ne.0) return + atoms(i)=jtty_control_atom(int(c_atoms(i)%subtype)) + case(JTTY_ATOM_GRID4) + if(c_atoms(i)%subtype.ne.0 .or. c_atoms(i)%value.ne.0) return + atoms(i)=jtty_grid4_atom(int(c_atoms(i)%role),descriptor_text) + case default + return + end select + enddo + call genjtty_atoms(atoms,int(natoms),itone,nsym) + if(nsym.gt.0) status=JTTY_ENCODE_OK + +contains + + subroutine unpack_descriptor_text(c_text,text,text_valid) + character(kind=c_char), intent(in) :: c_text(9) + character(len=13), intent(out) :: text + logical, intent(out) :: text_valid + integer :: j + + text='' + text_valid=.false. + do j=1,9 + if(c_text(j).eq.c_null_char) then + text_valid=.true. + return + endif + if(j.gt.8) return + text(j:j)=c_text(j) + enddo + end subroutine unpack_descriptor_text +end subroutine genjtty_atoms_c diff --git a/lib/jtty/jtty.f90 b/lib/jtty/jtty.f90 new file mode 100644 index 00000000..a8ac65c9 --- /dev/null +++ b/lib/jtty/jtty.f90 @@ -0,0 +1,60 @@ +program jtty + +! Basic implementation of the JTTY protocol for use from the command line. + + use jtty_mod + use jtty_fec + use jttycom + integer jttyaudio !C function for JTTY portaudio + character*12 arg + data idevin/-1/,idevout/-1/ + + narg=iargc() + if(narg.ne.7) then + print*,'Usage: jtty MyCall HisCall devin devout fTol nQSO ndebug' + print*,'Example: jtty K1JT K9AN 2 5 100 123 0' + call padevsub(idevin,idevout) !Configure the portaudio devices + go to 999 + endif + call getarg(1,mycall) + call getarg(2,hiscall) + call getarg(3,arg) + read(arg,*) idevin + call getarg(4,arg) + read(arg,*) idevout + call getarg(5,arg) + read(arg,*) ftol + call getarg(6,arg) + read(arg,*) nQSO + call getarg(7,arg) + read(arg,*) ndebug + + call padevsub(idevin,idevout) !Configure the portaudio devices + + nright=1 !Use right channel for audio input + iwrite=0 !Set buffer pointer + nfsample=12000 !Sample rate (Hz) + ngo=1 !Set to 0 to stop program + npabuf=384 !PortAudio: 384 frames per buffer, 31.25 baud, 0.032 s + ntxok=0 + ntransmitting=0 + ltx=.false. + lrx=.false. + autoseq=.false. + QSO_in_progress=.false. + ntxed=0 + nwave=59*384 + txmsg='' + ftx=1500.0 + +! Start the input and output audio streams. Note that in normal use this call +! does not return until an error or end-of-program occurs. + + ierr=jttyaudio(idevin,idevout,npabuf,nright,y1,y2,NMAX,iwrite,itx, & + iwave,nwave+3*npabuf,nfsample,nTxOK,nTransmitting,ngo,ndebug) + + if(ierr.ne.0) then + print*,'Error',ierr,' starting audio input or output.' + endif + +999 end program jtty diff --git a/lib/jtty/jtty.ini b/lib/jtty/jtty.ini new file mode 100644 index 00000000..cecea728 --- /dev/null +++ b/lib/jtty/jtty.ini @@ -0,0 +1,3 @@ +K1JT FN20 2 5 0 NJ +K1JT FN20 1 6 0 NJ +MyCall MyGrid AudioIn AudioOut PTTport Exch diff --git a/lib/jtty/jtty_block_pow.f90 b/lib/jtty/jtty_block_pow.f90 new file mode 100644 index 00000000..795e8559 --- /dev/null +++ b/lib/jtty/jtty_block_pow.f90 @@ -0,0 +1,101 @@ +subroutine jtty_block_pow(z, nsym, iblock, pow_block) + +! Coherent block detection for JTTY's 4-FSK symbols. Cascades the already- +! computed blocksize-1 complex correlator outputs z(0:3,1:nsym) (see +! jtty_mdecode.f90's decode_and_merge) into coherent blocksize-2 and, if +! iblock==4, blocksize-4 candidate-sequence sums, then reduces back to a +! max-over-consistent-sequences per-tone/per-position array shaped like the +! ordinary single-symbol pow(0:3,1:nsym), ready to feed directly into +! tbcc_wava_fsk_decode's tone_energies argument -- no changes needed there. +! +! Combining operator is plain addition at every cascade level, with no +! rotation/derotation term. This is specific to JTTY's tone grid: ctones() +! is built with dphi=i*TWOPI/nss, so one full symbol window advances tone +! i's phase by exactly i*TWOPI -- an exact multiple of 2*pi for all four +! tones -- unlike e.g. FST4's centered tone grid (get_fst4_bitmetrics.f90), +! which picks up a guaranteed 180-degree flip every symbol and so needs a +! subtraction at its first cascade step. +! +! nsym is expected even (NCHAN_SYM=46). The L=2 cascade (nsym/2 pairs) is +! always built first and used directly when iblock==2. When iblock==4, +! pairs are grouped by two; if the pair count is odd, the last pair is left +! at its L=2 reduction instead of being folded into an L=4 group -- this +! costs nothing extra, since the L=2 cascade already covers every position. + + implicit none + integer, intent(in) :: nsym ! NCHAN_SYM (46) + integer, intent(in) :: iblock ! 2 or 4 + complex, intent(in) :: z(0:3,nsym) + real, intent(out) :: pow_block(0:3,nsym) + + complex :: c2(0:3,0:3,nsym/2) + complex :: s4 + integer :: npair, nquad, ip, iq, ipL, ipR + integer :: posA, posB, pos1, pos2, pos3, pos4 + integer :: ta, tb, tc, td + real :: p2 + + npair = nsym/2 + + do ip=1,npair + posA=2*ip-1 + posB=2*ip + do ta=0,3 + do tb=0,3 + c2(ta,tb,ip) = z(ta,posA) + z(tb,posB) + enddo + enddo + enddo + +! L=2 reduction, always computed: used directly for iblock==2, and as the +! trailing-remainder fallback for iblock==4. + do ip=1,npair + posA=2*ip-1 + posB=2*ip + do ta=0,3 + p2 = real(c2(ta,0,ip)*conjg(c2(ta,0,ip))) + p2 = max(p2, real(c2(ta,1,ip)*conjg(c2(ta,1,ip)))) + p2 = max(p2, real(c2(ta,2,ip)*conjg(c2(ta,2,ip)))) + p2 = max(p2, real(c2(ta,3,ip)*conjg(c2(ta,3,ip)))) + pow_block(ta,posA) = p2/2.0 + enddo + do tb=0,3 + p2 = real(c2(0,tb,ip)*conjg(c2(0,tb,ip))) + p2 = max(p2, real(c2(1,tb,ip)*conjg(c2(1,tb,ip)))) + p2 = max(p2, real(c2(2,tb,ip)*conjg(c2(2,tb,ip)))) + p2 = max(p2, real(c2(3,tb,ip)*conjg(c2(3,tb,ip)))) + pow_block(tb,posB) = p2/2.0 + enddo + enddo + + if(iblock.eq.4) then + nquad = npair/2 + do iq=1,nquad + ipL=2*iq-1 + ipR=2*iq + pos1=2*ipL-1 + pos2=2*ipL + pos3=2*ipR-1 + pos4=2*ipR + pow_block(:,pos1)=0.0 + pow_block(:,pos2)=0.0 + pow_block(:,pos3)=0.0 + pow_block(:,pos4)=0.0 + do ta=0,3 + do tb=0,3 + do tc=0,3 + do td=0,3 + s4 = c2(ta,tb,ipL) + c2(tc,td,ipR) + p2 = real(s4*conjg(s4))/4.0 + pow_block(ta,pos1) = max(pow_block(ta,pos1), p2) + pow_block(tb,pos2) = max(pow_block(tb,pos2), p2) + pow_block(tc,pos3) = max(pow_block(tc,pos3), p2) + pow_block(td,pos4) = max(pow_block(td,pos4), p2) + enddo + enddo + enddo + enddo + enddo + endif + +end subroutine jtty_block_pow diff --git a/lib/jtty/jtty_codewords.f90 b/lib/jtty/jtty_codewords.f90 new file mode 100644 index 00000000..da0f3162 --- /dev/null +++ b/lib/jtty/jtty_codewords.f90 @@ -0,0 +1,16 @@ + integer cw(0:63) !Codewords for the RS(7,2) code + data cw/o'1243675',o'2436751',o'3675124',o'4367512',o'5124367', & + o'6751243',o'7512436',o'0352764',o'3527640',o'2764035', & !10 + o'5276403',o'4035276',o'7640352',o'6403527',o'3061457', & + o'0614573',o'1457306',o'6145730',o'7306145',o'4573061', & !20 + o'5730614',o'2170546',o'1705462',o'0546217',o'7054621', & + o'6217054',o'5462170',o'4621705',o'5607231',o'6072315', & !30 + o'7231560',o'0723156',o'1560723',o'2315607',o'3156072', & + o'4716320',o'7163204',o'6320471',o'1632047',o'0471632', & !40 + o'3204716',o'2047163',o'7425013',o'4250137',o'5013742', & + o'2501374',o'3742501',o'0137425',o'1374250',o'6534102', & !50 + o'5341026',o'4102653',o'3410265',o'2653410',o'1026534', & + o'0265341',o'0000000',o'1111111',o'2222222',o'3333333', & !60 + o'4444444',o'5555555',o'6666666',o'7777777'/ + +! The source alphabet is defined by JTTY_ALPHABET in jtty_mod.f90. diff --git a/lib/jtty/jtty_decode.f90 b/lib/jtty/jtty_decode.f90 new file mode 100644 index 00000000..357c687c --- /dev/null +++ b/lib/jtty/jtty_decode.f90 @@ -0,0 +1,192 @@ +subroutine jtty_decode(iwave,nchunk,nsps,f0,ftol,smin,synced,xdt,f1,snr,decoded,success,nharderrors,nsync,dmin) +! +! note nsps is samples per symbol at 12000 s^-1 sample rate. +! + use jtty_mod + use jtty_fec + use jtty_tbcc_decoder, only: jtty_tbcc_decode + use jtty_payload_correlators, only: jtty_payload_correlator, & + jtty_payload_correlator_prepare, jtty_correlate_payload_symbols + implicit none + character*80, intent(out) :: decoded + character*34 :: c32(MAX_FRAMES) + integer :: final_payload(PAYLOAD_BITS) + integer*2, intent(in) :: iwave(nchunk) + integer :: i,j,i0,ja,jb + integer, intent(in) :: nchunk,nsps !size of chunk, nsps at 12000 Sa/s + integer :: nchunk6,nana !size of chunk, nana at 6000 Sa/s + integer :: nframe6 !size of frame at 6000 Sa/s + integer, save :: nsps0=-999 + integer, save :: nfft,nh2,nss + type(jtty_payload_correlator), save :: payload_correlator + complex :: zsym(0:3,TOTAL_K),zhalf(0:3,TOTAL_K) + integer :: iloc(1) + integer :: irxsync(13) + integer, intent(out) :: nharderrors,nsync + real :: fsample + real :: spk,fpk,pa,pt,pn + real :: fbest,xdtbest,sbest + real, allocatable :: s(:), sm(:), s0(:) + real :: a(3) + real :: pow(0:3) + real, save :: twopi,baud,dt + real :: phi,dphi,df2 + real :: ssnr,db + real, intent(in) :: f0,ftol,smin + real, intent(out) :: dmin + real, intent(inout) :: xdt,f1,snr + complex, allocatable :: c(:) + complex, allocatable :: c0(:) + complex, allocatable :: c1(:) + complex, allocatable,save :: csync(:) !Waveform for sync at 6000 s^-1 sample rate + complex, allocatable,save :: ctones(:,:) + complex :: z + logical, intent(out) :: success + logical, intent(inout) :: synced + logical :: source_valid + + success=.false. + decoded=' ' + nharderrors=-1 + nsync=0 + dmin=0.0 + if(sum(abs(iwave)).eq.0) return + + if(nsps.ne.nsps0) then + nsps0=nsps + nss=nsps/2 ! samples per symbol at 6000 sa/s + nfft=8192 ! FFT size for sync search, gives df2=0.732 + nh2=nfft/2 ! spectrum size for sync search + +! allocate saved arrays + if(allocated(csync)) deallocate(csync) + allocate(csync(0:13*nss-1)) + if(allocated(ctones)) deallocate(ctones) + allocate(ctones(0:nss-1,0:3)) + +! Generate complex waveform for sync + twopi=8.0*atan(1.0) + baud=6000.0/real(nss) !31.25 for nss=192 + dt=1/6000.0 + call gen_syncwave(csync,nss) + + do i=0,3 + phi=0.0 + dphi=twopi*i*baud*dt + do j=0,nss-1 + ctones(j,i)=cmplx(cos(phi),sin(phi)) + phi=phi+dphi + enddo + enddo + endif + + nchunk6=nchunk/2 ! chunk size at 6000 Sa/s + nframe6=59*nss ! frame size at 6000 Sa/s + +! make size of c0 next power of 2 larger than nchunk + nana = 2**nint(log(real(nchunk))/log(2.0)+0.5) + allocate(c0(0:nana-1)) + +! convert integer samples at 12K Sa/s to complex analytic signal at 6K Sa/s + call ana64a(iwave,nchunk,c0,nana) + c0(nchunk6:)=0. + + allocate(c(0:nfft-1)) ! + allocate(c1(0:nchunk6-1)) + allocate(s(0:nh2)) + allocate(sm(0:nh2)) + allocate(s0(0:nh2)) + + fsample=6000.0 + dt=1.0/fsample + df2=fsample/nfft + decoded=' ' + + if(.not.synced) then + sbest=0. + fbest=0. + xdtbest=0. + fpk=0. + ja=(f0-ftol)/df2 + jb=(f0+ftol)/df2 + if(ja .lt. 3) ja=3 + if(jb .gt. nh2-2) jb=nh2-2 !Keep s(j-2:j+2) within s(0:nh2) + do i0=0,nframe6/4,12 !Search over quarter-frame segments + xdt=i0*dt + c(0:13*nss-1)=conjg(csync(0:13*nss-1))*c0(i0:i0+13*nss-1) + c(13*nss:)=0. + call four2a(c,nfft,1,-1,1) !Compute the sync-shifted spectrum + spk=0. + do j=ja-2,jb+2 + s(j)=real(c(j))**2 + aimag(c(j))**2 + enddo + do j=ja,jb + sm(j)=s(j-2)+2*s(j-1)+3*s(j)+2*s(j+1)+s(j+2) + if(sm(j).gt.spk) then + spk=sm(j) + fpk=j*df2 + xdt=i0*dt + endif + enddo + if(spk.gt.sbest) then + s0=sm + sbest=spk + fbest=fpk + xdtbest=xdt + endif + enddo + + xdt=xdtbest + snr=db(sbest) + f1=fbest + +! call jtty_peakup(c0,c1,csync,xdtbest,fbest,xdt,f1,snr) + endif + + a=0. + a(1)=-f1 !Shift peak to zero frequency + call twkfreq(c0,c1,nchunk6,6000.0,a) + + pt=0. + pa=0. + do j=1,13 ! find tone powers for sync symbols + i0=nint(xdt/dt) + (j-1)*nss + if(i0+nss.gt.nchunk6) exit + + do i=0,3 + c(0:nss-1)=conjg(ctones(0:nss-1,i))*c1(i0:i0+nss-1) + z=sum(c(0:nss-1)) + pow(i)=abs(z)**2 + enddo + iloc=maxloc(pow)-1 + irxsync(j)=iloc(1) + pt=pt+pow(is13(j)) !signal plus noise + pa=pa+sum(pow) !signal plus 4*noise + enddo + ssnr=-99.0 + pn=(pa-pt)/3.0 + if(pn.gt.0.) ssnr=db(pt/pn) ! pt/pn instead of pt/pn-1 to avoid negative snr estimates + snr=ssnr ! replace the snr derived from sync-shifted spectrum + nsync=count(is13.eq.irxsync) ! nsync is the number of correct hard-decoded sync tones. + + if(nsync .gt. 6 .and. snr .gt. smin) go to 10 + return + +10 synced=.true. + + + call jtty_payload_correlator_prepare(payload_correlator,nss) + call jtty_correlate_payload_symbols(payload_correlator,c1, & + nint(xdt/dt)+13*nss,zsym,zhalf) + call jtty_tbcc_decode(zsym,zhalf,final_payload,success) + nharderrors=-1 + if(success) nharderrors=0 + + decoded=' ' + if( success ) then + write(c32(1),'(34i1)') final_payload + call unpack_jtty(c32,1,decoded,source_valid=source_valid) + if(.not.source_valid) success=.false. + endif + return +end subroutine jtty_decode diff --git a/lib/jtty/jtty_design.md b/lib/jtty/jtty_design.md new file mode 100644 index 00000000..9448c8db --- /dev/null +++ b/lib/jtty/jtty_design.md @@ -0,0 +1,145 @@ +# JTTY Design + +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 + +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. + +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. + +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. + +## 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. + +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. + +## 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. + +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 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. + +`sjtty` defaults to Unknown. An optional leading `--exchange-profile=unknown|field-day|rtty-roundup` selects the profile for either its one-message packing invocation or its eight-argument waveform invocation. Invalid profile values are errors. For example, `sjtty --exchange-profile=rtty-roundup "599 001"` selects the one-frame serial interpretation. + +## 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 + +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. + +| 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. + +`%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. + +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. + +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). + +## Contest exchange example + +The native defaults keep the usual run sequence compact while retaining explicit meanings: + +| Run station | S+P stations | Frames | +| --- | --- | ---: | +| `CQ KA1ABC CQ` | | 1 | +| | `WB9XYZ` | 1 | +| | `JA6DEF` | 1 | +| `WB9XYZ 599 101` | | 2 | +| | `599 057` | 1 | +| `TU NOW JA6DEF 599 102` | | 2 | +| | *(no decode)* | 1 | +| `JA6DEF AGN?` | | 1 | +| | `599 292` | 1 | +| `TU KA1ABC CQ` | | 1 | + +Typed exchanges such as `599 05 NWT`, `599 156 1749`, and `1D EMA` fit one STRUCT30 frame. Automatic text packing recognizes `1D EMA`, but does not infer the zone/location or serial/time meanings of the other two examples. Strong FEC makes repeated visible fields unnecessary; when RF redundancy is desired, repeating the protected atom provides another independent synchronization, FEC, and CRC opportunity. + +These frame counts apply to ordinary text, without a native template or contest profile: + +| Input | Frames | Reason | +| --- | ---: | --- | +| `CQ K1ABC CQ` or `CQ KA1ABC CQ` | 1 | CQ call atom | +| `WB9XYZ` | 1 | Call atom | +| `WB9XYZ TU CQ KA1ABC CQ` | 2 | Two call atoms | +| `WB9XYZ 599 123` | 2 | Call and generic numeric exchange | +| `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` or `599 05` | 2 | No numeric kind is inferred to preserve leading zeros | +| `599 BRUCE` | 2 | No current generic five-character exchange atom | + +With the RTTY Roundup profile, `599 001` takes one frame and `K1ABC 599 001` takes two. `599 05` becomes `599 005` in one frame. The other examples retain their frame counts, although `599 123` and `599 MA` use typed SERIAL and STATE_PROVINCE atoms instead of generic atoms. diff --git a/lib/jtty/jtty_design.txt b/lib/jtty/jtty_design.txt new file mode 100644 index 00000000..b117e77c --- /dev/null +++ b/lib/jtty/jtty_design.txt @@ -0,0 +1,231 @@ +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_fec_mod.f90 b/lib/jtty/jtty_fec_mod.f90 new file mode 100644 index 00000000..b73a3e62 --- /dev/null +++ b/lib/jtty/jtty_fec_mod.f90 @@ -0,0 +1,19 @@ +module jtty_fec + +! JTTY's forward-error-correction configuration: the 13-symbol 4-FSK sync +! sequence and established TBCC/outer-check code. +! The profile and codec APIs are re-exported so JTTY callers need one module. + + use jtty_tbcc_code_profiles + use tbcc + +! The ACF of this 4FSK sync sequence has peak sidelobe level of 2/13 +! and 46 such values over the entire 25x7 lag space + integer :: is13(13) = [0,2,2,3,0,0,3,2,1,3,1,2,0] + +! Bit 33 of the 34-bit payload (see jtty_mod.f90's pack_jtty/unpack_jtty) is +! reserved-zero in the current protocol. Assigning it requires a coordinated +! protocol revision. Bit 34 is the "last frame of this message" flag. + integer, parameter :: JTTY_RESERVED_BIT = 33 + +end module jtty_fec diff --git a/lib/jtty/jtty_mdecode.f90 b/lib/jtty/jtty_mdecode.f90 new file mode 100644 index 00000000..4f77d51f --- /dev/null +++ b/lib/jtty/jtty_mdecode.f90 @@ -0,0 +1,1228 @@ +module jtty_mdec + + use iso_fortran_env, only: int64 + 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 + use jtty_fec, only: PAYLOAD_BITS, TOTAL_K, tbcc_encode + use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F + use jtty_tbcc_decoder, only: jtty_tbcc_decode + use jtty_payload_correlators, only: jtty_payload_correlator, & + jtty_payload_correlator_prepare, jtty_correlate_payload_symbols + + 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 :: snrdb = 0.0 !SNR of decoded frame + character(len=80) :: decoded = '' + logical :: trailing_sep = .false. !decoded ends with an implicit separator column + logical :: is_last_frame = .false. !this frame had the "last frame of message" bit set + end type decode + + type :: message_assembly + integer(int64) :: message_id = 0_int64 + real :: f1 = 0.0 + real :: tsync = 0.0 + real :: start_tsync = 0.0 + integer :: k = 0 + character(len=80) :: decoded = '' + logical :: trailing_sep = .false. + end type message_assembly + + type :: frame_fingerprint + real :: f1 = 0.0 + real :: tsync = 0.0 + end type frame_fingerprint + + type :: message_update + integer(int64) :: message_id = 0_int64 + real :: f1 = 0.0 + real :: start_tsync = 0.0 + character(len=80) :: decoded = '' + logical :: complete = .false. + end type message_update + + integer, parameter :: MAX_DECODES = 100 + integer, parameter :: MAX_ACTIVE_MESSAGES = 30 + integer, parameter :: MAX_RECENT_FRAMES = MAX_ACTIVE_MESSAGES*MAX_FRAMES + integer, parameter :: MAX_CONTINUATION_GAP = 3 + integer, parameter :: MAX_RETRO_STEPS = 3 + real, parameter :: FRAME_HISTORY_TIME_TOLERANCE = 0.05 + real, parameter :: FRAME_HISTORY_FREQ_TOLERANCE = 3.0 + real, parameter :: NEAR_SIMULTANEOUS_FREQ_TOLERANCE = 12.0 + real, parameter :: CONTINUATION_TIME_TOLERANCE = 0.1 + integer :: ndecodes = 0 + integer :: nactive = 0 + integer :: nrecent = 0 + integer :: npending = 0 + integer :: pending_first = 1 + integer(int64) :: next_message_id = 1_int64 + type(message_assembly) :: active_messages(MAX_ACTIVE_MESSAGES) + type(frame_fingerprint) :: recent_frames(MAX_RECENT_FRAMES) + type(message_update), allocatable :: pending_updates(:) + +! Cross-call "retro re-sweep" plumbing (see jtty_mdecode_step): interferer_* +! requests a pre-search subtraction; nsubtracted/subtracted_* report this +! call's own subtractions back out. + integer, parameter :: MAX_SUBTRACTED = 16 + logical :: interferer_pending = .false. + real :: interferer_f1 = 0.0 + real :: interferer_tsync = 0.0 + integer :: interferer_payload(PAYLOAD_BITS) = 0 + integer :: nsubtracted = 0 + real :: subtracted_f1(MAX_SUBTRACTED) = 0.0 + real :: subtracted_tsync(MAX_SUBTRACTED) = 0.0 + 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 + integer, private :: sync_chirp_output_count=0 + type, private :: sync_fft_cache + type(c_ptr) :: forward=c_null_ptr + type(c_ptr) :: backward=c_null_ptr + type(c_ptr) :: input_storage=c_null_ptr + type(c_ptr) :: spectrum_storage=c_null_ptr + type(c_ptr) :: inverse_storage=c_null_ptr + complex(c_float_complex), pointer, contiguous :: input(:)=>null() + complex(c_float_complex), pointer, contiguous :: spectrum(:)=>null() + complex(c_float_complex), pointer, contiguous :: inverse(:)=>null() + end type sync_fft_cache + 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) + +contains + + subroutine release_sync_fft_cache(cache) + use fftw3, only: fftwf_destroy_plan,fftwf_free + type(sync_fft_cache), intent(inout) :: cache + + !$omp critical(fftw) + if(c_associated(cache%forward)) call fftwf_destroy_plan(cache%forward) + if(c_associated(cache%backward)) call fftwf_destroy_plan(cache%backward) + !$omp end critical(fftw) + cache%forward=c_null_ptr + cache%backward=c_null_ptr + nullify(cache%input,cache%spectrum,cache%inverse) + if(c_associated(cache%input_storage)) call fftwf_free(cache%input_storage) + if(c_associated(cache%spectrum_storage)) call fftwf_free(cache%spectrum_storage) + if(c_associated(cache%inverse_storage)) call fftwf_free(cache%inverse_storage) + cache%input_storage=c_null_ptr + cache%spectrum_storage=c_null_ptr + cache%inverse_storage=c_null_ptr + end subroutine release_sync_fft_cache + + logical function allocate_sync_fft_buffer(nfft,storage,buffer) + use fftw3, only: fftwf_alloc_complex + integer, intent(in) :: nfft + type(c_ptr), intent(out) :: storage + complex(c_float_complex), pointer, contiguous, intent(out) :: buffer(:) + complex(c_float_complex), pointer, contiguous :: one_based_buffer(:) + + storage=fftwf_alloc_complex(int(nfft,c_size_t)) + allocate_sync_fft_buffer=c_associated(storage) + if(.not.allocate_sync_fft_buffer) return + call c_f_pointer(storage,one_based_buffer,[nfft]) + buffer(0:nfft-1)=>one_based_buffer + end function allocate_sync_fft_buffer + + logical function ensure_sync_fft_cache(nfft,needs_backward,fft_order) + use fftw3, only: fftwf_plan_dft_1d,FFTW_FORWARD,FFTW_BACKWARD, & + FFTW_MEASURE,FFTW_PRESERVE_INPUT,fftwf_free + integer, intent(in) :: nfft + logical, intent(in) :: needs_backward + integer, intent(out) :: fft_order + + ensure_sync_fft_cache=.false. + fft_order=0 + if(nfft.le.0) return + fft_order=trailz(nfft) + if(fft_order.lt.MIN_SYNC_FFT_ORDER .or. & + fft_order.gt.MAX_SYNC_FFT_ORDER) then + fft_order=0 + return + endif + if(2**fft_order.ne.nfft) then + fft_order=0 + return + endif + + if(.not.c_associated(sync_fft_caches(fft_order)%forward)) then + if(.not.allocate_sync_fft_buffer(nfft, & + sync_fft_caches(fft_order)%input_storage, & + sync_fft_caches(fft_order)%input)) then + fft_order=0 + return + endif + if(.not.allocate_sync_fft_buffer(nfft, & + sync_fft_caches(fft_order)%spectrum_storage, & + sync_fft_caches(fft_order)%spectrum)) then + call release_sync_fft_cache(sync_fft_caches(fft_order)) + fft_order=0 + return + endif + !$omp critical(fftw) + sync_fft_caches(fft_order)%forward=fftwf_plan_dft_1d(nfft, & + sync_fft_caches(fft_order)%input, & + sync_fft_caches(fft_order)%spectrum,FFTW_FORWARD, & + ior(FFTW_MEASURE,FFTW_PRESERVE_INPUT)) + !$omp end critical(fftw) + if(.not.c_associated(sync_fft_caches(fft_order)%forward)) then + call release_sync_fft_cache(sync_fft_caches(fft_order)) + fft_order=0 + return + endif + endif + + if(needs_backward .and. & + .not.c_associated(sync_fft_caches(fft_order)%backward)) then + if(.not.allocate_sync_fft_buffer(nfft, & + sync_fft_caches(fft_order)%inverse_storage, & + sync_fft_caches(fft_order)%inverse)) then + fft_order=0 + return + endif + !$omp critical(fftw) + sync_fft_caches(fft_order)%backward=fftwf_plan_dft_1d(nfft, & + sync_fft_caches(fft_order)%spectrum, & + sync_fft_caches(fft_order)%inverse,FFTW_BACKWARD,FFTW_MEASURE) + !$omp end critical(fftw) + if(.not.c_associated(sync_fft_caches(fft_order)%backward)) then + nullify(sync_fft_caches(fft_order)%inverse) + call fftwf_free(sync_fft_caches(fft_order)%inverse_storage) + sync_fft_caches(fft_order)%inverse_storage=c_null_ptr + fft_order=0 + return + endif + endif + + ensure_sync_fft_cache=c_associated(sync_fft_caches(fft_order)%forward) + if(needs_backward) ensure_sync_fft_cache=ensure_sync_fft_cache .and. & + c_associated(sync_fft_caches(fft_order)%backward) + if(.not.ensure_sync_fft_cache) then + call release_sync_fft_cache(sync_fft_caches(fft_order)) + fft_order=0 + endif + end function ensure_sync_fft_cache + + subroutine jtty_release_fft_resources() bind(C,name='jtty_release_fft_resources') + integer :: index + + do index=MIN_SYNC_FFT_ORDER,MAX_SYNC_FFT_ORDER + call release_sync_fft_cache(sync_fft_caches(index)) + enddo + if(allocated(sync_chirp_weights)) deallocate(sync_chirp_weights) + if(allocated(sync_chirp_kernel)) deallocate(sync_chirp_kernel) + sync_chirp_samples=0 + sync_chirp_first_bin=-1 + sync_chirp_output_count=0 + end subroutine jtty_release_fft_resources + + subroutine reset_decode_search_state() + nactive=0 + nrecent=0 + end subroutine reset_decode_search_state + + subroutine discard_pending_updates() + npending=0 + pending_first=1 + 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 + + 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 + + same_recent_frame=abs(f1_a-f1_b).lt.NEAR_SIMULTANEOUS_FREQ_TOLERANCE .and. & + abs(tsync_a-tsync_b).lt.FRAME_HISTORY_TIME_TOLERANCE + end function same_recent_frame + + pure function display_message_text(decoded) result(msg) + character(len=*), intent(in) :: decoded + character(len=80) :: msg + integer :: i + + msg=decoded + do i=1,len_trim(msg)-4 + if(msg(i:i+4).eq.'~~~~~') msg(i:i+4)=' ... ' + enddo + do i=1,len_trim(msg) + if(msg(i:i).eq.'~') msg(i:i)=' ' + enddo + if(msg(1:1).eq.' ') msg=trim(msg(2:)) + end function display_message_text + + logical function is_recent_frame(candidate) + type(decode), intent(in) :: candidate + integer :: i + + is_recent_frame=.false. + do i=1,nrecent + if(same_recent_frame(candidate%f1,candidate%tsync,recent_frames(i)%f1, & + recent_frames(i)%tsync)) then + is_recent_frame=.true. + return + endif + enddo + end function is_recent_frame + + subroutine remember_recent_frame(candidate) + type(decode), intent(in) :: candidate + + if(nrecent.ge.MAX_RECENT_FRAMES) then + ! Duplicate history must never prevent an otherwise valid decode. + recent_frames(1:MAX_RECENT_FRAMES-1)=recent_frames(2:MAX_RECENT_FRAMES) + else + nrecent=nrecent+1 + endif + recent_frames(nrecent)%f1=candidate%f1 + recent_frames(nrecent)%tsync=candidate%tsync + end subroutine remember_recent_frame + + subroutine queue_message_update(message,complete) + type(message_assembly), intent(in) :: message + logical, intent(in) :: complete + type(message_update), allocatable :: grown(:) + integer :: i,index,new_capacity + + do i=0,npending-1 + index=pending_first+i + if(pending_updates(index)%message_id.eq.message%message_id) then + pending_updates(index)%f1=message%f1 + pending_updates(index)%decoded=message%decoded + pending_updates(index)%complete=complete + return + endif + enddo + + if(.not.allocated(pending_updates)) then + allocate(pending_updates(MAX_ACTIVE_MESSAGES)) + else if(pending_first+npending.gt.size(pending_updates)) then + if(npending.lt.size(pending_updates)) then + pending_updates(1:npending)= & + pending_updates(pending_first:pending_first+npending-1) + else + new_capacity=2*npending + allocate(grown(new_capacity)) + grown(1:npending)=pending_updates(pending_first:pending_first+npending-1) + call move_alloc(grown,pending_updates) + endif + pending_first=1 + endif + npending=npending+1 + index=pending_first+npending-1 + 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)%decoded=message%decoded + pending_updates(index)%complete=complete + end subroutine queue_message_update + + subroutine remove_active_message(index) + integer, intent(in) :: index + + if(index.lt.1 .or. index.gt.nactive) return + if(index.lt.nactive) active_messages(index)=active_messages(nactive) + nactive=nactive-1 + end subroutine remove_active_message + + subroutine start_message(candidate,message,accepted) + type(decode), intent(in) :: candidate + type(message_assembly), intent(out) :: message + logical, intent(out) :: accepted + + message=message_assembly() + accepted=.false. + if(.not.candidate%is_last_frame .and. nactive.ge.MAX_ACTIVE_MESSAGES) return + call remember_recent_frame(candidate) + + message%message_id=next_message_id + message%f1=candidate%f1 + message%tsync=candidate%tsync + message%start_tsync=candidate%tsync + message%decoded=candidate%decoded + if(message%decoded(1:4).eq.'599 ') & + message%decoded='~'//trim(message%decoded) + message%k=len_trim(message%decoded) + message%trailing_sep=candidate%trailing_sep + + next_message_id=next_message_id+1_int64 + call queue_message_update(message,candidate%is_last_frame) + if(.not.candidate%is_last_frame) then + nactive=nactive+1 + active_messages(nactive)=message + endif + accepted=.true. + end subroutine start_message + + subroutine append_active_message(index,candidate,nframes_gap,message,accepted) + integer, intent(in) :: index,nframes_gap + type(decode), intent(in) :: candidate + type(message_assembly), intent(out) :: message + logical, intent(out) :: accepted + integer :: k,kz,n,nchar,nstart + + message=message_assembly() + accepted=.false. + if(index.lt.1 .or. index.gt.nactive) return + call remember_recent_frame(candidate) + + k=active_messages(index)%k + n=len_trim(candidate%decoded) + if(nframes_gap.gt.1) then + nstart=1 + if(n.ge.1) then + if(candidate%decoded(1:1).eq.'~') nstart=2 + endif + kz=min(k+5+(n-nstart+1),80) + nchar=max(kz-k-5,0) + active_messages(index)%decoded=trim(active_messages(index)%decoded)// & + '~~~~~'//candidate%decoded(nstart:nstart+nchar-1) + active_messages(index)%k=k+5+nchar + else + kz=min(k+n,80) + if(active_messages(index)%trailing_sep) then + active_messages(index)%decoded=trim(active_messages(index)%decoded)// & + ' '//candidate%decoded(1:kz-k) + else + active_messages(index)%decoded=trim(active_messages(index)%decoded)// & + candidate%decoded(1:kz-k) + endif + active_messages(index)%k=kz + endif + active_messages(index)%trailing_sep=candidate%trailing_sep + active_messages(index)%f1=candidate%f1 + active_messages(index)%tsync=candidate%tsync + call queue_message_update(active_messages(index),candidate%is_last_frame) + message=active_messages(index) + if(candidate%is_last_frame) call remove_active_message(index) + 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 + integer :: i,keep + + oldest_revisit=forward_tsync-real(MAX_RETRO_STEPS)*frame_period/4.0 + ! Retro candidates move backward in time, so only the forward watermark may expire history. + keep=0 + do i=1,nrecent + if(recent_frames(i)%tsync.lt. & + oldest_revisit-FRAME_HISTORY_TIME_TOLERANCE) cycle + keep=keep+1 + if(keep.ne.i) recent_frames(keep)=recent_frames(i) + enddo + nrecent=keep + + i=1 + do while(i.le.nactive) + 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 remove_active_message(i) + else + i=i+1 + endif + enddo + end subroutine prune_receive_state + subroutine jtty_tbcc_reencode_for_subtraction(payload, tones) + integer, intent(in) :: payload(PAYLOAD_BITS) + integer, intent(out) :: tones(TOTAL_K) + + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + end subroutine jtty_tbcc_reencode_for_subtraction + + pure subroutine jtty_search_window(fc,fwid,nfa,nfb,constrain_to_graph,df, & + first_bin,last_bin,ja,jb,usable) + implicit none + real, intent(inout) :: fc + real, intent(in) :: fwid,df + integer, intent(in) :: nfa,nfb,first_bin,last_bin + integer, intent(out) :: ja,jb + logical, intent(in) :: constrain_to_graph + logical, intent(out) :: usable + + ja=first_bin + jb=last_bin + usable=.false. + if(df.le.0.0 .or. fwid.lt.0.0 .or. first_bin.gt.last_bin) return + + if(constrain_to_graph) then + if(nfa.gt.nfb) return + fc=max(real(nfa),min(fc,real(nfb))) + endif + + ja=max(first_bin,int((fc-fwid)/df)) + jb=min(last_bin,int((fc+fwid)/df)) + if(constrain_to_graph) then + ja=max(ja,ceiling(real(nfa)/df)) + jb=min(jb,floor(real(nfb)/df)) + endif + usable=ja.le.jb + end subroutine jtty_search_window + + pure subroutine classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + type(message_assembly), intent(in) :: existing + type(decode), intent(in) :: candidate + 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 + integer :: nstep,nfp + + df1=candidate%f1-existing%f1 + dtsync=candidate%tsync-existing%tsync + match=.false. + nframes_gap=1 + nfp=nint(dtsync/frame_period) + fp_resid=abs(dtsync-frame_period*nfp) + if(nfp.ge.1 .and. nfp.le.MAX_CONTINUATION_GAP .and. & + fp_resid.lt.CONTINUATION_TIME_TOLERANCE) then + df_tol=10.0+3.0*real(nfp-1) + match=abs(df1).lt.df_tol + if(match) nframes_gap=nfp + endif + + ! Retro sweeps revisit only the preceding three quarter-frame windows. + is_window_dupe=.false. + if(.not.match) then + qstep=frame_period/4.0 + nstep=nint(dtsync/qstep) + resid=abs(dtsync-qstep*nstep) + if(abs(nstep).le.MAX_RETRO_STEPS .and. abs(df1).lt.10.0 .and. & + resid.lt.0.003 .and. & + .not.(mod(abs(nstep),4).eq.0 .and. nstep.ne.0)) then + match=.true. + is_window_dupe=.true. + endif + endif + + end subroutine classify_active_candidate + + subroutine jtty_mdecode(istart,istart0,iwave,nchunk,nsps,ndebug,nfa,nfb,f0,ftol,smin) + +! First try at a multi-decoder for JTTY - replaces the single-decode version in +! jtty_decode.f90. Does not pass decodes back to rjtty_sub yet - just prints +! results to the console + +! Note: nsps is samples per symbol at 12000 s^-1 sample rate. + use iso_fortran_env, only: int16 + use jtty_mod + use jtty_fec + implicit none + integer, parameter :: MAXCAND = 100 + integer, parameter :: NSYNC_SYM = 13 + integer, parameter :: NCHAN_SYM = 46 + integer, parameter :: NFRAME_SYM = 59 + real, parameter :: FSAMPLE = 6000.0 + real, parameter :: TWOPI = 6.283185307179586 + character(len=80) :: msg + character(len=34) :: c32(MAX_FRAMES) + integer :: final_payload(PAYLOAD_BITS), tone_symbols_chk(NCHAN_SYM) + integer :: tone_symbols_full(NFRAME_SYM), ipass + integer(int16), intent(in) :: iwave(nchunk) + integer, intent(in) :: istart, istart0, ndebug + integer :: i,i0,is,j,ja,jb + integer, save :: ntstep, ntgrid + integer :: istep,first_sync_bin,last_sync_bin + integer :: nchan, ichan + integer, intent(in) :: nchunk,nsps !size of chunk, nsps at 12000 Sa/s + integer, intent(in) :: nfa,nfb !Wide Graph freq range + integer :: nchunk6,nana !size of chunk, nana at 6000 Sa/s + integer, save :: nframe6 !size of frame at 6000 Sa/s + integer, save :: nsps0=-999 + type(jtty_payload_correlator), save :: payload_correlator + integer, save :: nfft,nh2,nss + integer :: iloc(1) + integer :: irxsync(NSYNC_SYM), irxchan(NCHAN_SYM) + integer :: iactive + 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) + integer :: nsync,nsymerrs + real :: fc,fwid + real :: fpk,pa,pt,pn + real :: fbest,xdtbest + real :: xdt_retry + real, allocatable, save :: s0(:,:) + logical, allocatable, save :: mask0(:,:) + real :: a(3) + real :: pow(0:3,NCHAN_SYM) + real, save :: baud,dt,df2 + real :: phi,dphi + real, external :: db + real, intent(in) :: f0,ftol,smin + real :: snrdb, xdt + real :: xdt1, f11, snr0 + complex, allocatable,save,target :: c(:) + complex, allocatable,save :: c0(:) + complex, allocatable,save :: c1(:) + complex, allocatable,save :: csync(:) !Waveform for sync at 6000 s^-1 sample rate + complex, allocatable,save :: ctones(:,:) + complex :: z + logical :: match + logical :: dupe + logical :: usable + logical :: is_window_dupe + logical :: is_pure_dupe + logical :: success_dec + logical :: channel_decoded, decoded_ok + logical :: any_subtracted + logical :: s0_valid + integer :: ir + type(decode) :: cand(MAXCAND) !Candidates for decoding + type(decode) :: dec !Current successful decode + logical :: use_interferer + real :: use_interferer_f1, use_interferer_tsync + integer :: use_interferer_payload(PAYLOAD_BITS) + +! Capture and clear the retro-resweep interferer request (if any) as the +! very first thing this call does, before any possible early return below +! -- otherwise a stale request could leak into a later, unrelated call. + use_interferer=interferer_pending + use_interferer_f1=interferer_f1 + use_interferer_tsync=interferer_tsync + use_interferer_payload=interferer_payload + interferer_pending=.false. + nsubtracted=0 + + nsync=0 + + if(istart.eq.istart0 .and. .not.use_interferer) then + ndecodes=0 + call reset_decode_search_state() + endif + if(sum(abs(int(iwave))).eq.0) return + + nchunk6=nchunk/2 ! chunk size at 6000 Sa/s +! nana is the size of c0 - next power of 2 larger than nchunk + nana = 2**nint(log(real(nchunk))/log(2.0)+0.5) + + if(nsps.ne.nsps0) then + nsps0=nsps + nss=nsps/2 ! samples per symbol at 6000 sa/s + nfft=8192 ! FFT size for sync search, gives df2=0.732 + df2=FSAMPLE/nfft + nh2=nfft/2 ! spectrum size for sync search + nframe6=NFRAME_SYM*nss ! frame size at 6000 Sa/s + ntstep=nframe6/4 + ntgrid=ntstep/12 + +! allocate saved arrays once + if(allocated(csync)) deallocate(csync) + allocate(csync(0:NSYNC_SYM*nss-1)) + if(allocated(ctones)) deallocate(ctones) + allocate(ctones(0:nss-1,0:3)) + if(allocated(c0)) deallocate(c0) + allocate(c0(0:nana-1)) + if(allocated(c)) deallocate(c) + allocate(c(0:nfft-1)) ! + if(allocated(c1)) deallocate(c1) + allocate(c1(0:nchunk6-1)) + if(allocated(s0)) deallocate(s0) + allocate(s0(0:nh2,0:ntgrid)) + s0=0. + if(allocated(mask0)) deallocate(mask0) + allocate(mask0(0:nh2,0:ntgrid)) + +! Generate complex waveform for sync + baud=FSAMPLE/real(nss) !31.25 for nss=192 + dt=1/FSAMPLE + call gen_syncwave(csync,nss) + + do i=0,3 + phi=0.0 + dphi=i*TWOPI/real(nss) + do j=0,nss-1 + ctones(j,i)=cmplx(cos(phi),sin(phi)) + phi=phi+dphi + enddo + enddo + endif + + call jtty_payload_correlator_prepare(payload_correlator,nss) + +! convert integer samples at 12K Sa/s to complex analytic signal at 6K Sa/s + call ana64a(iwave,nchunk,c0,nana) + c0(nchunk6:)=0. + + if(use_interferer) then + ! Retro re-sweep call: subtract the already-known signal out of + ! this window's own c0 before searching, on the theory that this + ! window's own candidates (whose frame spans reach ~ntstep to + ! nframe6 forward of this window's own [0,ntstep] search range) + ! may have been corrupted by that signal's energy even though this + ! window never itself searched for that signal's own sync. See + ! jtty_mdecode_step. + tone_symbols_full(1:NSYNC_SYM)=is13 + 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) + endif + +! Look for up to 2 sync candidates in each quarter-frame (0.424 second) by 2*FTol rectangle in +! the time/frequency plane. Find the peak in the search rectangle, then zero a small region +! of size nfz by ntz centered on the peak location and find the location of the next peak. + + nfz=nint(10.0/df2) ! 14 + ntz=nint(0.016*6000.0/12.0) ! 8 + + ! Every channel reads inside this span; unsearched bins may remain stale. + nchan=2 + first_sync_bin=nh2-2 + last_sync_bin=3 + do ichan=0,nchan + call channel_window() + if(.not.usable) cycle + first_sync_bin=min(first_sync_bin,ja) + last_sync_bin=max(last_sync_bin,jb) + enddo + + nc=2 ! look for 2 candidates in each channel + ncand=0 + any_subtracted=.false. + s0_valid=.false. + + ! Phase A: channel 0 gets first claim on every signal -- runs its own + ! full up-to-2-pass sweep to completion, accumulating n_ch0_ok across + ! both passes, before channels 1/2 (Phase B) ever run. + n_ch0_ok=0 + do ipass=1,2 + if(ipass.eq.2 .and. .not.any_subtracted) exit + if(.not.s0_valid) call build_s0() + ichan=0 + call process_channel() + enddo + + ! Channel 0 masks candidates privately, so an unchanged surface can + ! also serve channels 1/2. Their suppression modifies s0 directly. + any_subtracted=.false. + do ipass=1,2 + if(ipass.eq.2 .and. .not.any_subtracted) exit + if(.not.s0_valid) call build_s0() + do ichan=1,nchan + call process_channel() + enddo + s0_valid=.false. + enddo + + return + + contains + + subroutine build_s0() + use fftw3, only: fftwf_execute_dft + real(8), parameter :: CHIRP_TWOPI=6.2831853071795864769d0 + real(8) :: phase + real :: p0,p1,p2,p3,p4,chirp_scale + integer :: chirp_nfft,output_count,convolution_length + integer :: sync_fft_order + integer :: index,distance,first_output_bin + complex :: cz + complex, pointer :: fft_output(:) + logical :: use_chirp,full_fft_available + ! Rebuild s0, the FFT-correlation sync-search surface, from the + ! current c0 (may already reflect earlier-phase subtractions). + first_output_bin=first_sync_bin-2 + output_count=last_sync_bin-first_sync_bin+5 + convolution_length=NSYNC_SYM*nss+output_count-1 + chirp_nfft=1 + do while(chirp_nfft.lt.convolution_length) + chirp_nfft=2*chirp_nfft + enddo + use_chirp=output_count.gt.0 .and. & + chirp_nfft.lt.nfft .and. chirp_nfft.le.nfft/2 + + if(use_chirp) & + use_chirp=ensure_sync_fft_cache(chirp_nfft,.true.,sync_fft_order) + if(use_chirp .and. (sync_chirp_samples.ne.NSYNC_SYM*nss .or. & + sync_chirp_first_bin.ne.first_output_bin .or. & + sync_chirp_output_count.ne.output_count)) then + if(allocated(sync_chirp_weights)) deallocate(sync_chirp_weights) + if(allocated(sync_chirp_kernel)) deallocate(sync_chirp_kernel) + allocate(sync_chirp_weights(0:NSYNC_SYM*nss-1)) + allocate(sync_chirp_kernel(0:chirp_nfft-1)) + do index=0,NSYNC_SYM*nss-1 + phase=-CHIRP_TWOPI*(dble(first_output_bin)*dble(index)+ & + 0.5d0*dble(index)*dble(index))/dble(nfft) + sync_chirp_weights(index)=conjg(csync(index))* & + cmplx(cos(phase),sin(phase)) + enddo + sync_fft_caches(sync_fft_order)%input=0. + do distance=0,max(NSYNC_SYM*nss,output_count)-1 + phase=0.5d0*CHIRP_TWOPI*dble(distance)*dble(distance)/dble(nfft) + if(distance.lt.output_count) & + sync_fft_caches(sync_fft_order)%input(distance)= & + cmplx(cos(phase),sin(phase)) + if(distance.gt.0 .and. distance.lt.NSYNC_SYM*nss) & + sync_fft_caches(sync_fft_order)%input(chirp_nfft-distance)= & + cmplx(cos(phase),sin(phase)) + enddo + call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%forward, & + sync_fft_caches(sync_fft_order)%input, & + sync_fft_caches(sync_fft_order)%spectrum) + sync_chirp_kernel=sync_fft_caches(sync_fft_order)%spectrum + sync_chirp_samples=NSYNC_SYM*nss + sync_chirp_first_bin=first_output_bin + sync_chirp_output_count=output_count + endif + + ! Wider searches retain the full FFT path. + full_fft_available=.false. + if(.not.use_chirp) & + full_fft_available=ensure_sync_fft_cache(nfft,.false.,sync_fft_order) + if(use_chirp) then + sync_fft_caches(sync_fft_order)%input(NSYNC_SYM*nss:)=0. + chirp_scale=1.0/real(chirp_nfft) + else if(full_fft_available) then + ! Preserving the input keeps this padding intact for every time column. + sync_fft_caches(sync_fft_order)%input(NSYNC_SYM*nss:)=0. + endif + if(full_fft_available) then + fft_output=>sync_fft_caches(sync_fft_order)%spectrum + else + fft_output=>c + endif + istep=0 + do i0=0,ntstep,12 !Search over quarter-frame segment + xdt=i0*dt + if(use_chirp) then + sync_fft_caches(sync_fft_order)%input(0:NSYNC_SYM*nss-1)= & + sync_chirp_weights* & + c0(i0:i0+NSYNC_SYM*nss-1) + call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%forward, & + sync_fft_caches(sync_fft_order)%input, & + sync_fft_caches(sync_fft_order)%spectrum) + sync_fft_caches(sync_fft_order)%spectrum= & + sync_fft_caches(sync_fft_order)%spectrum*sync_chirp_kernel + call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%backward, & + sync_fft_caches(sync_fft_order)%spectrum, & + sync_fft_caches(sync_fft_order)%inverse) + ! Bluestein's omitted output chirp has unit magnitude. + cz=sync_fft_caches(sync_fft_order)%inverse(0)*chirp_scale + p0=real(cz)**2+aimag(cz)**2 + cz=sync_fft_caches(sync_fft_order)%inverse(1)*chirp_scale + p1=real(cz)**2+aimag(cz)**2 + cz=sync_fft_caches(sync_fft_order)%inverse(2)*chirp_scale + p2=real(cz)**2+aimag(cz)**2 + cz=sync_fft_caches(sync_fft_order)%inverse(3)*chirp_scale + p3=real(cz)**2+aimag(cz)**2 + do j=first_sync_bin,last_sync_bin + cz=sync_fft_caches(sync_fft_order)%inverse( & + j-first_sync_bin+4)*chirp_scale + p4=real(cz)**2+aimag(cz)**2 + s0(j,istep)=p0+2*p1+3*p2+2*p3+p4 + p0=p1 + p1=p2 + p2=p3 + p3=p4 + enddo + else + if(full_fft_available) then + sync_fft_caches(sync_fft_order)%input(0:NSYNC_SYM*nss-1)= & + conjg(csync(0:NSYNC_SYM*nss-1))*c0(i0:i0+NSYNC_SYM*nss-1) + call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%forward, & + sync_fft_caches(sync_fft_order)%input, & + sync_fft_caches(sync_fft_order)%spectrum) + else + c=0. + c(0:NSYNC_SYM*nss-1)=conjg(csync(0:NSYNC_SYM*nss-1))* & + c0(i0:i0+NSYNC_SYM*nss-1) + call four2a(c,nfft,1,-1,1) + endif + ! Keep the two-bin halo while advancing the five-bin smoothing kernel. + p0=real(fft_output(first_sync_bin-2))**2+ & + aimag(fft_output(first_sync_bin-2))**2 + p1=real(fft_output(first_sync_bin-1))**2+ & + aimag(fft_output(first_sync_bin-1))**2 + p2=real(fft_output(first_sync_bin))**2+ & + aimag(fft_output(first_sync_bin))**2 + p3=real(fft_output(first_sync_bin+1))**2+ & + aimag(fft_output(first_sync_bin+1))**2 + do j=first_sync_bin,last_sync_bin + p4=real(fft_output(j+2))**2+aimag(fft_output(j+2))**2 + s0(j,istep)=p0+2*p1+3*p2+2*p3+p4 + p0=p1 + p1=p2 + p2=p3 + p3=p4 + enddo + endif + istep=istep+1 + enddo + nstep_search=istep-1 + s0_valid=.true. + end subroutine build_s0 + + subroutine channel_window() + if(ichan.eq.0) then + fc=f0 + fwid=ftol + else + fc=1350 + if(ichan.eq.2) fc=1650 + fwid=150 + endif + call jtty_search_window(fc,fwid,nfa,nfb,ichan.ne.0,df2,3, & + ubound(s0,1)-2,ja,jb,usable) + end subroutine channel_window + + subroutine process_channel() + ! One channel's candidate search plus sticky-sync retry, for the + ! host's current ichan/ipass (host-associated with jtty_mdecode). + call channel_window() + if(.not.usable) return + nc0=nc + ! A wide QSO band needs more candidates to avoid crowding out its signal. + if(ichan.eq.0) nc0=max(2, min(8, nint(fwid/(nfz*df2)))) + fbest=0. + xdtbest=0. + fpk=0. + channel_decoded=.false. + + if(ichan.ne.0 .and. n_ch0_ok.gt.0) then + ! Erase only channel 0's actual successful-decode neighborhoods + ! (not its whole nominal band) so channels 1/2 can't rediscover + ! them, while staying free to catch what channel 0 missed. + do i=1,n_ch0_ok + if(max(ja,ja_ch0_ok(i)) .le. min(jb,jb_ch0_ok(i))) & + s0(max(ja,ja_ch0_ok(i)):min(jb,jb_ch0_ok(i)),0:nstep_search) = 0.0 + enddo + endif + + if(ichan.eq.0) mask0(ja:jb,0:nstep_search)=.true. + + do ic=1,nc0 + if(ichan.eq.0) then + ! Channel 0 uses a private mask instead of zeroing s0 + ! directly, so candidates that never pass the decode gate + ! don't eat into channels 1/2's shared search surface. + nsloc=maxloc(s0(ja:jb,0:nstep_search), & + mask=mask0(ja:jb,0:nstep_search)) + mask0( max( ja, nsloc(1)-nfz+ja ) : min( jb, nsloc(1)+nfz+ja ), & + max( 0, nsloc(2)-ntz ) : min( nstep_search, nsloc(2)+ntz ) ) = .false. + else + nsloc=maxloc(s0(ja:jb,0:nstep_search)) + s0( max( ja, nsloc(1)-nfz+ja ) : min( jb, nsloc(1)+nfz+ja ), & + max( 0, nsloc(2)-ntz ) : min( nstep_search, nsloc(2)+ntz ) ) = 0.0 + endif + fbest = (nsloc(1)-1+ja)*df2 + xdtbest = (nsloc(2)-1)*dt*12 + + if(ichan.eq.0) then + call jtty_peakup(c0,c1,csync,nchunk6, nss, xdtbest, fbest, xdt1, f11, snr0) + xdtbest=xdt1 + fbest=f11 + endif + + if(ncand .ge. MAXCAND) exit + ncand=ncand+1 + cand(ncand)%xdt=xdtbest + cand(ncand)%f1=fbest + + a=0. + a(1)=-cand(ncand)%f1 !Shift peak to zero frequency + call twkfreq(c0,c1,nchunk6,6000.0,a) + + pt=0. + pa=0. + pow=0.0 + do j=1,NSYNC_SYM ! find tone powers for sync symbols + i0=nint(cand(ncand)%xdt/dt) + (j-1)*nss + if(i0+nss.gt.nchunk6) exit + + do i=0,3 + z = dot_product(ctones(0:nss-1,i), c1(i0:i0+nss-1)) + pow(i,j)=real(z*conjg(z)) + enddo + + iloc=maxloc(pow(:,j))-1 + irxsync(j)=iloc(1) + pt=pt+pow(is13(j),j) !signal plus noise + pa=pa+sum(pow(:,j)) !signal plus 4*noise + enddo + + snrdb=-99.9 + pn=(pa-pt)/3.0 + if(pn.gt.0.) snrdb=db(pt/pn) + nsync=count(is13.eq.irxsync) ! nsync is the number of correct hard-decoded sync tones. + cand(ncand)%snrdb=snrdb + + if( ichan.eq.0 .and. (nsync .le. 6 .or. snrdb .lt. smin)) cycle + if( ichan.ne.0 .and. (nsync .le. 8 .or. snrdb .lt. 5.0)) cycle + +! looks like a real candidate - try to decode + call decode_and_merge(ic, decoded_ok) + if(decoded_ok) call record_ch0_success() + if(decoded_ok) channel_decoded=.true. + enddo ! candidate loop + + if(.not.channel_decoded) then + ! Sticky-sync retry: nothing decoded this call. If an active + ! message's continuation frame is due almost exactly one frame + ! period ago, retry the FEC decode directly at that remembered + ! sync point instead of giving up on it. + 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) - & + 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 + if(xdt_retry.lt.0.0) cycle + if(ncand .ge. MAXCAND) exit + ncand=ncand+1 + cand(ncand)%xdt=xdt_retry + cand(ncand)%f1=active_messages(ir)%f1 + ! decode_and_merge reads tone powers from c1, which is only + ! valid for whichever frequency the blind-candidate loop + ! above last shifted it to -- re-shift it for this retry's + ! own frequency, or it silently correlates against the wrong + ! signal (dchristle, PR #337). + a=0. + a(1)=-cand(ncand)%f1 + call twkfreq(c0,c1,nchunk6,6000.0,a) + nsync=-1 ! not meaningful for a sticky-sync retry; flags it in ndebug output + call decode_and_merge(-1, decoded_ok) + if(decoded_ok) call record_ch0_success() + if(decoded_ok) channel_decoded=.true. + exit ! at most one retry attempt per channel per call + enddo + endif + end subroutine process_channel + + subroutine record_ch0_success() + ! Record channel 0's successful-decode neighborhood so Phase B can + ! avoid it, and decode_and_merge's dedup check can catch it too. + if(ichan.ne.0) return + if(n_ch0_ok.ge.16) return + n_ch0_ok=n_ch0_ok+1 + ja_ch0_ok(n_ch0_ok)=nint(cand(ncand)%f1/df2)-nfz + jb_ch0_ok(n_ch0_ok)=nint(cand(ncand)%f1/df2)+nfz + f1_ch0_ok(n_ch0_ok)=cand(ncand)%f1 + tsync_ch0_ok(n_ch0_ok)=cand(ncand)%tsync + end subroutine record_ch0_success + + subroutine decode_and_merge(ic_label, decoded_ok) + ! Shared by the candidate loop and the sticky-sync retry: given + ! cand(ncand)%xdt/%f1, decode the 46 info symbols and merge into + ! active_messages(:). ic_label is only for the ndebug print (-1 for a retry). + integer, intent(in) :: ic_label + logical, intent(out) :: decoded_ok + complex :: zsym(0:3,NCHAN_SYM) + complex :: zhalf(0:3,NCHAN_SYM) + integer :: payload_start + integer :: best_cont + real :: best_df,dfabs + logical :: have_win,accepted,source_valid + integer :: gap,best_gap + type(message_assembly) :: accepted_message + + decoded_ok=.false. + payload_start=nint(cand(ncand)%xdt/dt) + NSYNC_SYM*nss + call jtty_correlate_payload_symbols(payload_correlator,c1,payload_start,zsym,zhalf) + call jtty_tbcc_decode(zsym,zhalf,final_payload,success_dec) + ! Half-symbol off-tone leakage is not a noise estimate; diagnostics use M1. + pow=abs(zsym)**2 + do j=1,NCHAN_SYM + iloc=maxloc(pow(:,j))-1 + irxchan(j)=iloc(1) + enddo + cand(ncand)%decoded=' ' + if( .not. success_dec ) return + + write(c32(1),'(34i1)') final_payload + call unpack_jtty(c32,1,cand(ncand)%decoded,cand(ncand)%trailing_sep, & + cand(ncand)%is_last_frame,source_valid) + if(.not.source_valid) return + + ndecodes=ndecodes+1 + ! Re-encode the decoded payload to recover the expected tone + ! per symbol, for the symbol-error-count/SNR diagnostic below + ! (mirrors what the old LDPC path got for free from its own + ! codeword bits). + call jtty_tbcc_reencode_for_subtraction(final_payload, tone_symbols_chk) + nsymerrs=13-nsync + do j = 1, NCHAN_SYM + is=tone_symbols_chk(j) + if(is.ne.irxchan(j)) nsymerrs=nsymerrs+1 + pt=pt+pow(is,j) + pa=pa+sum(pow(:,j)) + enddo + pn=(pa-pt)/3.0 + if(pn.gt.0.) then + snrdb=db(pt/pn) + cand(ncand)%snrdb=snrdb + endif + cand(ncand)%tsync=(istart-1)/12000.0 + cand(ncand)%xdt + decoded_ok=.true. + +! dupe detection + dupe=.false. + do i=1,ncand-1 + if( cand(i)%decoded .eq. cand(ncand)%decoded .and. & + abs(cand(i)%tsync - cand(ncand)%tsync).lt. 0.032 ) dupe=.true. + enddo + ! A channel-1/2 candidate matching a frame channel 0 already decoded + ! this call is sync-estimation noise, not a distinct signal. 3.0 Hz + ! tracks jtty_peakup's coherent-combining frequency precision. + if(ichan.ne.0) then + do i=1,n_ch0_ok + if(same_frame(cand(ncand)%f1,cand(ncand)%tsync, & + f1_ch0_ok(i),tsync_ch0_ok(i))) dupe=.true. + enddo + endif + if(dupe) return + + ! Subtract this signal from c0 so a second, weaker one underneath can + ! be found by a follow-up sweep over the residual (see the ipass loop + ! in jtty_mdecode). tone_symbols_full is the re-encoded, error- + ! corrected full frame (sync + info), matching what genjtty.f90 + ! assembles for TX. + tone_symbols_full(1:NSYNC_SYM)=is13 + tone_symbols_full(NSYNC_SYM+1:NFRAME_SYM)=tone_symbols_chk + call subtract_jtty(c0, nana, nchunk6, tone_symbols_full, NFRAME_SYM, & + nss, cand(ncand)%f1, cand(ncand)%xdt) + any_subtracted=.true. + s0_valid=.false. + + if(nsubtracted.lt.MAX_SUBTRACTED) then + nsubtracted=nsubtracted+1 + subtracted_f1(nsubtracted)=cand(ncand)%f1 + subtracted_tsync(nsubtracted)=cand(ncand)%tsync + subtracted_payload(:,nsubtracted)=final_payload + endif + + dec=cand(ncand) + match=.false. + is_pure_dupe=is_recent_frame(dec) + iactive=0 + if(.not.is_pure_dupe .and. nactive.gt.0) then + have_win=.false. + best_cont=0 + best_df=1.0e30 + best_gap=1 + do i=1,nactive + call classify_active_candidate(active_messages(i),dec, & + nframe6/6000.0,match,is_window_dupe,gap) + if(.not.match) cycle + if(is_window_dupe) then + if(.not.have_win) iactive=i + have_win=.true. + cycle + endif + dfabs=abs(dec%f1-active_messages(i)%f1) + if(dfabs.lt.best_df) then + best_df=dfabs + best_cont=i + best_gap=gap + endif + enddo + if(have_win) then + match=.true. + is_pure_dupe=.true. + else if(best_cont.gt.0) then + match=.true. + iactive=best_cont + else + match=.false. + endif + endif + + if(.not.is_pure_dupe .and. match) then + call append_active_message(iactive,dec,best_gap,accepted_message,accepted) + if(.not.accepted) return + msg=accepted_message%decoded + if(dec%is_last_frame) iactive=0 + else if(.not.is_pure_dupe) then + call start_message(dec,accepted_message,accepted) + if(.not.accepted) return + msg=accepted_message%decoded + if(dec%is_last_frame) then + iactive=0 + else + iactive=nactive + endif + else + msg=dec%decoded + endif + msg=display_message_text(msg) + if(ndebug.eq.0) then + if(.not.is_pure_dupe) write(*,3001) nint(dec%f1),trim(msg) +3001 format(i4,2x,a) + else if(ndebug.gt.0) then + write(*,3002) ichan,ipass,ic_label,ndecodes,iactive,nactive,match, & + use_interferer,dec%f1,dec%xdt,dec%tsync,nint(dec%snrdb-20.0), & + nsync,nsymerrs,trim(msg) +3002 format(6i4,2L3,f7.1,f7.3,f9.3,i5,i4,i4,2x,a) + endif + end subroutine decode_and_merge + + end subroutine jtty_mdecode + + subroutine jtty_mdecode_step(iwave,nwave,istart,istart0,nchunk,nsps,ndebug,nfa,nfb,f0,ftol,smin) + +! Wraps jtty_mdecode with "retro" re-sweeps: after the normal forward call, +! re-run the candidate sweep for up to 3 prior quarter-frame windows for +! every signal this call newly subtracted, since their candidates' frame +! spans could overlap that signal's energy. Not cascaded to further retro +! passes. Both rjtty_sub and rjtty call this instead of jtty_mdecode +! directly, passing the FULL buffer so retro calls can reach backward into it. + + use iso_fortran_env, only: int16 + implicit none + integer, intent(in) :: nwave + integer(int16), intent(in) :: iwave(nwave) + integer, intent(in) :: istart, istart0, nchunk, nsps, ndebug, nfa, nfb + 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) + integer :: payload_local(PAYLOAD_BITS,MAX_SUBTRACTED) + + nframe=59*nsps + step=nframe/4 + call prune_receive_state((istart-1)/12000.0,nframe/12000.0) + + interferer_pending=.false. ! defensive: no stale interferer input + call jtty_mdecode(istart,istart0,iwave(istart),nchunk,nsps,ndebug,nfa,nfb, & + f0,ftol,smin) + +! Copy this call's subtraction events out before any retro call below +! overwrites the same module-level output arrays with its own results. + n_local=nsubtracted + if(n_local.gt.0) then + f1_local(1:n_local)=subtracted_f1(1:n_local) + tsync_local(1:n_local)=subtracted_tsync(1:n_local) + payload_local(:,1:n_local)=subtracted_payload(:,1:n_local) + endif + + do i=1,n_local + do k=1,MAX_RETRO_STEPS + istart_prev=istart-k*step + if(istart_prev.lt.1) cycle + interferer_pending=.true. + interferer_f1=f1_local(i) + interferer_tsync=tsync_local(i) + interferer_payload=payload_local(:,i) + call jtty_mdecode(istart_prev,istart0,iwave(istart_prev),nchunk,nsps, & + ndebug,nfa,nfb,f0,ftol,smin) + enddo + enddo + + return + end subroutine jtty_mdecode_step + +end module jtty_mdec diff --git a/lib/jtty/jtty_mod.f90 b/lib/jtty/jtty_mod.f90 new file mode 100644 index 00000000..7ff25b5b --- /dev/null +++ b/lib/jtty/jtty_mod.f90 @@ -0,0 +1,447 @@ +module jtty_mod + + use jtty_source_codec + + parameter (MAX_FRAMES=16) !Max frames for the encoded message + character(len=*), parameter :: JTTY_ALPHABET = ALPHABET + integer, parameter :: JTTY_EXCHANGE_UNKNOWN=0,JTTY_EXCHANGE_FIELD_DAY=1,JTTY_EXCHANGE_RTTY=2 + +contains + +subroutine pack_jtty(message,c32,nframes,exchange_profile) + +! Input: character*80 message !JTTY message, as it appears to a user +! Output: character*34 c32 !34-bit payload: 32 bits of existing +! !grammar (unchanged) + 1 "last frame +! !of this message" flag (c32(:)(34:34)) +! !+ 1 reserved bit, always '0' +! !(c32(:)(33:33)), that the decoder +! !uses as a free extra check beyond +! !the CRC. +! integer nframes !Frames in this message (max = 16) +! +! Minimize frames after alphabet and exchange-profile normalization. + + use packjt77_grammar, only: pack77_arrl_section_index + implicit none + character*80 message,msg + character*34 c32(MAX_FRAMES) + integer, intent(in), optional :: exchange_profile + integer, parameter :: INF=999 + type(jtty_source_atom) :: choice(80),atoms(MAX_FRAMES) + integer :: dp(81),successor(80),n,ipos,inext,natoms,nframes,profile + logical valid + + call normalize_jtty_message(message,msg) + message=msg + nframes=0 + c32='' + profile=JTTY_EXCHANGE_UNKNOWN + if(present(exchange_profile)) profile=exchange_profile + if(profile.lt.JTTY_EXCHANGE_UNKNOWN .or. profile.gt.JTTY_EXCHANGE_RTTY) then + nframes=-1 + return + endif + if(profile.eq.JTTY_EXCHANGE_RTTY) then + call normalize_serials(valid) + if(.not.valid) then + nframes=-1 + return + endif + endif + message=msg + n=len_trim(msg) + if(n.le.0) return + + ! dp(i) is the minimum frame count for msg(i:n). + dp=INF + successor=0 + dp(n+1)=0 + do ipos=n,1,-1 + inext=min(n+1,ipos+5) + call consider(jtty_text5_atom(msg(ipos:inext-1)),inext) + if(ipos.gt.1) then + if(msg(ipos-1:ipos-1).ne.' ') cycle + endif + call try_compact() + enddo + + if(dp(1).gt.MAX_FRAMES) then + nframes=-1 + return + endif + ipos=1 + natoms=0 + do while(ipos.le.n) + natoms=natoms+1 + atoms(natoms)=choice(ipos) + ipos=successor(ipos) + enddo + call pack_jtty_atoms(atoms,natoms,c32,nframes,valid) + if(.not.valid) then + c32='' + nframes=-1 + endif + +contains + + subroutine normalize_serials(ok) + logical, intent(out) :: ok + character(len=160) :: result + character(len=80) :: rendered + integer :: first,last,next,last_field,value,length + logical :: numeric + + result='' + first=1 + length=len_trim(msg) + do while(first.le.length) + last=index(msg(first:length),' ') + if(last.eq.0) then + last=length + else + last=first+last-2 + endif + rendered=msg(first:last) + next=last+2 + if(rendered.eq.'599' .and. next.le.length) then + last_field=index(msg(next:length),' ') + if(last_field.eq.0) then + last_field=length + else + last_field=next+last_field-2 + endif + call decimal_value(msg(next:last_field),value,numeric) + if(numeric) then + call render_jtty_atom(jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,value),rendered,ok) + if(.not.ok) return + next=last_field+2 + endif + endif + if(first.eq.1) then + result=trim(rendered) + else + result=trim(result)//' '//trim(rendered) + endif + if(len_trim(result).gt.len(msg)) then + ok=.false. + return + endif + first=next + enddo + msg=result + ok=.true. + end subroutine normalize_serials + + subroutine consider(atom,next) + type(jtty_source_atom), intent(in) :: atom + integer, intent(in) :: next + integer :: cost,rank,best_rank,key,best_key + + cost=1+dp(next) + if(cost.gt.MAX_FRAMES .or. cost.gt.dp(ipos)) return + rank=merge(1,0,atom%kind.eq.JTTY_ATOM_TEXT5) + best_rank=merge(1,0,choice(ipos)%kind.eq.JTTY_ATOM_TEXT5) + key=100*atom%kind+2*atom%subtype+atom%role + best_key=100*choice(ipos)%kind+2*choice(ipos)%subtype+choice(ipos)%role + if(cost.eq.dp(ipos)) then + if(rank.gt.best_rank) return + if(rank.eq.best_rank) then + if(next.lt.successor(ipos)) return + if(next.eq.successor(ipos) .and. key.ge.best_key) return + endif + endif + dp(ipos)=cost + successor(ipos)=next + choice(ipos)=atom + end subroutine consider + + subroutine offer(atom) + type(jtty_source_atom), intent(in) :: atom + type(jtty_source_atom) :: decoded + character(len=34) :: frame + character(len=80) :: rendered + logical :: ok,eom + integer :: length,last,next + + call pack_jtty_atom(atom,frame,.false.,ok) + if(.not.ok) return + call unpack_jtty_atom(frame,decoded,ok,eom) + if(.not.ok) return + call render_jtty_atom(decoded,rendered,ok) + if(.not.ok) return + length=len_trim(rendered) + if(length.eq.0) return + last=ipos+length-1 + if(last.gt.n) return + if(msg(ipos:last).ne.rendered(1:length)) return + next=n+1 + if(last.lt.n) then + if(msg(last+1:last+1).ne.' ') return + ! Structured frames supply exactly one following separator column. + next=last+2 + endif + call consider(atom,next) + end subroutine offer + + subroutine try_compact() + character(len=80) :: words(3) + integer :: first,last,nwords,j,action,role,field,value,length,section_index + logical :: numeric + + words='' + first=ipos + nwords=0 + do j=1,size(words) + if(first.gt.n) exit + last=index(msg(first:n),' ') + if(last.eq.0) then + last=n + else + last=first+last-2 + endif + nwords=j + words(j)=msg(first:last) + first=last+2 + enddo + + do j=1,nwords + if(len_trim(words(j)).gt.len(choice(1)%text)) cycle + do action=JTTY_CALL_CQ,JTTY_CALL_TU_NOW + call offer(jtty_call_atom(action,trim(words(j)))) + enddo + enddo + do j=lbound(CONTROL_TEXT,1),ubound(CONTROL_TEXT,1) + call offer(jtty_control_atom(j)) + enddo + + do role=JTTY_ROLE_FIELD_ONLY,JTTY_ROLE_FULL + field=1 + if(role.eq.JTTY_ROLE_FULL) then + if(words(1).ne.'599' .or. nwords.lt.2) cycle + field=2 + endif + length=len_trim(words(field)) + call decimal_value(trim(words(field)),value,numeric) + if(numeric) call offer(jtty_exch_num_atom(role,JTTY_NUM_GENERIC,value)) + if(numeric .and. role.eq.JTTY_ROLE_FULL .and. profile.eq.JTTY_EXCHANGE_RTTY) & + call offer(jtty_exch_num_atom(role,JTTY_NUM_SERIAL,value)) + if(length.eq.4) call offer(jtty_grid4_atom(role,words(field)(1:4))) + if(role.ne.JTTY_ROLE_FULL .or. length.lt.2 .or. length.gt.3) cycle + if(scan(trim(words(field)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ').eq.0) cycle + call offer(jtty_exch_loc_atom(role,JTTY_LOC_QTH,trim(words(field)))) + if(profile.eq.JTTY_EXCHANGE_RTTY) & + call offer(jtty_exch_loc_atom(role,JTTY_LOC_STATE_PROVINCE,trim(words(field)))) + enddo + + length=len_trim(words(1)) + 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))) + call offer(jtty_class_section_atom(value,words(1)(length:length),section_index)) + end subroutine try_compact + + subroutine decimal_value(text,value,valid) + character(len=*), intent(in) :: text + integer, intent(out) :: value + logical, intent(out) :: valid + integer :: j + + value=0 + valid=.false. + if(len(text).lt.1 .or. len(text).gt.6) return + if(verify(text,'0123456789').ne.0) return + do j=1,len(text) + value=10*value+ichar(text(j:j))-ichar('0') + enddo + valid=value.le.131071 + end subroutine decimal_value + +end subroutine pack_jtty + +logical function jtty_standard_call(c13) + +! True only for tokens safe to carry in a 28-bit structured callsign field. + + use packjt77 + character*13 c13,c13a + character*13 unpacked + character*6 bcall_1 + logical ok1,success + integer*4 n28 + + jtty_standard_call=.false. + c13a=c13 + ! chkcall is a syntax filter; pack28/unpack28 round-trip defines what this + ! protocol field can actually carry. + call chkcall(c13a,bcall_1,ok1) + if(.not.ok1) return + if(index(c13a,'/').gt.0) return + if(c13a(1:1).eq.'Q') return + if(verify(trim(c13a),'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789').ne.0) return + + call pack28(c13a,n28) + call unpack28(n28,unpacked,success) + if(.not.success) return + jtty_standard_call=trim(unpacked).eq.trim(c13a) + +end function jtty_standard_call + +subroutine normalize_jtty_message(raw,normalized) + +! Fold operator text into the source alphabet used by the JTTY encoder. + + character*80 raw,normalized + character*1 c + logical last_space + + normalized='' + last_space=.true. + j=0 + + do i=1,len(raw) + c=raw(i:i) + if(ichar(c).eq.0) c=' ' + ! The decoder uses '~' as a display marker for space, not a source symbol. + if(c.eq.'~') c=' ' + if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32) + if(jchar(c).lt.0) c='#' + if(c.eq.' ') then + if(last_space) cycle + j=j+1 + normalized(j:j)=' ' + last_space=.true. + else + j=j+1 + normalized(j:j)=c + last_space=.false. + endif + enddo + +end subroutine normalize_jtty_message + +subroutine unpack_jtty(c32,nframes,message,trailing_sep,is_last_frame,source_valid) + +! Input: character*34 c32 !34-bit payload: 32 bits of existing +! !grammar + 1 reserved bit (33) + 1 +! !"last frame of this message" flag (34) +! integer nframes !Frames in this message (max = 16) +! Output: character*80 message !JTTY message, as it appears to a user +! logical trailing_sep (optional) !True if the last frame +! processed appended an implicit separator column. +! logical is_last_frame (optional) !True if the last frame +! processed had its "last frame of message" flag +! set -- for callers (e.g. jtty_mdecode's slot +! accumulation) that decode one frame at a time and +! need to know when a message is complete. +! +! Frame decoding flow: +! 1. Read the class bits once for each 32-bit payload. +! 2. Dispatch only assigned frame forms. +! 3. Append through one bounds-safe path. + + character*80 message + character*34 c32(MAX_FRAMES) + logical, intent(out), optional :: trailing_sep + logical, intent(out), optional :: is_last_frame + logical, intent(out), optional :: source_valid + + character*80 rendered + type(jtty_source_atom) atom + logical last_frame_sep + logical last_frame_flag + logical frame_valid,render_valid,frame_eom,all_valid + + message='' + k=1 + last_frame_sep=.false. + last_frame_flag=.false. + all_valid=nframes.ge.1 .and. nframes.le.MAX_FRAMES + do iframe=1,max(0,min(nframes,MAX_FRAMES)) + last_frame_sep=.false. + last_frame_flag=.false. + call unpack_jtty_atom(c32(iframe),atom,frame_valid,frame_eom) + if(.not.frame_valid) then + all_valid=.false. + cycle + endif + call render_jtty_atom(atom,rendered,render_valid) + if(.not.render_valid) then + all_valid=.false. + cycle + endif + last_frame_flag=frame_eom + if(atom%kind.eq.JTTY_ATOM_TEXT5) then + call append_payload_chars() + else + call append_text(rendered(1:len_trim(rendered))) + call append_implicit_separator() + endif + + enddo + + if(present(trailing_sep)) trailing_sep=last_frame_sep + if(present(is_last_frame)) is_last_frame=last_frame_flag .and. all_valid + if(present(source_valid)) source_valid=all_valid + + return + +contains + + subroutine append_text(text) + character*(*) text + integer i + + do i=1,len(text) + if(k.le.len(message)) message(k:k)=text(i:i) + k=k+1 + enddo + end subroutine append_text + + subroutine append_payload_chars() + ! TEXT5 carries five 6-bit JTTY characters in the upper 30 bits. + integer n30, j, idx + character*1 c + + read(c32(iframe),1006) n30 +1006 format(b30.30) + do j=1,5 + idx=iand(ishft(n30,-6*(5-j)),63) + c=charj(idx) + if(c.eq.' ') c='~' + if(k.le.len(message)) message(k:k)=c + k=k+1 + enddo + end subroutine append_payload_chars + + subroutine append_implicit_separator() + ! Structured frames leave one blank column before any following frame. + k=k+1 + last_frame_sep=.true. + end subroutine append_implicit_separator + +end subroutine unpack_jtty + + +character*1 function charj(j) + +! Returns the printable character corresponding to JTTY index j (0-63), + + charj=source_char(j) + + return +end function charj + +integer function jchar(c0) + +! Returns the JTTY index (0-63) corresponding to character c0. + + character*1 c0 + + jchar=source_index(c0) + + return +end function jchar + +end module jtty_mod diff --git a/lib/jtty/jtty_msgs.txt b/lib/jtty/jtty_msgs.txt new file mode 100644 index 00000000..f97d8ad1 --- /dev/null +++ b/lib/jtty/jtty_msgs.txt @@ -0,0 +1,23 @@ +CQ KA1ABC CQ +WB9XYZ +TU KA1ABC CQ +WB9XYZ TU +WB9XYZ AGN? +WB9XYZ TU CQ KA1ABC CQ +TU NOW JA6DEF 599 123 +WB9XYZ 599 0123 +WB9XYZ NR? + +599 1234 +599 MA +599 FN42 +599 BRUCE + +PJ4/KA1ABC +CQ KA1ABC +CQ PJ4/KA1ABC CQ +PJ4/KA1ABC 599 124 + + +THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG. +0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!"#$%,&*()_'=[]{}<>|:; diff --git a/lib/jtty/jtty_n1mm_integration.md b/lib/jtty/jtty_n1mm_integration.md new file mode 100644 index 00000000..63125cc9 --- /dev/null +++ b/lib/jtty/jtty_n1mm_integration.md @@ -0,0 +1,140 @@ +# JTTY and N1MM Logger+ Integration + +## Summary + +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. + +## Setup + +- Configure N1MM Logger+ with WSJT-X as for FT8. A starting point is [Operating WW Digi with N1MM and WSJT-X](https://www.rttycontesting.com/tutorials/n1mm/operating-ww-digi-with-n1mm/). +- Verify radio control, PTT, audio, and the `forEW1` configuration in FT8 before selecting JTTY. +- Enter `JTTY` in the N1MM callsign field and press Enter to start WSJT-X in JTTY mode. +- Confirm that the WSJT-X footer shows JTTY and the window title contains `forEW1`. +- Use radio test mode, zero output power, or a dummy load for initial checks. +- Save the existing Digital Function Key file before loading the supplied `JTTY Messages.mc` example. + +End-to-end validation with N1MM on Windows, including two-radio focus, call selection, queue movement, and Run/S&P state transitions, remains required before release. + +## Literal TXTEXT + +N1MM expands logger macros before passing TXTEXT to WSJT-X. An untagged result uses the literal source interface: + +- 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. 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. + +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. + +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: + +```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 | + +Payloads contain dynamic values, not the phrases implied by an action. For +example, `CQ` receives only the callsign, `CALL_TU_CQ` receives two callsigns, +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. + +`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 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. + +## Bundled action mappings + +The supplied macro file deliberately omits hardcoded `599`. Full-role native exchanges render the report canonically when the selected profile calls for it; Field Day class/section does not. + +| Context | Key | Tagged meaning | +| --- | --- | --- | +| Run | F1 | `CQ` | +| Run | F2 | `CALL_EXCH` | +| Run | F3 | `CALL_TU_CQ` | +| Run | F4 | `MYCALL` | +| Run | F5 | `HISCALL` | +| Run | F6 | `CONTROL NR?` | +| Run | F8 | `CONTROL AGN?` | +| S&P | F1 | `CQ` | +| S&P | F2 | `CALL_EXCH` | +| S&P | F3 | `CALL_TU_MY` | +| S&P | F4 | `CALL_MY` | +| S&P | F5 | `HISCALL` | +| S&P | F6 | `MYCALL` | +| S&P | F7 | `EXCH` | +| S&P | F8 | `CONTROL AGN?` | + +Run F11 is intentionally left spare. N1MM call stacking can transmit a call +correction before `{LOGTHENPOP}` and change the station referenced by subsequent +callsign and exchange macros. That sequence cannot satisfy the leading-tag +contract reliably without validated N1MM TXTEXT ordering. `TU_NOW_EXCH` remains +available for an explicit leading tag whose already-expanded payload names the +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 complete wire definition is in [`jtty_source_encoding.txt`](jtty_source_encoding.txt). diff --git a/lib/jtty/jtty_payload_correlators.f90 b/lib/jtty/jtty_payload_correlators.f90 new file mode 100644 index 00000000..296ffe69 --- /dev/null +++ b/lib/jtty/jtty_payload_correlators.f90 @@ -0,0 +1,108 @@ +module jtty_payload_correlators + use, intrinsic :: iso_fortran_env, only: int32, real32, real64 + implicit none + private + + real(real32), parameter :: TWO_PI = 6.2831853071795864769_real32 + + type, public :: jtty_payload_correlator + private + integer(int32) :: samples_per_symbol = 0_int32 + real(real32), allocatable :: reference_real(:,:) + real(real32), allocatable :: reference_imaginary(:,:) + end type jtty_payload_correlator + + public :: jtty_payload_correlator_prepare + public :: jtty_correlate_payload_symbols + +contains + + subroutine jtty_payload_correlator_prepare(correlator, samples_per_symbol) + type(jtty_payload_correlator), intent(inout) :: correlator + integer(int32), intent(in) :: samples_per_symbol + real(real32) :: phase, phase_step + integer :: sample, tone + + if (samples_per_symbol <= 0_int32 .or. modulo(samples_per_symbol,2_int32) /= 0_int32) & + error stop 'invalid JTTY payload symbol length' + if (correlator%samples_per_symbol == samples_per_symbol .and. & + allocated(correlator%reference_real) .and. & + allocated(correlator%reference_imaginary)) return + + correlator%samples_per_symbol = samples_per_symbol + if (allocated(correlator%reference_real)) deallocate(correlator%reference_real) + if (allocated(correlator%reference_imaginary)) & + deallocate(correlator%reference_imaginary) + allocate(correlator%reference_real(0:3,0:samples_per_symbol-1)) + allocate(correlator%reference_imaginary(0:3,0:samples_per_symbol-1)) + + do tone = 0, 3 + phase = 0.0_real32 + phase_step = TWO_PI*real(tone,real32)/real(samples_per_symbol,real32) + do sample = 0, samples_per_symbol - 1 + correlator%reference_real(tone,sample) = cos(phase) + correlator%reference_imaginary(tone,sample) = sin(phase) + phase = phase + phase_step + end do + end do + end subroutine jtty_payload_correlator_prepare + + subroutine jtty_correlate_payload_symbols(correlator, samples, payload_start, & + correlations, half_correlations) + ! Samples are candidate-centered analytic baseband; payload_start is zero-based. + type(jtty_payload_correlator), intent(in) :: correlator + complex(real32), intent(in) :: samples(0:) + integer(int32), intent(in) :: payload_start + complex(real32), intent(out) :: correlations(0:,:), half_correlations(0:,:) + real(real32) :: sample_real, sample_imaginary + real(real32) :: full_real(0:3), full_imaginary(0:3) + real(real32) :: half_real(0:3), half_imaginary(0:3) + real(real32) :: product_rr(0:3), product_ii(0:3), product_ri(0:3), product_ir(0:3) + real(real64) :: energy(0:3) + integer :: available_symbols, first, offset, segment, half_length, symbol, tone + + if (.not.allocated(correlator%reference_real) .or. & + correlator%samples_per_symbol <= 0_int32) & + error stop 'unprepared JTTY payload correlator' + if (size(correlations,1) /= 4 .or. any(shape(correlations) /= shape(half_correlations))) & + error stop 'invalid JTTY payload correlation shape' + if (payload_start < 0_int32) error stop 'invalid JTTY payload offset' + correlations = cmplx(0.0_real32,0.0_real32,real32) + half_correlations = cmplx(0.0_real32,0.0_real32,real32) + if (payload_start >= size(samples)) return + available_symbols = min(size(correlations,2), & + (size(samples)-payload_start)/correlator%samples_per_symbol) + half_length = correlator%samples_per_symbol/2 + + do symbol = 1, available_symbols + first = payload_start + (symbol - 1)*correlator%samples_per_symbol + full_real = 0.0_real32 + full_imaginary = 0.0_real32 + energy = 0.0_real64 + do segment = 0, 1 + half_real = 0.0_real32 + half_imaginary = 0.0_real32 + do offset = segment*half_length, (segment+1)*half_length-1 + sample_real = real(samples(first+offset),real32) + sample_imaginary = aimag(samples(first+offset)) + product_rr = correlator%reference_real(:,offset)*sample_real + product_ii = correlator%reference_imaginary(:,offset)*sample_imaginary + product_ri = correlator%reference_real(:,offset)*sample_imaginary + product_ir = correlator%reference_imaginary(:,offset)*sample_real + ! Preserve each observation's accumulation order while sharing products. + full_real = full_real + product_rr + product_ii + full_imaginary = full_imaginary + product_ri - product_ir + half_real = half_real + product_rr + product_ii + half_imaginary = half_imaginary + product_ri - product_ir + end do + energy = energy + real(half_real*half_real + half_imaginary*half_imaginary,real64) + end do + do tone = 0, 3 + correlations(tone,symbol) = cmplx(full_real(tone),full_imaginary(tone),real32) + half_correlations(tone,symbol) = & + cmplx(real(sqrt(max(0.0_real64,energy(tone))),real32),0.0_real32,real32) + end do + end do + end subroutine jtty_correlate_payload_symbols + +end module jtty_payload_correlators diff --git a/lib/jtty/jtty_peakup.f90 b/lib/jtty/jtty_peakup.f90 new file mode 100644 index 00000000..80afcbe2 --- /dev/null +++ b/lib/jtty/jtty_peakup.f90 @@ -0,0 +1,146 @@ +subroutine jtty_peakup(c0,c1,csync,nchunk,nss,xdt0,f0,xdt,f1,snr) + implicit none + + complex, intent(in) :: c0(0:nchunk-1) !Complex data at 6000 S/s + complex :: c1(0:nchunk-1) !Work array + complex, intent(in) :: csync(0:13*nss-1) + complex :: c(0:13*nss-1) !Lengh of Barker sequence + complex :: z + complex :: zcur(0:12), zbest(0:12), ztot + complex :: qstep(0:12) + real :: a(3) + real :: fsample, dt, pmax, fpk, xdtpk, xnorm, p + real :: phase(0:12), uw(0:12) + real :: dphi, xm, ym, sxy, sxx, slope, intercept + real :: resid, resid_rms, dfhz, tsym + integer, intent(in) :: nchunk, nss + integer :: i, i0, ia, ib, idf, istart, iend, npsync, r + integer, parameter :: hop=4 + real, intent(in) :: xdt0, f0 + real, intent(out) :: xdt, f1, snr + real, parameter :: TWOPI = 6.283185307179586 + real, parameter :: PI = 3.141592653589793 + + npsync=13*nss ! size of the sync waveform array + do i=0,12 + istart=i*nss + qstep(i)=csync(istart+hop)*conjg(csync(istart)) + enddo + fsample=6000.0 + dt=1.0/fsample + ia=max(0,nint((xdt0-0.004)/dt)) + ! ib must bound the i0 loop against c1's actual size (nchunk), not + ! npsync (an unrelated length) -- else ib<ia silently returns f1=xdt=0. + ib=min(nchunk-npsync,nint((xdt0+0.004)/dt)) + + pmax=0. + fpk=0. + xdtpk=0. + c1=cmplx(0.,0.) + xnorm=sum(abs(c0(0:nchunk-1)))/real(nchunk) + do idf=-5,5 + a=0. + a(1)=-f0 + 0.5*idf !Shift assumed peak to zero frequency + call twkfreq(c0,c1,ib+npsync,fsample,a) + if(ia.le.ib) then + c(0:npsync-1)=conjg(csync)*c1(ia:ia+npsync-1) + do i=0,12 + istart=i*nss + iend=istart+nss-1 + zcur(i)=sum(c(istart:iend)) + enddo + endif + do i0=ia,ib,hop !Search over xdt for sync pattern + xdt=i0*dt + if(ia.le.ib) then +! Coherent only within a symbol (32ms) here; this locates the sync +! instant. Stage 2 below refines f1 with a coherent combination across +! all 13 symbols once that instant is known. + p=0 + do i=0,12 + z=zcur(i) + p=p+real(z)**2+aimag(z)**2 + enddo + if(p.gt.pmax) then + pmax=p + fpk=-a(1) + xdtpk=i0*dt + zbest=zcur + endif + if(i0+hop.le.ib) then + do i=0,12 + istart=i*nss + z=cmplx(0.,0.) + do r=0,hop-1 + z=z+conjg(csync(istart+r))*c1(i0+istart+r) + enddo + zcur(i)=qstep(i)*(zcur(i)-z) + z=cmplx(0.,0.) + do r=0,hop-1 + z=z+conjg(csync(istart+nss-hop+r))* & + c1(i0+istart+nss+r) + enddo + zcur(i)=zcur(i)+z + enddo + endif + endif + enddo + enddo + + ! Stage 2: the winning candidate's 13 per-symbol phasors carry a near- + ! linear phase ramp vs. symbol index, from the sub-0.5-Hz residual + ! frequency error the coarse idf grid above can't resolve. Fit and + ! remove that ramp, then combine all 13 symbols coherently for a + ! sharper f1. + if(pmax.gt.0.) then + tsym=nss/fsample + do i=0,12 + phase(i)=atan2(aimag(zbest(i)),real(zbest(i))) + enddo + uw(0)=phase(0) + do i=1,12 + dphi=phase(i)-phase(i-1) + do while(dphi.gt.PI) + dphi=dphi-TWOPI + enddo + do while(dphi.lt.-PI) + dphi=dphi+TWOPI + enddo + uw(i)=uw(i-1)+dphi + enddo + xm=6.0 !mean symbol index (0..12) + ym=sum(uw)/13.0 + sxy=0. + sxx=0. + do i=0,12 + sxy=sxy+(real(i)-xm)*(uw(i)-ym) + sxx=sxx+(real(i)-xm)**2 + enddo + slope=sxy/sxx + intercept=ym-slope*xm + resid_rms=0. + do i=0,12 + resid=uw(i)-(slope*real(i)+intercept) + resid_rms=resid_rms+resid**2 + enddo + resid_rms=sqrt(resid_rms/13.0) + dfhz=slope/(TWOPI*tsym) + + ! Guardrails: only trust the refinement when the fit is clean (this + ! sharpens the coarse estimate, it doesn't replace it) and the + ! correction stays within the coarse grid's own 0.5 Hz step. + if(resid_rms.lt.1.0 .and. abs(dfhz).le.0.5) then + ztot=cmplx(0.,0.) + do i=0,12 + ztot=ztot+zbest(i)*cmplx(cos(-slope*i),sin(-slope*i)) + enddo + fpk=fpk+dfhz + pmax=real(ztot)**2+aimag(ztot)**2 + endif + endif + + f1=fpk + xdt=xdtpk + snr=pmax + return +end subroutine jtty_peakup diff --git a/lib/jtty/jtty_source_codec.f90 b/lib/jtty/jtty_source_codec.f90 new file mode 100644 index 00000000..e73a62ad --- /dev/null +++ b/lib/jtty/jtty_source_codec.f90 @@ -0,0 +1,470 @@ +module jtty_source_codec + use iso_c_binding, only: c_char,c_int,c_int8_t,c_int32_t + use packjt77, only: pack28,unpack28 + use packjt77_grammar, only: PACK77_NSEC,PACK77_ARRL_SECTIONS + implicit none + +! i2.n2 Example Bits Total Purpose +! 0.0 CQ K1ABC CQ 28+2+2 32 CQ call action +! 0.1 K1ABC 28+2+2 32 bare call action +! 0.2 TU K1ABC CQ 28+2+2 32 TU/CQ call action +! 0.3 K1ABC TU 28+2+2 32 call/TU action +! 1.0 K1ABC AGN? 28+2+2 32 call/AGN action +! 1.1 TU NOW K1ABC 28+2+2 32 TU NOW/call action +! 1.2-3 reserved 28+2+2 32 invalid in version 1 +! 2.x STRUCT30 27+3+2 32 typed structured source atom +! 3.x TEXT5 30+2 32 five six-bit JTTY characters +! +! family Name Body fields, from bit 1 toward bit 27 +! 000 EXCH_NUM role1 + number_kind4 + value17 + zero5 +! 001 EXCH_LOC role1 + location_kind4 + length1 + 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-110 reserved invalid in version 1 +! 111 guard space always invalid + + integer, parameter :: I8=selected_int_kind(18) + character(len=*), parameter :: ALPHABET = & + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!"#$%,&*()_''=[]{}<>|:;' + integer, parameter :: JTTY_ATOM_CALL=0,JTTY_ATOM_EXCH_NUM=1 + integer, parameter :: JTTY_ATOM_EXCH_LOC=2,JTTY_ATOM_EXCH_PAIR=3 + integer, parameter :: JTTY_ATOM_EXCH_NUM_TIME=4,JTTY_ATOM_CONTROL=5 + integer, parameter :: JTTY_ATOM_GRID4=6,JTTY_ATOM_TEXT5=7 + integer, parameter :: JTTY_CALL_CQ=0,JTTY_CALL_CALL=1,JTTY_CALL_TU_CQ=2 + integer, parameter :: JTTY_CALL_CALL_TU=3,JTTY_CALL_CALL_AGN=4,JTTY_CALL_TU_NOW=5 + integer, parameter :: JTTY_ROLE_FIELD_ONLY=0,JTTY_ROLE_FULL=1 + integer, parameter :: JTTY_NUM_SERIAL=0,JTTY_NUM_CQ_ZONE=1,JTTY_NUM_ITU_ZONE=2 + integer, parameter :: JTTY_NUM_AGE=3,JTTY_NUM_POWER=4,JTTY_NUM_CHECK=5 + integer, parameter :: JTTY_NUM_LICENSE_YEAR=6,JTTY_NUM_GENERIC=7 + integer, parameter :: JTTY_LOC_STATE_PROVINCE=0,JTTY_LOC_SECTION=1 + integer, parameter :: JTTY_LOC_COUNTRY_PREFIX=2,JTTY_LOC_QTH=3,JTTY_LOC_ADMIN_CODE=4 + integer, parameter :: JTTY_PAIR_ZONE_LOC3=0,JTTY_PAIR_CLASS_SECTION=1 + integer, parameter :: JTTY_MISC_CONTROL=0,JTTY_MISC_GRID4=1 + integer(c_int), parameter :: JTTY_ENCODE_OK=0,JTTY_ENCODE_INVALID_DESCRIPTOR=1 + integer(c_int), parameter :: JTTY_ENCODE_UNKNOWN_SECTION=2 + integer, parameter :: JTTY_CONTROL_AGN=0,JTTY_CONTROL_CALL=1,JTTY_CONTROL_AGN_CALL=2 + integer, parameter :: JTTY_CONTROL_NR=3,JTTY_CONTROL_AGN_NR=4,JTTY_CONTROL_EXCH=5 + integer, parameter :: JTTY_CONTROL_STATE=6,JTTY_CONTROL_SECTION=7,JTTY_CONTROL_ZONE=8 + integer, parameter :: JTTY_CONTROL_GRID=9,JTTY_CONTROL_RPRT=10,JTTY_CONTROL_QSL_TU=11 + integer, parameter :: JTTY_CONTROL_TU=12,JTTY_CONTROL_QRZ=13,JTTY_CONTROL_QSO_B4=14 + integer, parameter :: JTTY_CONTROL_WAIT=15,JTTY_CONTROL_NIL=16,JTTY_CONTROL_OK=17 + character(len=8), parameter :: CONTROL_TEXT(0:17)=[character(len=8) :: & + 'AGN?','CALL?','AGN CALL','NR?','AGN NR','EXCH?','STATE?','SECTION?', & + 'ZONE?','GRID?','RPRT?','QSL TU','TU','QRZ?','QSO B4','WAIT','NIL?','OK?'] + + type :: jtty_source_atom + integer :: kind=-1,subtype=0,role=JTTY_ROLE_FIELD_ONLY,value=0,value2=0 + character(len=13) :: text='' + end type jtty_source_atom + + type, bind(C) :: jtty_source_atom_c + integer(c_int8_t) :: kind,subtype,role,reserved + integer(c_int32_t) :: value + character(kind=c_char) :: text(9) + end type jtty_source_atom_c + +contains + +subroutine pack_jtty_atom(atom,frame,eom,valid) + type(jtty_source_atom), intent(in) :: atom + character(len=34), intent(out) :: frame + logical, intent(in) :: eom + logical, intent(out) :: valid + integer(I8) :: body,top30,n32,token_value,pair_data,data + integer :: i,n28,i2,n2,n,grid_index,class_index + character(len=13) :: call_text,roundtrip + character(len=5) :: text5 + logical :: success + frame=''; valid=.false.; n32=0 + select case(atom%kind) + case(JTTY_ATOM_CALL) + if(atom%subtype.lt.0 .or. atom%subtype.gt.5) return + call_text=atom%text + if(.not.standard_call(call_text)) return + call pack28(call_text,n28); call unpack28(n28,roundtrip,success) + if(.not.success .or. trim(roundtrip).ne.trim(call_text)) return + if(atom%subtype.le.3) then; i2=0; n2=atom%subtype + else; i2=1; n2=atom%subtype-4; endif + n32=ishft(int(n28,I8),4)+4*n2+i2 + case(JTTY_ATOM_EXCH_NUM) + if(.not.valid_role(atom%role) .or. .not.valid_number(atom%subtype,atom%value)) return + body=ishft(int(atom%role,I8),26)+ishft(int(atom%subtype,I8),22)+ishft(int(atom%value,I8),5) + call finish_struct(body,0,n32) + case(JTTY_ATOM_EXCH_LOC) + if(.not.valid_role(atom%role) .or. atom%subtype.lt.0 .or. atom%subtype.gt.4) return + n=len_trim(atom%text); if(n.ne.2 .and. n.ne.3) return + call pack_base36(atom%text(1:n),token_value,success); if(.not.success) return + body=ishft(int(atom%role,I8),26)+ishft(int(atom%subtype,I8),22)+ & + ishft(int(n-2,I8),21)+ishft(token_value,5) + call finish_struct(body,1,n32) + case(JTTY_ATOM_EXCH_PAIR) + select case(atom%subtype) + case(JTTY_PAIR_ZONE_LOC3) + if(atom%value.lt.1 .or. atom%value.gt.40) return + n=len_trim(atom%text); if(n.ne.2 .and. n.ne.3) return + call pack_base36(atom%text(1:n),token_value,success); if(.not.success) return + pair_data=ishft(int(atom%value,I8),17)+ishft(int(n-2,I8),16)+token_value + case(JTTY_PAIR_CLASS_SECTION) + if(atom%value.lt.1 .or. atom%value.gt.32) return + if(atom%value2.lt.1 .or. atom%value2.gt.PACK77_NSEC .or. len_trim(atom%text).ne.1) return + class_index=ichar(atom%text(1:1))-ichar('A'); if(class_index.lt.0 .or. class_index.gt.5) return + pair_data=ishft(int(atom%value,I8),17)+ishft(int(class_index,I8),14)+ & + ishft(int(atom%value2,I8),7) + case default; return + end select + body=ishft(int(atom%subtype,I8),24)+ishft(pair_data,1); call finish_struct(body,2,n32) + case(JTTY_ATOM_EXCH_NUM_TIME) + if(.not.valid_role(atom%role) .or. atom%value.lt.0 .or. atom%value.gt.16383) return + if(atom%value2.lt.0 .or. atom%value2.gt.1439) return + body=ishft(int(atom%role,I8),26)+ishft(int(atom%value,I8),12)+ishft(int(atom%value2,I8),1) + call finish_struct(body,3,n32) + case(JTTY_ATOM_CONTROL) + if(atom%subtype.lt.0 .or. atom%subtype.gt.17) return + body=ishft(int(JTTY_MISC_CONTROL,I8),23)+ishft(int(atom%subtype,I8),16) + call finish_struct(body,4,n32) + case(JTTY_ATOM_GRID4) + if(.not.valid_role(atom%role)) return + call grid4_to_index(atom%text,grid_index,success); if(.not.success) return + data=ishft(int(atom%role,I8),22)+ishft(int(grid_index,I8),7) + body=ishft(int(JTTY_MISC_GRID4,I8),23)+data; call finish_struct(body,4,n32) + case(JTTY_ATOM_TEXT5) + text5=atom%text(1:5); top30=0 + do i=1,5 + if(source_index(text5(i:i)).lt.0) return + top30=64*top30+source_index(text5(i:i)) + enddo + n32=4*top30+3 + case default; return + end select + write(frame(1:32),'(b32.32)') n32 + frame(33:33)='0' + frame(34:34)=merge('1','0',eom) + valid=.true. +end subroutine pack_jtty_atom + +subroutine finish_struct(body,family,n32) + integer(I8), intent(in) :: body + integer, intent(in) :: family + integer(I8), intent(out) :: n32 + n32=4*(8*body+family)+2 +end subroutine finish_struct + +subroutine unpack_jtty_atom(frame,atom,valid,eom) + character(len=34), intent(in) :: frame + type(jtty_source_atom), intent(out) :: atom + logical, intent(out) :: valid,eom + integer(I8) :: top30,body,pair_data,data,token_value + integer :: i,i2,family,n28,n2,zero,n,grid_index,class_index + character(len=13) :: call_text + logical :: success + atom=jtty_source_atom(); valid=.false.; eom=.false. + if(verify(frame,'01').ne.0 .or. frame(33:33).ne.'0') return + if(frame(1:32).eq.repeat('0',32)) return + read(frame,'(b30.30,b2.2)') top30,i2 + select case(i2) + case(0,1) + read(frame,'(b28.28,b2.2)') n28,n2 + if(i2.eq.1 .and. n2.gt.1) return + call unpack28(n28,call_text,success) + if(.not.success .or. .not.standard_call(call_text)) return + atom=jtty_call_atom(merge(n2,n2+4,i2.eq.0),call_text) + case(2) + family=int(iand(top30,7_I8)); body=ishft(top30,-3) + select case(family) + case(0) + atom%kind=JTTY_ATOM_EXCH_NUM; atom%role=int(ibits(body,26,1)) + atom%subtype=int(ibits(body,22,4)); atom%value=int(ibits(body,5,17)) + zero=int(ibits(body,0,5)) + if(zero.ne.0 .or. .not.valid_number(atom%subtype,atom%value)) return + case(1) + atom%kind=JTTY_ATOM_EXCH_LOC; atom%role=int(ibits(body,26,1)) + atom%subtype=int(ibits(body,22,4)); n=int(ibits(body,21,1))+2 + token_value=ibits(body,5,16); zero=int(ibits(body,0,5)) + if(zero.ne.0 .or. atom%subtype.gt.4 .or. token_value.ge.36_I8**n) return + if(n.eq.3 .and. token_value.lt.36_I8**2) return + call unpack_base36(token_value,n,atom%text) + case(2) + atom%kind=JTTY_ATOM_EXCH_PAIR; atom%subtype=int(ibits(body,24,3)) + pair_data=ibits(body,1,23); zero=int(ibits(body,0,1)); if(zero.ne.0) return + select case(atom%subtype) + case(JTTY_PAIR_ZONE_LOC3) + atom%value=int(ibits(pair_data,17,6)); n=int(ibits(pair_data,16,1))+2 + token_value=ibits(pair_data,0,16) + if(atom%value.lt.1 .or. atom%value.gt.40 .or. token_value.ge.36_I8**n) return + if(n.eq.3 .and. token_value.lt.36_I8**2) return + call unpack_base36(token_value,n,atom%text) + case(JTTY_PAIR_CLASS_SECTION) + atom%value=int(ibits(pair_data,17,6)); class_index=int(ibits(pair_data,14,3)) + atom%value2=int(ibits(pair_data,7,7)); zero=int(ibits(pair_data,0,7)) + if(atom%value.lt.1 .or. atom%value.gt.32 .or. class_index.gt.5) return + if(atom%value2.lt.1 .or. atom%value2.gt.PACK77_NSEC .or. zero.ne.0) return + atom%text(1:1)=char(ichar('A')+class_index) + case default; return + end select + case(3) + atom%kind=JTTY_ATOM_EXCH_NUM_TIME; atom%role=int(ibits(body,26,1)) + atom%value=int(ibits(body,12,14)); atom%value2=int(ibits(body,1,11)) + zero=int(ibits(body,0,1)); if(zero.ne.0 .or. atom%value2.gt.1439) return + case(4) + i=int(ibits(body,23,4)); data=ibits(body,0,23) + select case(i) + case(JTTY_MISC_CONTROL) + atom%kind=JTTY_ATOM_CONTROL; atom%subtype=int(ibits(data,16,7)) + zero=int(ibits(data,0,16)); if(zero.ne.0 .or. atom%subtype.gt.17) return + case(JTTY_MISC_GRID4) + atom%kind=JTTY_ATOM_GRID4; atom%role=int(ibits(data,22,1)) + grid_index=int(ibits(data,7,15)); zero=int(ibits(data,0,7)) + if(zero.ne.0 .or. grid_index.ge.32400) return + call index_to_grid4(grid_index,atom%text) + case default; return + end select + case default; return + end select + case(3) + atom%kind=JTTY_ATOM_TEXT5 + do i=1,5 + atom%text(i:i)=source_char(int(iand(ishft(top30,-6*(5-i)),63_I8))) + enddo + end select + eom=frame(34:34).eq.'1' + valid=.true. +end subroutine unpack_jtty_atom + +subroutine render_jtty_atom(atom,text,valid) + type(jtty_source_atom), intent(in) :: atom + character(len=80), intent(out) :: text + logical, intent(out) :: valid + character(len=16) :: first,second + character(len=3) :: section + integer :: hours,minutes + text=''; valid=.true. + select case(atom%kind) + case(JTTY_ATOM_CALL) + select case(atom%subtype) + case(JTTY_CALL_CQ); text='CQ '//trim(atom%text)//' CQ' + case(JTTY_CALL_CALL); text=trim(atom%text) + case(JTTY_CALL_TU_CQ); text='TU '//trim(atom%text)//' CQ' + case(JTTY_CALL_CALL_TU); text=trim(atom%text)//' TU' + case(JTTY_CALL_CALL_AGN); text=trim(atom%text)//' AGN?' + case(JTTY_CALL_TU_NOW); text='TU NOW '//trim(atom%text) + case default; valid=.false. + end select + case(JTTY_ATOM_EXCH_NUM) + if(.not.valid_role(atom%role) .or. .not.valid_number(atom%subtype,atom%value)) then + valid=.false.; return + endif + call render_number(atom%subtype,atom%value,first); call render_role(atom%role,trim(first),text) + case(JTTY_ATOM_EXCH_LOC) + if(atom%subtype.lt.0 .or. atom%subtype.gt.4) then; valid=.false.; return; endif + call render_role(atom%role,trim(atom%text),text) + case(JTTY_ATOM_EXCH_PAIR) + select case(atom%subtype) + case(JTTY_PAIR_ZONE_LOC3) + write(first,'(i2.2)') atom%value; text='599 '//trim(first)//' '//trim(atom%text) + case(JTTY_PAIR_CLASS_SECTION) + if(atom%value2.lt.1 .or. atom%value2.gt.PACK77_NSEC) then; valid=.false.; return; endif + section=PACK77_ARRL_SECTIONS(atom%value2) + write(first,'(i0,a1)') atom%value,atom%text(1:1); text=trim(first)//' '//trim(section) + case default; valid=.false. + end select + case(JTTY_ATOM_EXCH_NUM_TIME) + if(.not.valid_role(atom%role) .or. atom%value.lt.0 .or. atom%value.gt.16383 .or. & + atom%value2.lt.0 .or. atom%value2.gt.1439) then; valid=.false.; return; endif + call render_number(JTTY_NUM_SERIAL,atom%value,first) + hours=atom%value2/60; minutes=mod(atom%value2,60) + write(second,'(i2.2,i2.2)') hours,minutes + call render_role(atom%role,trim(first)//' '//trim(second),text) + case(JTTY_ATOM_CONTROL) + if(atom%subtype.lt.0 .or. atom%subtype.gt.17) then; valid=.false.; return; endif + text=trim(CONTROL_TEXT(atom%subtype)) + case(JTTY_ATOM_GRID4) + call render_role(atom%role,atom%text(1:4),text) + case(JTTY_ATOM_TEXT5); text(1:5)=atom%text(1:5) + case default; valid=.false. + end select +end subroutine render_jtty_atom + +subroutine render_role(role,field,text) + integer, intent(in) :: role + character(len=*), intent(in) :: field + character(len=80), intent(out) :: text + if(role.eq.JTTY_ROLE_FULL) then; text='599 '//field; else; text=field; endif +end subroutine render_role + +subroutine render_number(kind,value,text) + integer, intent(in) :: kind,value + character(len=16), intent(out) :: text + select case(kind) + case(JTTY_NUM_SERIAL) + if(value.lt.1000) then; write(text,'(i3.3)') value; else; write(text,'(i0)') value; endif + case(JTTY_NUM_CQ_ZONE,JTTY_NUM_ITU_ZONE,JTTY_NUM_CHECK) + if(value.lt.100) then; write(text,'(i2.2)') value; else; write(text,'(i0)') value; endif + case(JTTY_NUM_LICENSE_YEAR); write(text,'(i4.4)') value + case default; write(text,'(i0)') value + end select +end subroutine render_number + +logical function valid_number(kind,value) + integer, intent(in) :: kind,value + valid_number=kind.ge.0 .and. kind.le.7 .and. value.ge.0 .and. value.le.131071 + if(.not.valid_number) return + if(kind.eq.JTTY_NUM_CQ_ZONE) valid_number=value.ge.1 .and. value.le.40 + if(kind.eq.JTTY_NUM_ITU_ZONE) valid_number=value.ge.1 .and. value.le.90 + if(kind.eq.JTTY_NUM_LICENSE_YEAR) valid_number=value.le.9999 +end function valid_number + +logical function valid_role(role) + integer, intent(in) :: role + valid_role=role.eq.JTTY_ROLE_FIELD_ONLY .or. role.eq.JTTY_ROLE_FULL +end function valid_role + +logical function standard_call(call_text) + character(len=13), intent(in) :: call_text + character(len=13) :: work,unpacked + character(len=6) :: base_call + logical :: ok,success + integer :: n28 + standard_call=.false.; work=call_text + call chkcall(work,base_call,ok) + if(.not.ok .or. index(work,'/').gt.0 .or. work(1:1).eq.'Q') return + if(verify(trim(work),'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789').ne.0) return + call pack28(work,n28); call unpack28(n28,unpacked,success) + standard_call=success .and. trim(unpacked).eq.trim(work) +end function standard_call + +type(jtty_source_atom) function jtty_call_atom(action,call) result(atom) + integer, intent(in) :: action + character(len=*), intent(in) :: call + atom%kind=JTTY_ATOM_CALL; atom%subtype=action; atom%text=call +end function jtty_call_atom + +type(jtty_source_atom) function jtty_exch_num_atom(role,kind,value) result(atom) + integer, intent(in) :: role,kind,value + atom%kind=JTTY_ATOM_EXCH_NUM; atom%role=role; atom%subtype=kind; atom%value=value +end function jtty_exch_num_atom + +type(jtty_source_atom) function jtty_exch_loc_atom(role,kind,token) result(atom) + integer, intent(in) :: role,kind + character(len=*), intent(in) :: token + atom%kind=JTTY_ATOM_EXCH_LOC; atom%role=role; atom%subtype=kind; atom%text=token +end function jtty_exch_loc_atom + +type(jtty_source_atom) function jtty_zone_loc_atom(zone,token) result(atom) + integer, intent(in) :: zone + character(len=*), intent(in) :: token + atom%kind=JTTY_ATOM_EXCH_PAIR; atom%subtype=JTTY_PAIR_ZONE_LOC3 + atom%value=zone; atom%text=token +end function jtty_zone_loc_atom + +type(jtty_source_atom) function jtty_class_section_atom(count,class,section_index) result(atom) + integer, intent(in) :: count,section_index + character(len=*), intent(in) :: class + atom%kind=JTTY_ATOM_EXCH_PAIR; atom%subtype=JTTY_PAIR_CLASS_SECTION + atom%value=count; atom%value2=section_index; atom%text=class +end function jtty_class_section_atom + +type(jtty_source_atom) function jtty_exch_num_time_atom(role,serial,minute_of_day) result(atom) + integer, intent(in) :: role,serial,minute_of_day + atom%kind=JTTY_ATOM_EXCH_NUM_TIME; atom%role=role + atom%value=serial; atom%value2=minute_of_day +end function jtty_exch_num_time_atom + +type(jtty_source_atom) function jtty_control_atom(phrase_id) result(atom) + integer, intent(in) :: phrase_id + atom%kind=JTTY_ATOM_CONTROL; atom%subtype=phrase_id +end function jtty_control_atom + +type(jtty_source_atom) function jtty_grid4_atom(role,grid) result(atom) + integer, intent(in) :: role + character(len=*), intent(in) :: grid + atom%kind=JTTY_ATOM_GRID4; atom%role=role; atom%text=grid +end function jtty_grid4_atom + +type(jtty_source_atom) function jtty_text5_atom(text) result(atom) + character(len=*), intent(in) :: text + integer :: n + atom%kind=JTTY_ATOM_TEXT5; atom%text=''; n=min(5,len(text)) + 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) + 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 :: i + 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 + do i=1,natoms + call pack_jtty_atom(atoms(i),frames(i),i.eq.natoms,valid) + if(.not.valid) then; frames=''; return; endif + enddo + nframes=natoms +end subroutine pack_jtty_atoms + +subroutine pack_base36(token,value,valid) + character(len=*), intent(in) :: token + integer(I8), intent(out) :: value + logical, intent(out) :: valid + integer :: i,digit + value=0; valid=len(token).eq.2 .or. len(token).eq.3 + if(.not.valid) return + do i=1,len(token) + digit=index('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',token(i:i))-1 + if(digit.lt.0) then; valid=.false.; return; endif + value=36*value+digit + enddo + if(len(token).eq.3 .and. value.lt.36_I8**2) valid=.false. +end subroutine pack_base36 + +subroutine unpack_base36(value,n,token) + integer(I8), intent(in) :: value + integer, intent(in) :: n + character(len=13), intent(out) :: token + integer(I8) :: work + integer :: i,digit + token=''; work=value + do i=n,1,-1 + digit=int(mod(work,36_I8)); work=work/36 + token(i:i)='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'(digit+1:digit+1) + enddo +end subroutine unpack_base36 + +subroutine grid4_to_index(grid,index_value,valid) + character(len=*), intent(in) :: grid + integer, intent(out) :: index_value + logical, intent(out) :: valid + integer :: a,b,c,d + index_value=0; valid=len_trim(grid).eq.4 + if(.not.valid) return + a=ichar(grid(1:1))-ichar('A'); b=ichar(grid(2:2))-ichar('A') + c=ichar(grid(3:3))-ichar('0'); d=ichar(grid(4:4))-ichar('0') + valid=a.ge.0 .and. a.lt.18 .and. b.ge.0 .and. b.lt.18 .and. & + c.ge.0 .and. c.lt.10 .and. d.ge.0 .and. d.lt.10 + if(valid) index_value=((a*18+b)*10+c)*10+d +end subroutine grid4_to_index + +subroutine index_to_grid4(index_value,grid) + integer, intent(in) :: index_value + character(len=13), intent(out) :: grid + integer :: work,a,b,c,d + grid=''; work=index_value + d=mod(work,10); work=work/10; c=mod(work,10); work=work/10 + b=mod(work,18); a=work/18 + grid(1:4)=char(ichar('A')+a)//char(ichar('A')+b)//char(ichar('0')+c)//char(ichar('0')+d) +end subroutine index_to_grid4 + +integer function source_index(c) + character(len=1), intent(in) :: c + source_index=index(ALPHABET,c)-1 +end function source_index + +character(len=1) function source_char(i) + integer, intent(in) :: i + source_char=ALPHABET(i+1:i+1) +end function source_char + +end module jtty_source_codec diff --git a/lib/jtty/jtty_source_encoding.txt b/lib/jtty/jtty_source_encoding.txt new file mode 100644 index 00000000..efc78c6e --- /dev/null +++ b/lib/jtty/jtty_source_encoding.txt @@ -0,0 +1,380 @@ +JTTY source encoding + +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 +is one only on the final atom of a source message. It is a sender-intended +boundary, not evidence that earlier atoms were received or that a QSO is +complete. + +The 32-bit all-zero grammar word is an invalid sentinel. A receiver shall also +reject a source word if any reserved-zero field is nonzero or if it contains an +unassigned type, family, subtype, enum value, or out-of-range field. These +source-validity checks are made after FEC and CRC verification. An invalid +source word shall not be displayed, create a receive slot, complete a message +through EOM, or participate in signal subtraction. + +Top-level message space + +-------------------------------------------------------------------------------- +i2.n2 Example Bits Total Purpose +-------------------------------------------------------------------------------- +0.0 CQ K1ABC CQ 28 2 30 CQ call action +0.1 K1ABC 28 2 30 CALL action +0.2 TU K1ABC CQ 28 2 30 TU/CQ action +0.3 K1ABC TU 28 2 30 CALL/TU action +1.0 K1ABC AGN? 28 2 30 CALL/AGN action +1.1 TU NOW K1ABC 28 2 30 TU NOW/CALL action +1.2 (reserved; invalid) +1.3 (reserved; invalid) +2 599 123 27 3 30 STRUCT30 +3 HELLO 6 6 6 6 6 30 TEXT5 +-------------------------------------------------------------------------------- + +For i2=0 or 1, bits 1-28 are the existing call28 representation, bits 29-30 +are n2, and bits 31-32 are i2. Only standard calls that round-trip through the +existing pack28/unpack28 grammar are valid JTTY call atoms. The six assigned +actions render exactly as shown above after substituting the decoded call. + +For i2=3, bits 1-30 contain five six-bit characters in transmission order and +bits 31-32 are 11. Character values 0-63 index this alphabet: + + 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!"#$%,&*()_'=[]{}<>|:; + +The final TEXT5 atom is padded on the right with spaces. Padding is not part of +the rendered message. + +STRUCT30 + +For i2=2, bits 1-27 are body27, bits 28-30 are family3, and bits 31-32 +are 10. Fields below are listed in bit order, from bit 1 toward bit 27. + +-------------------------------------------------------------------------------- +Family Name Body fields Total Status +-------------------------------------------------------------------------------- +000 EXCH_NUM role1 kind4 value17 zero5 27 assigned +001 EXCH_LOC role1 kind4 length1 token16 zero5 27 assigned +010 EXCH_PAIR schema3 pair_data23 zero1 27 assigned +011 EXCH_NUM_TIME role1 serial14 minute11 zero1 27 assigned +100 MISC subtype4 subtype_data23 27 assigned +101 PROFILED body27 27 reserved +110 VERSIONED body27 27 reserved +111 INVALID body27 27 invalid guard +-------------------------------------------------------------------------------- + +Families 101-111 are invalid in version 1. They reserve space for a future +profiled/dense extension, a versioned extension, and an explicit validity +guard, respectively. A future assignment requires a protocol revision. + +Common fields + +role1 is an utterance role: + + 0 field-only; do not render a signal report + 1 full exchange; prefix the rendered fields with "599 " + +Base-36 fields use digit values 0-9 followed by A-Z. A token is accumulated +left to right, so ABC is ((10 * 36) + 11) * 36 + 12. length1 is 0 for exactly +two characters and 1 for exactly three characters. The token16 value shall be +less than 36^2 for length=0. For length=1 it shall be at least 36^2 and less +than 36^3; a three-character spelling with a leading zero would have a +canonical two-character representation and is invalid. Lowercase and +punctuation do not occur on the wire. + +EXCH_NUM, family 000 + +-------------------------------------------------------------------------------- +Kind Name Values Canonical field rendering +-------------------------------------------------------------------------------- +0 SERIAL 0-131071 decimal, at least three digits +1 CQ_ZONE 1-40 decimal, at least two digits +2 ITU_ZONE 1-90 decimal, at least two digits +3 AGE 0-131071 decimal +4 POWER 0-131071 decimal +5 CHECK 0-131071 decimal, at least two digits +6 FIRST_LICENSE_YEAR 0-9999 decimal, exactly four digits +7 GENERIC_NUMERIC 0-131071 decimal +8-15 (reserved; invalid) +-------------------------------------------------------------------------------- + +The role determines whether "599 " precedes the field. Apart from CQ and ITU +zones and the four-digit license-year domain, the core grammar enforces only +the 17-bit range; contest-specific limits belong to future profile validation. +Decimal width, separators, 5NN spelling, and visible repetition are not +represented. + +EXCH_LOC, family 001 + +-------------------------------------------------------------------------------- +Kind Name +-------------------------------------------------------------------------------- +0 STATE_PROVINCE +1 ARRL_RAC_SECTION +2 COUNTRY_PREFIX +3 GENERIC_QTH +4 LOCAL_ADMINISTRATIVE_CODE +5-15 (reserved; invalid) +-------------------------------------------------------------------------------- + +The token has the base-36 and length rules above. The role determines whether +"599 " precedes it. + +EXCH_PAIR, family 010 + +-------------------------------------------------------------------------------- +Schema Name pair_data fields Valid ranges +-------------------------------------------------------------------------------- +0 ZONE_LOC3 cq_zone6 length1 token16 zone 1-40; token as above +1 CLASS_SECTION count6 class3 section7 zero7 count 1-32; class 0-5; + section 1-86 +2-7 (reserved; invalid) +-------------------------------------------------------------------------------- + +ZONE_LOC3 always renders "599 <zone> <token>" with a two-digit-minimum zone. +CLASS_SECTION renders "<count><class> <section>". Class values 0-5 mean A-F; +6-7 are invalid. Section values 1-86 index PACK77_ARRL_SECTIONS in +lib/77bit/packjt77_grammar.f90; value zero and values 87-127 are invalid. The +registry is deliberately shared rather than copied into this specification. + +EXCH_NUM_TIME, family 011 + + role1 + serial14 + minute_of_day11 + zero1 + +serial is 0-16383. minute_of_day is 0-1439 and maps to UTC HHMM by division +and remainder by 60. The serial uses at least three digits and UTC time exactly +four digits. role=1 renders "599 <serial> <HHMM>"; role=0 omits "599 ". Values +1440-2047 for minute_of_day are invalid. + +MISC, family 100 + +-------------------------------------------------------------------------------- +Subtype Name subtype_data fields +-------------------------------------------------------------------------------- +0 CONTROL phrase7 zero16 +1 GRID4 role1 grid4_code15 zero7 +2-15 (reserved; invalid) +-------------------------------------------------------------------------------- + +CONTROL phrase assignments and canonical renderings are: + +-------------------------------------------------------------------------------- +ID Phrase ID Phrase ID Phrase +-------------------------------------------------------------------------------- + 0 AGN? 6 STATE? 12 TU + 1 CALL? 7 SECTION? 13 QRZ? + 2 AGN CALL 8 ZONE? 14 QSO B4 + 3 NR? 9 GRID? 15 WAIT + 4 AGN NR 10 RPRT? 16 NIL? + 5 EXCH? 11 QSL TU 17 OK? +-------------------------------------------------------------------------------- + +Phrase values 18-127 are invalid. CONTROL's sixteen reserved bits shall be +zero. + +GRID4 accepts only Maidenhead fields AA00 through RR99. With A=0, the code is: + + (((field_1 * 18 + field_2) * 10 + digit_1) * 10 + digit_2) + +Thus the valid domain is 0-32399. Values 32400-32767 are invalid. role=1 +renders "599 <GRID4>" and role=0 renders only the four-character grid. + +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. + +Candidates at complete token boundaries are: + + * All six call forms, 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 " followed by a valid two- or three-character base-36 token + containing at least one letter, as full-role GENERIC_QTH. Canonical + base-36 length rules apply; numeric-only tokens cannot use this path. + * Valid GRID4, field-only or preceded by "599 ". + * Canonical CLASS_SECTION using the count, class, and section rules above. + +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. + +RTTY Roundup additionally considers full "599 <number>" as SERIAL and full +"599 <location>" as STATE_PROVINCE under the existing native exchange rules. +Location tokens must contain at least one letter. Before the shared packing +algorithm, explicit RTTY Roundup canonicalizes decimal tokens following a +complete "599" token to the SERIAL spelling (at least three digits). Eligible +tokens have one to six digits and value 0-131071. Unsupported tokens keep their +spelling and use normal fallback. Bare digits and Unknown or Field Day input +retain their spelling after ordinary text normalization. The canonical message +is returned to the GUI for display and logging. A canonical result exceeding +80 characters is rejected rather than truncated. + +The exact-render requirement applies to this profile-normalized text, and no +bare number is inferred as SERIAL. CQ_ZONE, ITU_ZONE, +AGE, POWER, CHECK, FIRST_LICENSE_YEAR, other specific location kinds, +ZONE_LOC3, and EXCH_NUM_TIME are not inferred from ordinary text. The profile +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. + +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 +two frames because their leading zeros cannot be preserved with GENERIC_NUMERIC. +Under RTTY Roundup, "599 001" uses one SERIAL frame and "K1ABC 599 001" uses +two frames. Under RTTY Roundup, "599 05" becomes "599 005" and "599 0123" +becomes "599 123", each using one SERIAL frame. Under Unknown or Field Day +they retain their spelling and use two frames. "599 BRUCE" also needs two: +STRUCT30 has no generic five-character exchange atom. + +sjtty defaults to Unknown. The optional leading argument +--exchange-profile=unknown|field-day|rtty-roundup applies to both its +one-message packing and eight-argument waveform invocations. An invalid +profile value is an error. + +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 +use the exact-compatibility rule below. + +-------------------------------------------------------------------------------- +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 full exchange +F7 %H AGN? CALL_AGN(his_call) +F8 %E configured full exchange +-------------------------------------------------------------------------------- + +%E is the configured profile exchange. The default profile accepts a decimal +serial. FIELD_DAY accepts exactly "<count><class> <section>" and encodes +CLASS_SECTION. RTTY accepts either a decimal SERIAL or a canonical two- or +three-character STATE_PROVINCE token. %G accepts one valid GRID4 and is +field-only; the exact template "599 %G" selects a full-role GRID4. These are +semantic placeholders, not text substitution followed by source inference. + +The exact former defaults "%H 599 %N", "TU NOW %Q 599 %N", and "599 %N" +remain recognized during migration and are replaced by their %E forms when +still unchanged in saved settings. Edited variants are not migrated or matched +as native templates. An unrecognized customized template uses automatic text +packing after normal placeholder expansion. A recognized native template +whose required runtime call, exchange, or grid is invalid is rejected; it +never changes meaning by falling back to literal transmission. + +Practical transmit subset + +The wire codec defines and validates every atom in this document. The current +WSJT-X macro and tagged-N1MM compilers intentionally generate a smaller +operator-facing subset: the six Call8 actions, SERIAL, RTTY STATE_PROVINCE, +CLASS_SECTION, GRID4, and registered CONTROL phrases. The automatic text packer +also generates GENERIC_NUMERIC and GENERIC_QTH. Other number and location kinds, +ZONE_LOC3, and EXCH_NUM_TIME have canonical receive rendering and remain +available to explicit native codec callers, but are not inferred from ordinary +text or exposed as general-purpose transmit macros in this version. + +Tagged N1MM TXTEXT + +N1MM can opt into the practical native subset by placing this marker at the +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: + +-------------------------------------------------------------------------------- +Action Expanded payload Native meaning +-------------------------------------------------------------------------------- +CQ <mycall> CQ(mycall) +CALL_EXCH <hiscall> <exchange> CALL(hiscall), full exchange +CALL_TU_CQ <hiscall> <mycall> CALL_TU(hiscall), CQ(mycall) +MYCALL <mycall> CALL(mycall) +HISCALL <hiscall> CALL(hiscall) +TU_NOW_EXCH <hiscall> <exchange> TU_NOW_CALL(hiscall), exchange +CALL_MY <hiscall> <mycall> CALL(hiscall), CALL(mycall) +CALL_TU_MY <hiscall> <mycall> CALL_TU(hiscall), CALL(mycall) +EXCH <exchange> configured full exchange +GRID <grid4> field-only GRID4 +CONTROL <registered phrase> CONTROL(phrase) +-------------------------------------------------------------------------------- + +The exchange payload follows the same default, FIELD_DAY, and RTTY profile +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 +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. + +Representative 34-bit vectors + +Binary strings below contain bits 1-34 exactly. Hex values interpret the same +34 bits as an unsigned integer and pad to nine hex digits. Both serial rows +encode the same atom and demonstrate the EOM difference; changing any final +atom to non-final clears the final binary bit and subtracts one from its hex +value. + +-------------------------------------------------------------------------------- +Meaning Bits 1-34 Hex +-------------------------------------------------------------------------------- +CQ K1ABC CQ 0000100110111101111000110101000001 0x026F78D41 +EXCH_NUM full SERIAL 123, more 1000000000000001111011000000001000 0x20007B008 +EXCH_NUM full SERIAL 123, EOM 1000000000000001111011000000001001 0x20007B009 +EXCH_LOC full STATE CA 1000000000000110111010000000011001 0x2001BA019 +ZONE_LOC3 05 NWT 0000001011011110010000110100101001 0x00B790D29 +CLASS_SECTION 1D EMA 0010000010110001011000000000101001 0x082C58029 +EXCH_NUM_TIME full 156 1749 1000000100111001000010110100111001 0x204E42D39 +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_spec.f90 b/lib/jtty/jtty_spec.f90 new file mode 100644 index 00000000..27101200 --- /dev/null +++ b/lib/jtty/jtty_spec.f90 @@ -0,0 +1,40 @@ +subroutine jtty_spec(iwave,iz)
+
+ parameter (NFFT=262144,NH=NFFT/2)
+ integer*2 iwave(iz)
+ real*4 x(NFFT)
+ real*4 s(0:NH)
+ complex c(0:NH)
+ equivalence (x,c)
+
+ x(1:iz)=iwave
+ x(iz+1:)=0.
+ call four2a(c,NFFT,1,-1,0)
+
+ do i=0,NH
+ c(i)=c(i)/NFFT
+ s(i)=real(c(i))**2 + aimag(c(i))**2
+ enddo
+ do i=1,200
+ call smo121(s,NH+1)
+ enddo
+ smax=maxval(s)
+ s=s/(4.0*smax)
+ tpmax=sum(s)
+
+ df=12000.0/NFFT
+ f1=0.
+ f2=0.
+ tp=0.
+ do i=0,NH
+ if(f1.eq.0.0 .and. db(s(i)).gt.-60.0) f1=i*df
+ if(i*df.gt.1500.0 .and. db(s(i)).gt.-60.0) f2=i*df
+ tp=tp+s(i)
+ write(70,3070) i*df,db(s(i)),100.0*tp/tpmax,s(i)
+3070 format(3f12.3,e12.3)
+ enddo
+ write(*,1000) f1,f2,f2-f1
+1000 format(3f10.1)
+
+ return
+end subroutine jtty_spec
diff --git a/lib/jtty/jtty_tbcc_code_profile.f90 b/lib/jtty/jtty_tbcc_code_profile.f90 new file mode 100644 index 00000000..9037d790 --- /dev/null +++ b/lib/jtty/jtty_tbcc_code_profile.f90 @@ -0,0 +1,106 @@ +module jtty_tbcc_code_profiles + use, intrinsic :: iso_fortran_env, only: int32 + implicit none + private + + integer(int32), parameter, public :: JTTY_TBCC_PAYLOAD_BITS = 34_int32 + integer(int32), parameter, public :: JTTY_TBCC_OUTER_CHECK_BITS = 12_int32 + integer(int32), parameter, public :: JTTY_TBCC_INFORMATION_BITS = & + JTTY_TBCC_PAYLOAD_BITS + JTTY_TBCC_OUTER_CHECK_BITS + + ! A circular rate-1/2 trellis with memory nu has 2**nu states and a + ! constraint-length register of nu+1 bits. + type, public :: jtty_tbcc_code_profile + integer(int32) :: profile_id = 0_int32 + integer(int32) :: memory_nu = 0_int32 + integer(int32) :: constraint_length = 0_int32 + integer(int32) :: state_count = 0_int32 + integer(int32) :: state_mask = 0_int32 + integer(int32) :: register_mask = 0_int32 + ! Generator masks use integer bit patterns; octal notation is the + ! conventional spelling for convolutional codes such as 1167/1545. + integer(int32) :: generator_0 = 0_int32 + integer(int32) :: generator_1 = 0_int32 + ! The leading term of the outer polynomial is implicit; these masks describe + ! the stored feedback coefficients and remainder register. + integer(int32) :: outer_polynomial = 0_int32 + integer(int32) :: outer_top_bit_mask = 0_int32 + integer(int32) :: outer_register_mask = 0_int32 + integer(int32) :: payload_bits = 0_int32 + integer(int32) :: outer_check_bits = 0_int32 + integer(int32) :: information_bits = 0_int32 + end type jtty_tbcc_code_profile + + type(jtty_tbcc_code_profile), parameter, public :: & + JTTY_TBCC_PROFILE_1167_1545_80F = jtty_tbcc_code_profile( & + profile_id=1_int32, memory_nu=9_int32, constraint_length=10_int32, & + state_count=512_int32, state_mask=int(z'1FF', int32), & + register_mask=int(z'3FF', int32), & + generator_0=int(o'1167', int32), generator_1=int(o'1545', int32), & + outer_polynomial=int(z'80F', int32), & + outer_top_bit_mask=int(z'800', int32), & + outer_register_mask=int(z'FFF', int32), & + payload_bits=JTTY_TBCC_PAYLOAD_BITS, & + outer_check_bits=JTTY_TBCC_OUTER_CHECK_BITS, & + information_bits=JTTY_TBCC_INFORMATION_BITS) + + public :: jtty_tbcc_code_profile_is_valid + public :: jtty_tbcc_code_profile_is_supported + +contains + + pure logical function jtty_tbcc_code_profile_is_valid(profile) result(valid) + type(jtty_tbcc_code_profile), intent(in) :: profile + integer(int32) :: expected_state_count, expected_register_mask + + valid = .false. + if (profile%memory_nu < 1_int32 .or. profile%memory_nu > 20_int32) return + if (profile%constraint_length /= profile%memory_nu + 1_int32) return + expected_state_count = shiftl(1_int32, profile%memory_nu) + expected_register_mask = shiftl(1_int32, profile%constraint_length) - 1_int32 + if (profile%state_count /= expected_state_count) return + if (profile%state_mask /= expected_state_count - 1_int32) return + if (profile%register_mask /= expected_register_mask) return + if (profile%generator_0 <= 0_int32 .or. & + iand(profile%generator_0, not(profile%register_mask)) /= 0_int32) return + if (profile%generator_1 <= 0_int32 .or. & + iand(profile%generator_1, not(profile%register_mask)) /= 0_int32) return + if (profile%payload_bits /= JTTY_TBCC_PAYLOAD_BITS) return + if (profile%outer_check_bits /= JTTY_TBCC_OUTER_CHECK_BITS) return + if (profile%information_bits /= profile%payload_bits + profile%outer_check_bits) return + if (profile%outer_top_bit_mask /= & + shiftl(1_int32, profile%outer_check_bits - 1_int32)) return + if (profile%outer_register_mask /= & + shiftl(1_int32, profile%outer_check_bits) - 1_int32) return + if (profile%outer_polynomial <= 0_int32 .or. & + iand(profile%outer_polynomial, not(profile%outer_register_mask)) /= 0_int32) return + valid = .true. + end function jtty_tbcc_code_profile_is_valid + + pure logical function jtty_tbcc_code_profile_is_supported(profile) result(supported) + type(jtty_tbcc_code_profile), intent(in) :: profile + + supported = jtty_tbcc_code_profile_is_valid(profile) .and. & + jtty_tbcc_code_profiles_equal(profile, JTTY_TBCC_PROFILE_1167_1545_80F) + end function jtty_tbcc_code_profile_is_supported + + pure logical function jtty_tbcc_code_profiles_equal(left, right) result(equal) + type(jtty_tbcc_code_profile), intent(in) :: left, right + + equal = left%profile_id == right%profile_id .and. & + left%memory_nu == right%memory_nu .and. & + left%constraint_length == right%constraint_length .and. & + left%state_count == right%state_count .and. & + left%state_mask == right%state_mask .and. & + left%register_mask == right%register_mask .and. & + left%generator_0 == right%generator_0 .and. & + left%generator_1 == right%generator_1 .and. & + left%outer_polynomial == right%outer_polynomial .and. & + left%outer_top_bit_mask == right%outer_top_bit_mask .and. & + left%outer_register_mask == right%outer_register_mask .and. & + left%payload_bits == right%payload_bits .and. & + left%outer_check_bits == right%outer_check_bits .and. & + left%information_bits == right%information_bits + end function jtty_tbcc_code_profiles_equal + +end module jtty_tbcc_code_profiles diff --git a/lib/jtty/jtty_tbcc_decoder.f90 b/lib/jtty/jtty_tbcc_decoder.f90 new file mode 100644 index 00000000..c010331d --- /dev/null +++ b/lib/jtty/jtty_tbcc_decoder.f90 @@ -0,0 +1,151 @@ +module jtty_tbcc_decoder + use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64 + use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F + use jtty_tbcc_list_decoder, only: jtty_tbcc_decoder_plan, & + jtty_tbcc_decoder_workspace, jtty_tbcc_init_decoder_plan, & + jtty_tbcc_init_decoder_workspace, jtty_tbcc_list_wava_optimized, & + JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES + use tbcc, only: PAYLOAD_BITS + implicit none + private + + integer(int32), parameter :: COHERENT_LENGTHS(3) = [1_int32, 2_int32, 4_int32] + integer(int32), parameter :: CIRCULAR_PASSES = 2_int32 + + type, public :: jtty_tbcc_decode_result + integer(int32) :: accepted_hypothesis_rank = 0_int32 + integer(int32) :: exported_candidate_count = 0_int32 + integer(int32) :: circular_candidate_count = 0_int32 + integer(int32) :: coherent_block_length = 0_int32 + integer(int32) :: evaluated_rung_count = 0_int32 + integer(int64) :: accepted_identity = 0_int64 + real(real64) :: accepted_metric = -huge(0.0_real64) + logical :: used_half_symbol_observation = .false. + end type jtty_tbcc_decode_result + + type :: jtty_tbcc_rung_result + integer(int32) :: candidates(JTTY_TBCC_INFORMATION_BITS, & + JTTY_TBCC_MAX_HYPOTHESES) = 0_int32 + integer(int64) :: identities(JTTY_TBCC_MAX_HYPOTHESES) = 0_int64 + real(real64) :: clean_metrics(JTTY_TBCC_MAX_HYPOTHESES) = & + -huge(0.0_real64) + logical :: crc_valid(JTTY_TBCC_MAX_HYPOTHESES) = .false. + type(jtty_tbcc_decode_result) :: result + logical :: accepted = .false. + end type jtty_tbcc_rung_result + + logical, save :: decoders_initialized = .false. + type(jtty_tbcc_decoder_plan), save :: plans(3) + type(jtty_tbcc_decoder_workspace), save :: workspaces(3) + + public :: jtty_tbcc_decode + +contains + + subroutine jtty_tbcc_decode(correlations, half_correlations, payload, success, result) + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + complex(real32), intent(in) :: half_correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(out) :: payload(PAYLOAD_BITS) + logical, intent(out) :: success + type(jtty_tbcc_decode_result), intent(out), optional :: result + type(jtty_tbcc_decode_result) :: local_result + + !$omp critical(jtty_tbcc_decoder) + call initialize_decoders() + call decode_ladder(correlations, half_correlations, payload, success, local_result) + !$omp end critical(jtty_tbcc_decoder) + if (present(result)) result = local_result + end subroutine jtty_tbcc_decode + + subroutine initialize_decoders() + integer :: coherent_index + + if (decoders_initialized) return + + do coherent_index = 1, size(COHERENT_LENGTHS) + call jtty_tbcc_init_decoder_plan(plans(coherent_index), & + JTTY_TBCC_PROFILE_1167_1545_80F, & + COHERENT_LENGTHS(coherent_index), 4_int32, CIRCULAR_PASSES, & + JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspaces(coherent_index), & + plans(coherent_index)) + end do + decoders_initialized = .true. + end subroutine initialize_decoders + + subroutine decode_ladder(correlations, half_correlations, payload, success, result) + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + complex(real32), intent(in) :: half_correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(out) :: payload(PAYLOAD_BITS) + logical, intent(out) :: success + type(jtty_tbcc_decode_result), intent(out) :: result + type(jtty_tbcc_rung_result) :: decoded_rung + integer :: rung + + payload = 0_int32 + success = .false. + result = jtty_tbcc_decode_result() + do rung = 1, size(COHERENT_LENGTHS) + call decode_rung(correlations, rung, decoded_rung) + if (.not.decoded_rung%accepted) cycle + call accept_rung(decoded_rung, rung, .false., payload, success, result) + return + end do + + ! Half-symbol energies discard phase, so only L1 is meaningful here. + call decode_rung(half_correlations, 1, decoded_rung) + if (decoded_rung%accepted) then + call accept_rung(decoded_rung, 4, .true., payload, success, result) + else + result%evaluated_rung_count = 4_int32 + end if + end subroutine decode_ladder + + subroutine decode_rung(correlations, coherent_index, rung) + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer, intent(in) :: coherent_index + type(jtty_tbcc_rung_result), intent(out) :: rung + integer(int32) :: start_states(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: path_metrics(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: candidate_count, pool_count, rank + + rung = jtty_tbcc_rung_result() + call jtty_tbcc_list_wava_optimized(plans(coherent_index), & + workspaces(coherent_index), correlations, rung%candidates, rung%identities, & + rung%clean_metrics, path_metrics, start_states, rung%crc_valid, & + candidate_count, pool_count, prune_reserved_zero=.true.) + + rung%result = jtty_tbcc_decode_result( & + exported_candidate_count=candidate_count, & + circular_candidate_count=pool_count, & + coherent_block_length=COHERENT_LENGTHS(coherent_index)) + do rank = 1, candidate_count + if (.not.rung%crc_valid(rank)) cycle + ! Do not expand the fixed false-accept budget past the all-zero sentinel. + if (all(rung%candidates(1:PAYLOAD_BITS, rank) == 0_int32)) exit + rung%accepted = .true. + rung%result%accepted_hypothesis_rank = rank + rung%result%accepted_identity = rung%identities(rank) + rung%result%accepted_metric = rung%clean_metrics(rank) + exit + end do + end subroutine decode_rung + + subroutine accept_rung(rung, evaluated_rung_count, half_symbol, payload, success, result) + type(jtty_tbcc_rung_result), intent(in) :: rung + integer, intent(in) :: evaluated_rung_count + logical, intent(in) :: half_symbol + integer(int32), intent(out) :: payload(PAYLOAD_BITS) + logical, intent(out) :: success + type(jtty_tbcc_decode_result), intent(out) :: result + integer :: rank + + rank = rung%result%accepted_hypothesis_rank + payload = rung%candidates(1:PAYLOAD_BITS, rank) + success = .true. + result = rung%result + result%evaluated_rung_count = evaluated_rung_count + result%used_half_symbol_observation = half_symbol + end subroutine accept_rung + +end module jtty_tbcc_decoder diff --git a/lib/jtty/jtty_tbcc_list_decoder.f90 b/lib/jtty/jtty_tbcc_list_decoder.f90 new file mode 100644 index 00000000..ca4a4bd1 --- /dev/null +++ b/lib/jtty/jtty_tbcc_list_decoder.f90 @@ -0,0 +1,1168 @@ +module jtty_tbcc_list_decoder + use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64 + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + use jtty_tbcc_code_profiles, only: jtty_tbcc_code_profile, & + jtty_tbcc_code_profile_is_supported, JTTY_TBCC_INFORMATION_BITS + implicit none + private + + ! This module keeps decoder breadth and admission breadth separate. The + ! shorthand P1/P4 means retaining one/four distinct paths at every trellis + ! merge. H1/H4 means returning at most one/four unique, closed codewords to + ! the CRC admission layer. A wider path search therefore does not silently + ! increase the number of CRC hypotheses tested. + + public :: JTTY_TBCC_INFORMATION_BITS + integer(int32), parameter, public :: JTTY_TBCC_RESERVED_BIT = 33_int32 + integer(int32), parameter, public :: JTTY_TBCC_MAX_HYPOTHESES = 4_int32 + real(real64), parameter :: NEGATIVE_METRIC = -huge(0.0_real64) + + type :: survivor_t + logical :: valid = .false. + real(real64) :: metric = NEGATIVE_METRIC + integer(int32) :: origin_state = -1_int32 + integer(int32) :: bits(JTTY_TBCC_INFORMATION_BITS) = 0_int32 + end type survivor_t + + type :: pool_candidate_t + integer(int32) :: bits(JTTY_TBCC_INFORMATION_BITS) = 0_int32 + integer(int32) :: start_state = -1_int32 + integer(int64) :: identity = 0_int64 + real(real64) :: clean_metric = NEGATIVE_METRIC + real(real64) :: wava_metric = NEGATIVE_METRIC + logical :: crc_valid = .false. + end type pool_candidate_t + + integer(int32), parameter :: PACKED_ORIGIN_BITS = 11_int32 + integer(int32), parameter :: PACKED_VALID_BIT = JTTY_TBCC_INFORMATION_BITS + PACKED_ORIGIN_BITS + + type :: packed_survivor_t + real(real64) :: metric = NEGATIVE_METRIC + ! Low bits hold the input word in lexical order, then origin and validity. + ! Unwritten input bits stay zero, so integer order also orders every prefix. + integer(int64) :: key = 0_int64 + end type packed_survivor_t + + type, public :: jtty_tbcc_decoder_plan + private + ! Immutable trellis geometry and coherent branch tables shared by decodes. + logical :: initialized = .false. + type(jtty_tbcc_code_profile) :: code + integer(int32) :: coherent_length = 0_int32 + integer(int32) :: per_state_width = 0_int32 + integer(int32) :: wraps = 0_int32 + integer(int32) :: hypothesis_count = 0_int32 + integer(int32) :: state_count = 0_int32 + integer(int32) :: block_count = 0_int32 + integer(int32) :: max_branch_count = 0_int32 + integer(int32) :: pool_capacity = 0_int32 + integer(int32) :: hash_capacity = 0_int32 + integer(int32) :: energy_count = 0_int32 + integer(int32), allocatable :: next_state(:,:), tone(:,:) + integer(int32), allocatable :: block_starts(:), block_lengths(:) + integer(int32), allocatable :: branch_counts(:), energy_offsets(:) + integer(int32), allocatable :: branch_end_states(:,:,:) + integer(int32), allocatable :: branch_sequence_indices(:,:,:) + integer(int64), allocatable :: branch_identities(:,:) + end type jtty_tbcc_decoder_plan + + type, public :: jtty_tbcc_decoder_workspace + private + ! Reusable scratch storage keeps allocation outside the receiver hot path. + logical :: initialized = .false. + type(packed_survivor_t), allocatable :: previous(:,:), current(:,:) + type(pool_candidate_t), allocatable :: pool(:) + integer(int32), allocatable :: order(:), sort_scratch(:), hash_indices(:) + integer(int64), allocatable :: hash_keys(:) + real(real64), allocatable :: sequence_energies(:) + logical, allocatable :: hash_used(:) + end type jtty_tbcc_decoder_workspace + + public :: jtty_tbcc_transition + public :: jtty_tbcc_supertransition + public :: jtty_tbcc_coherent_metric + public :: jtty_tbcc_score_candidate + public :: jtty_tbcc_tailbiting_state + public :: jtty_tbcc_candidate_identity + public :: jtty_tbcc_crc_valid + public :: jtty_tbcc_list_wava + public :: jtty_tbcc_list_wava_reference + public :: jtty_tbcc_init_decoder_plan + public :: jtty_tbcc_init_decoder_workspace + public :: jtty_tbcc_list_wava_optimized + +contains + + pure subroutine jtty_tbcc_transition(code, state, input_bit, next_state, tone) + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: state, input_bit + integer(int32), intent(out) :: next_state, tone + integer(int32) :: output_register, out_b0, out_b1, state_mask + + state_mask = code%state_mask + output_register = iand(ior(shiftl(state, 1), input_bit), & + code%register_mask) + out_b0 = modulo(popcnt(iand(output_register, code%generator_0)), 2) + out_b1 = modulo(popcnt(iand(output_register, code%generator_1)), 2) + tone = 2_int32*out_b0 + ieor(out_b0, out_b1) + next_state = iand(output_register, state_mask) + end subroutine jtty_tbcc_transition + + pure subroutine jtty_tbcc_supertransition(code, start_state, input_bits, & + end_state, tones) + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: start_state + integer(int32), intent(in) :: input_bits(:) + integer(int32), intent(out) :: end_state + integer(int32), intent(out) :: tones(size(input_bits)) + integer(int32) :: offset, state + + state = start_state + do offset = 1, size(input_bits) + call jtty_tbcc_transition(code, state, input_bits(offset), & + end_state, tones(offset)) + state = end_state + end do + end_state = state + end subroutine jtty_tbcc_supertransition + + pure real(real64) function jtty_tbcc_coherent_metric(correlations, & + first_symbol, tones) result(metric) + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(in) :: first_symbol + integer(int32), intent(in) :: tones(:) + complex(real32) :: coherent_sum + integer(int32) :: offset + + coherent_sum = cmplx(0.0_real32, 0.0_real32, real32) + do offset = 1, size(tones) + coherent_sum = coherent_sum + & + correlations(tones(offset), first_symbol + offset - 1) + end do + metric = real(coherent_sum*conjg(coherent_sum), real64) / & + real(size(tones), real64) + end function jtty_tbcc_coherent_metric + + pure integer(int32) function jtty_tbcc_tailbiting_state(code, bits) & + result(state) + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bit_index, state_mask + + state = 0_int32 + state_mask = code%state_mask + do bit_index = JTTY_TBCC_INFORMATION_BITS - code%memory_nu + 1, & + JTTY_TBCC_INFORMATION_BITS + state = iand(ior(shiftl(state, 1), bits(bit_index)), state_mask) + end do + end function jtty_tbcc_tailbiting_state + + pure subroutine jtty_tbcc_score_candidate(code, correlations, & + coherent_length, bits, metric, closed) + type(jtty_tbcc_code_profile), intent(in) :: code + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(in) :: coherent_length + integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS) + real(real64), intent(out) :: metric + logical, intent(out) :: closed + integer(int32) :: block_length, block_start, end_state, next_state, start_state + integer(int32) :: tones(4) + + start_state = jtty_tbcc_tailbiting_state(code, bits) + end_state = start_state + metric = 0.0_real64 + do block_start = 1, JTTY_TBCC_INFORMATION_BITS, coherent_length + block_length = min(coherent_length, & + JTTY_TBCC_INFORMATION_BITS - block_start + 1_int32) + call jtty_tbcc_supertransition(code, end_state, & + bits(block_start:block_start + block_length - 1), next_state, & + tones(1:block_length)) + metric = metric + jtty_tbcc_coherent_metric(correlations, & + block_start, tones(1:block_length)) + end_state = next_state + end do + closed = end_state == start_state + end subroutine jtty_tbcc_score_candidate + + pure integer(int64) function jtty_tbcc_candidate_identity(bits) & + result(identity) + integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bit_index + + identity = 0_int64 + do bit_index = 1, JTTY_TBCC_INFORMATION_BITS + if (bits(bit_index) /= 0_int32) identity = ibset(identity, bit_index - 1) + end do + end function jtty_tbcc_candidate_identity + + pure logical function jtty_tbcc_crc_valid(code, bits) result(valid) + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bit_index, crc_register + + crc_register = 0_int32 + do bit_index = 1, JTTY_TBCC_INFORMATION_BITS + crc_register = ieor(crc_register, & + shiftl(bits(bit_index), code%outer_check_bits - 1_int32)) + if (iand(crc_register, code%outer_top_bit_mask) /= 0_int32) then + crc_register = ieor(shiftl(crc_register, 1), code%outer_polynomial) + else + crc_register = shiftl(crc_register, 1) + end if + crc_register = iand(crc_register, code%outer_register_mask) + end do + valid = crc_register == 0_int32 + end function jtty_tbcc_crc_valid + + subroutine jtty_tbcc_init_decoder_plan(plan, code, coherent_length, & + per_state_width, wraps, hypothesis_count) + type(jtty_tbcc_decoder_plan), intent(out) :: plan + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: coherent_length, per_state_width, wraps + integer(int32), intent(in) :: hypothesis_count + integer(int32) :: block_index, block_length, block_start, branch_word + integer(int32) :: end_state, input_bit, offset, state, tone_word + integer(int32) :: input_bits(4), tones(4) + integer(int64) :: branch_identity + + call validate_decoder_arguments(code, coherent_length, per_state_width, & + wraps, hypothesis_count) + if (code%memory_nu > PACKED_ORIGIN_BITS) error stop 'TBCC state does not fit packed survivor' + plan%code = code + plan%coherent_length = coherent_length + plan%per_state_width = per_state_width + plan%wraps = wraps + plan%hypothesis_count = hypothesis_count + plan%state_count = code%state_count + plan%block_count = (JTTY_TBCC_INFORMATION_BITS + coherent_length - 1_int32) / & + coherent_length + plan%max_branch_count = shiftl(1_int32, coherent_length) + plan%pool_capacity = plan%state_count*per_state_width + plan%hash_capacity = 1_int32 + do while (plan%hash_capacity < 2_int32*plan%pool_capacity) + plan%hash_capacity = 2_int32*plan%hash_capacity + end do + + allocate(plan%next_state(0:plan%state_count - 1, 0:1)) + allocate(plan%tone(0:plan%state_count - 1, 0:1)) + do input_bit = 0, 1 + do state = 0, plan%state_count - 1 + call jtty_tbcc_transition(code, state, input_bit, & + plan%next_state(state, input_bit), plan%tone(state, input_bit)) + end do + end do + + allocate(plan%block_starts(plan%block_count), plan%block_lengths(plan%block_count)) + allocate(plan%branch_counts(plan%block_count), plan%energy_offsets(plan%block_count)) + allocate(plan%branch_identities(0:plan%max_branch_count - 1, plan%block_count)) + allocate(plan%branch_end_states(0:plan%state_count - 1, & + 0:plan%max_branch_count - 1, plan%block_count)) + allocate(plan%branch_sequence_indices(0:plan%state_count - 1, & + 0:plan%max_branch_count - 1, plan%block_count)) + plan%branch_identities = 0_int64 + plan%branch_end_states = 0_int32 + plan%branch_sequence_indices = 0_int32 + plan%energy_count = 0_int32 + do block_index = 1, plan%block_count + block_start = 1_int32 + (block_index - 1_int32)*coherent_length + block_length = min(coherent_length, & + JTTY_TBCC_INFORMATION_BITS - block_start + 1_int32) + plan%block_starts(block_index) = block_start + plan%block_lengths(block_index) = block_length + plan%branch_counts(block_index) = shiftl(1_int32, block_length) + plan%energy_offsets(block_index) = plan%energy_count + 1_int32 + plan%energy_count = plan%energy_count + shiftl(1_int32, 2_int32*block_length) + do branch_word = 0, plan%branch_counts(block_index) - 1 + call unpack_branch_word(branch_word, block_length, input_bits) + branch_identity = 0_int64 + do offset = 1, block_length + if (input_bits(offset) /= 0_int32) & + branch_identity = ibset(branch_identity, JTTY_TBCC_INFORMATION_BITS - block_start - offset + 1_int32) + end do + plan%branch_identities(branch_word, block_index) = branch_identity + do state = 0, plan%state_count - 1 + call planned_supertransition(plan, state, input_bits, block_length, & + end_state, tones, tone_word) + plan%branch_end_states(state, branch_word, block_index) = end_state + plan%branch_sequence_indices(state, branch_word, block_index) = & + plan%energy_offsets(block_index) + tone_word + end do + end do + end do + plan%initialized = .true. + end subroutine jtty_tbcc_init_decoder_plan + + subroutine jtty_tbcc_init_decoder_workspace(workspace, plan) + type(jtty_tbcc_decoder_workspace), intent(out) :: workspace + type(jtty_tbcc_decoder_plan), intent(in) :: plan + + if (.not.plan%initialized) error stop 'TBCC list decoder plan is not initialized' + allocate(workspace%previous(0:plan%state_count - 1, plan%per_state_width)) + allocate(workspace%current(0:plan%state_count - 1, plan%per_state_width)) + allocate(workspace%pool(max(1_int32, plan%pool_capacity))) + allocate(workspace%order(max(1_int32, plan%pool_capacity))) + allocate(workspace%sort_scratch(max(1_int32, plan%pool_capacity))) + allocate(workspace%hash_keys(plan%hash_capacity)) + allocate(workspace%hash_indices(plan%hash_capacity)) + allocate(workspace%hash_used(plan%hash_capacity)) + allocate(workspace%sequence_energies(plan%energy_count)) + workspace%initialized = .true. + end subroutine jtty_tbcc_init_decoder_workspace + + subroutine jtty_tbcc_list_wava(correlations, code, coherent_length, & + per_state_width, wraps, hypothesis_count, candidate_bits, & + candidate_identities, candidate_clean_metrics, candidate_wava_metrics, & + candidate_start_states, candidate_crc_valid, candidate_count, pool_count, & + prune_reserved_zero, reference_bits, reference_present, & + reference_pool_rank, reference_h_rank) + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: coherent_length, per_state_width, wraps + integer(int32), intent(in) :: hypothesis_count + integer(int32), intent(out) :: candidate_bits(JTTY_TBCC_INFORMATION_BITS, hypothesis_count) + integer(int64), intent(out) :: candidate_identities(hypothesis_count) + real(real64), intent(out) :: candidate_clean_metrics(hypothesis_count) + real(real64), intent(out) :: candidate_wava_metrics(hypothesis_count) + integer(int32), intent(out) :: candidate_start_states(hypothesis_count) + logical, intent(out) :: candidate_crc_valid(hypothesis_count) + integer(int32), intent(out) :: candidate_count, pool_count + logical, intent(in), optional :: prune_reserved_zero + integer(int32), intent(in), optional :: reference_bits(JTTY_TBCC_INFORMATION_BITS) + logical, intent(out), optional :: reference_present + integer(int32), intent(out), optional :: reference_pool_rank, reference_h_rank + type(jtty_tbcc_decoder_plan) :: plan + type(jtty_tbcc_decoder_workspace) :: workspace + + call jtty_tbcc_init_decoder_plan(plan, code, coherent_length, & + per_state_width, wraps, hypothesis_count) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + candidate_bits, candidate_identities, candidate_clean_metrics, & + candidate_wava_metrics, candidate_start_states, candidate_crc_valid, & + candidate_count, pool_count, prune_reserved_zero, reference_bits, & + reference_present, reference_pool_rank, reference_h_rank) + end subroutine jtty_tbcc_list_wava + + subroutine jtty_tbcc_list_wava_optimized(plan, workspace, correlations, & + candidate_bits, candidate_identities, candidate_clean_metrics, & + candidate_wava_metrics, candidate_start_states, candidate_crc_valid, & + candidate_count, pool_count, prune_reserved_zero, reference_bits, & + reference_present, reference_pool_rank, reference_h_rank) + type(jtty_tbcc_decoder_plan), intent(in) :: plan + type(jtty_tbcc_decoder_workspace), intent(inout) :: workspace + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(out) :: candidate_bits(:, :) + integer(int64), intent(out) :: candidate_identities(:) + real(real64), intent(out) :: candidate_clean_metrics(:), candidate_wava_metrics(:) + integer(int32), intent(out) :: candidate_start_states(:) + logical, intent(out) :: candidate_crc_valid(:) + integer(int32), intent(out) :: candidate_count, pool_count + logical, intent(in), optional :: prune_reserved_zero + integer(int32), intent(in), optional :: reference_bits(JTTY_TBCC_INFORMATION_BITS) + logical, intent(out), optional :: reference_present + integer(int32), intent(out), optional :: reference_pool_rank, reference_h_rank + type(packed_survivor_t), allocatable :: swap_survivors(:,:) + integer(int32) :: block_index, hash_slot + integer(int32) :: output_rank, pool_index, rank, state, wrap + integer(int64) :: identity, reference_identity + real(real64) :: clean_metric + logical :: closed, found, prune, ordered_metrics + + call validate_optimized_storage(plan, workspace, candidate_bits, & + candidate_identities, candidate_clean_metrics, candidate_wava_metrics, & + candidate_start_states, candidate_crc_valid) + call precompute_sequence_energies(plan, correlations, workspace%sequence_energies) + ! Nonfinite metrics do not provide the monotone rank order needed by the cutoff. + ordered_metrics = all(ieee_is_finite(workspace%sequence_energies)) + call clear_packed_survivors(workspace%previous) + do state = 0, plan%state_count - 1 + workspace%previous(state, 1)%key = ibset(shiftl(int(state, int64), JTTY_TBCC_INFORMATION_BITS), PACKED_VALID_BIT) + workspace%previous(state, 1)%metric = 0.0_real64 + end do + + prune = .false. + if (present(prune_reserved_zero)) prune = prune_reserved_zero + do wrap = 1, plan%wraps + call reset_packed_frame_identity(workspace%previous) + do block_index = 1, plan%block_count + call advance_packed_survivors(plan, block_index, prune, workspace%sequence_energies, & + workspace%previous, workspace%current, ordered_metrics) + call move_alloc(workspace%previous, swap_survivors) + call move_alloc(workspace%current, workspace%previous) + call move_alloc(swap_survivors, workspace%current) + end do + end do + + pool_count = 0_int32 + workspace%hash_used = .false. + do state = 0, plan%state_count - 1 + do rank = 1, plan%per_state_width + if (.not.btest(workspace%previous(state, rank)%key, PACKED_VALID_BIT)) cycle + ! Tail-biting paths are eligible only when their final and remembered + ! initial states agree after the last wrap. + if (ibits(workspace%previous(state, rank)%key, & + JTTY_TBCC_INFORMATION_BITS, PACKED_ORIGIN_BITS) /= state) cycle + identity = reverse_identity(workspace%previous(state, rank)%key) + ! The same complete word can close through more than one retained path; + ! hash by all 46 bits before applying the global hypothesis limit. + call locate_identity(identity, workspace%hash_keys, workspace%hash_indices, & + workspace%hash_used, hash_slot, pool_index, found) + if (found) then + if (workspace%previous(state, rank)%metric > & + workspace%pool(pool_index)%wava_metric .or. & + (.not.(workspace%previous(state, rank)%metric < & + workspace%pool(pool_index)%wava_metric) .and. & + state < workspace%pool(pool_index)%start_state)) then + workspace%pool(pool_index)%wava_metric = & + workspace%previous(state, rank)%metric + workspace%pool(pool_index)%start_state = state + end if + cycle + end if + pool_count = pool_count + 1_int32 + pool_index = pool_count + workspace%hash_used(hash_slot) = .true. + workspace%hash_keys(hash_slot) = identity + workspace%hash_indices(hash_slot) = pool_index + workspace%pool(pool_index)%identity = identity + workspace%pool(pool_index)%start_state = state + workspace%pool(pool_index)%wava_metric = workspace%previous(state, rank)%metric + call unpack_identity(identity, workspace%pool(pool_index)%bits) + ! WAVA survivor metrics include history from earlier wraps. Admission + ! order is based on a clean, single-frame score of each complete word. + call score_planned_identity(plan, workspace%sequence_energies, identity, & + clean_metric, closed) + if (.not.closed) error stop 'closed TBCC survivor failed clean scoring closure' + workspace%pool(pool_index)%clean_metric = clean_metric + ! This flag reports the polynomial remainder only. Message admission, + ! including the protocol's all-zero rejection, remains with the caller. + workspace%pool(pool_index)%crc_valid = & + jtty_tbcc_crc_valid(plan%code, workspace%pool(pool_index)%bits) + end do + end do + + do pool_index = 1, pool_count + workspace%order(pool_index) = pool_index + end do + call sort_candidate_order_with_scratch(workspace%pool, workspace%order, & + workspace%sort_scratch, pool_count) + candidate_bits = 0_int32 + candidate_identities = 0_int64 + candidate_clean_metrics = NEGATIVE_METRIC + candidate_wava_metrics = NEGATIVE_METRIC + candidate_start_states = -1_int32 + candidate_crc_valid = .false. + candidate_count = min(plan%hypothesis_count, pool_count) + do output_rank = 1, candidate_count + pool_index = workspace%order(output_rank) + candidate_bits(:, output_rank) = workspace%pool(pool_index)%bits + candidate_identities(output_rank) = workspace%pool(pool_index)%identity + candidate_clean_metrics(output_rank) = workspace%pool(pool_index)%clean_metric + candidate_wava_metrics(output_rank) = workspace%pool(pool_index)%wava_metric + candidate_start_states(output_rank) = workspace%pool(pool_index)%start_state + candidate_crc_valid(output_rank) = workspace%pool(pool_index)%crc_valid + end do + + if (present(reference_present)) reference_present = .false. + if (present(reference_pool_rank)) reference_pool_rank = 0_int32 + if (present(reference_h_rank)) reference_h_rank = 0_int32 + if (present(reference_bits)) then + reference_identity = jtty_tbcc_candidate_identity(reference_bits) + do output_rank = 1, pool_count + pool_index = workspace%order(output_rank) + if (workspace%pool(pool_index)%identity /= reference_identity) cycle + if (present(reference_present)) reference_present = .true. + if (present(reference_pool_rank)) reference_pool_rank = output_rank + if (present(reference_h_rank)) then + if (output_rank <= candidate_count) reference_h_rank = output_rank + end if + exit + end do + end if + end subroutine jtty_tbcc_list_wava_optimized + + subroutine jtty_tbcc_list_wava_reference(correlations, code, coherent_length, & + per_state_width, wraps, hypothesis_count, candidate_bits, & + candidate_identities, candidate_clean_metrics, candidate_wava_metrics, & + candidate_start_states, candidate_crc_valid, candidate_count, pool_count, & + prune_reserved_zero, reference_bits, reference_present, & + reference_pool_rank, reference_h_rank) + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: coherent_length, per_state_width, wraps + integer(int32), intent(in) :: hypothesis_count + integer(int32), intent(out) :: candidate_bits(JTTY_TBCC_INFORMATION_BITS, hypothesis_count) + integer(int64), intent(out) :: candidate_identities(hypothesis_count) + real(real64), intent(out) :: candidate_clean_metrics(hypothesis_count) + real(real64), intent(out) :: candidate_wava_metrics(hypothesis_count) + integer(int32), intent(out) :: candidate_start_states(hypothesis_count) + logical, intent(out) :: candidate_crc_valid(hypothesis_count) + integer(int32), intent(out) :: candidate_count, pool_count + logical, intent(in), optional :: prune_reserved_zero + integer(int32), intent(in), optional :: reference_bits(JTTY_TBCC_INFORMATION_BITS) + logical, intent(out), optional :: reference_present + integer(int32), intent(out), optional :: reference_pool_rank + integer(int32), intent(out), optional :: reference_h_rank + type(survivor_t), allocatable :: previous(:,:), current(:,:) + type(pool_candidate_t), allocatable :: pool(:) + integer(int32), allocatable :: order(:), hash_indices(:) + integer(int32), allocatable :: block_starts(:), block_lengths(:) + integer(int32), allocatable :: branch_bits(:,:,:), branch_end_states(:,:,:) + integer(int64), allocatable :: hash_keys(:) + real(real64), allocatable :: branch_metrics(:,:,:) + logical, allocatable :: hash_used(:) + integer(int32) :: block_length, block_start, branch_count, branch_word + integer(int32) :: block_count, block_index, max_branch_count + integer(int32) :: state_count, state, rank, wrap, end_state, output_rank + integer(int32) :: input_bits(4), tones(4), pool_capacity, hash_capacity + integer(int32) :: pool_index, hash_slot + integer(int64) :: identity, reference_identity + real(real64) :: branch_metric, clean_metric + logical :: prune, closed, found + type(survivor_t) :: extension + + call validate_decoder_arguments(code, coherent_length, per_state_width, & + wraps, hypothesis_count) + state_count = code%state_count + block_count = (JTTY_TBCC_INFORMATION_BITS + coherent_length - 1_int32) / coherent_length + max_branch_count = shiftl(1_int32, coherent_length) + pool_capacity = state_count*per_state_width + hash_capacity = 1_int32 + do while (hash_capacity < 2_int32*pool_capacity) + hash_capacity = 2_int32*hash_capacity + end do + + allocate(previous(0:state_count - 1, per_state_width)) + allocate(current(0:state_count - 1, per_state_width)) + allocate(pool(max(1_int32, pool_capacity))) + allocate(order(max(1_int32, pool_capacity))) + allocate(hash_keys(hash_capacity), hash_indices(hash_capacity)) + allocate(hash_used(hash_capacity)) + allocate(block_starts(block_count), block_lengths(block_count)) + allocate(branch_bits(4, 0:max_branch_count - 1, block_count)) + allocate(branch_end_states(0:state_count - 1, 0:max_branch_count - 1, block_count)) + allocate(branch_metrics(0:state_count - 1, 0:max_branch_count - 1, block_count)) + branch_bits = 0_int32 + branch_end_states = 0_int32 + branch_metrics = 0.0_real64 + do block_index = 1, block_count + block_start = 1_int32 + (block_index - 1_int32)*coherent_length + block_length = min(coherent_length, & + JTTY_TBCC_INFORMATION_BITS - block_start + 1_int32) + block_starts(block_index) = block_start + block_lengths(block_index) = block_length + branch_count = shiftl(1_int32, block_length) + do branch_word = 0, branch_count - 1 + call unpack_branch_word(branch_word, block_length, input_bits) + branch_bits(:, branch_word, block_index) = input_bits + do state = 0, state_count - 1 + call jtty_tbcc_supertransition(code, state, & + input_bits(1:block_length), end_state, tones(1:block_length)) + branch_end_states(state, branch_word, block_index) = end_state + branch_metrics(state, branch_word, block_index) = & + jtty_tbcc_coherent_metric(correlations, block_start, & + tones(1:block_length)) + end do + end do + end do + call clear_survivors(previous) + do state = 0, state_count - 1 + previous(state, 1)%valid = .true. + previous(state, 1)%metric = 0.0_real64 + previous(state, 1)%origin_state = state + end do + + prune = .false. + if (present(prune_reserved_zero)) prune = prune_reserved_zero + do wrap = 1, wraps + call reset_frame_identity(previous) + do block_index = 1, block_count + block_start = block_starts(block_index) + block_length = block_lengths(block_index) + branch_count = shiftl(1_int32, block_length) + call clear_survivors(current) + do state = 0, state_count - 1 + do rank = 1, per_state_width + if (.not.previous(state, rank)%valid) cycle + do branch_word = 0, branch_count - 1 + if (prune .and. block_contains_reserved(block_start, block_length)) then + if (branch_bits(JTTY_TBCC_RESERVED_BIT - block_start + 1, & + branch_word, block_index) /= & + 0_int32) cycle + end if + end_state = branch_end_states(state, branch_word, block_index) + branch_metric = branch_metrics(state, branch_word, block_index) + extension = previous(state, rank) + extension%metric = extension%metric + branch_metric + extension%bits(block_start:block_start + block_length - 1) = & + branch_bits(1:block_length, branch_word, block_index) + call insert_survivor(current(end_state, :), extension, & + block_start + block_length - 1_int32) + end do + end do + end do + previous = current + end do + end do + + pool_count = 0_int32 + hash_used = .false. + hash_keys = 0_int64 + hash_indices = 0_int32 + do state = 0, state_count - 1 + do rank = 1, per_state_width + if (.not.previous(state, rank)%valid) cycle + if (previous(state, rank)%origin_state /= state) cycle + identity = jtty_tbcc_candidate_identity(previous(state, rank)%bits) + call locate_identity(identity, hash_keys, hash_indices, hash_used, & + hash_slot, pool_index, found) + if (found) then + if (previous(state, rank)%metric > pool(pool_index)%wava_metric .or. & + (.not.(previous(state, rank)%metric < pool(pool_index)%wava_metric) .and. & + state < pool(pool_index)%start_state)) then + pool(pool_index)%wava_metric = previous(state, rank)%metric + pool(pool_index)%start_state = state + end if + cycle + end if + pool_count = pool_count + 1_int32 + pool_index = pool_count + hash_used(hash_slot) = .true. + hash_keys(hash_slot) = identity + hash_indices(hash_slot) = pool_index + pool(pool_index)%bits = previous(state, rank)%bits + pool(pool_index)%identity = identity + pool(pool_index)%start_state = state + pool(pool_index)%wava_metric = previous(state, rank)%metric + call jtty_tbcc_score_candidate(code, correlations, coherent_length, & + pool(pool_index)%bits, clean_metric, closed) + if (.not.closed) error stop 'closed TBCC survivor failed clean scoring closure' + pool(pool_index)%clean_metric = clean_metric + pool(pool_index)%crc_valid = jtty_tbcc_crc_valid(code, pool(pool_index)%bits) + end do + end do + + do pool_index = 1, pool_count + order(pool_index) = pool_index + end do + call sort_candidate_order(pool, order, pool_count) + candidate_bits = 0_int32 + candidate_identities = 0_int64 + candidate_clean_metrics = NEGATIVE_METRIC + candidate_wava_metrics = NEGATIVE_METRIC + candidate_start_states = -1_int32 + candidate_crc_valid = .false. + candidate_count = min(hypothesis_count, pool_count) + do output_rank = 1, candidate_count + pool_index = order(output_rank) + candidate_bits(:, output_rank) = pool(pool_index)%bits + candidate_identities(output_rank) = pool(pool_index)%identity + candidate_clean_metrics(output_rank) = pool(pool_index)%clean_metric + candidate_wava_metrics(output_rank) = pool(pool_index)%wava_metric + candidate_start_states(output_rank) = pool(pool_index)%start_state + candidate_crc_valid(output_rank) = pool(pool_index)%crc_valid + end do + + if (present(reference_present)) reference_present = .false. + if (present(reference_pool_rank)) reference_pool_rank = 0_int32 + if (present(reference_h_rank)) reference_h_rank = 0_int32 + if (present(reference_bits)) then + reference_identity = jtty_tbcc_candidate_identity(reference_bits) + do output_rank = 1, pool_count + pool_index = order(output_rank) + if (pool(pool_index)%identity /= reference_identity) cycle + if (.not.all(pool(pool_index)%bits == reference_bits)) cycle + if (present(reference_present)) reference_present = .true. + if (present(reference_pool_rank)) reference_pool_rank = output_rank + if (present(reference_h_rank)) then + if (output_rank <= candidate_count) reference_h_rank = output_rank + end if + exit + end do + end if + + deallocate(previous, current, pool, order, hash_keys, hash_indices, hash_used) + deallocate(block_starts, block_lengths, branch_bits, branch_end_states, branch_metrics) + end subroutine jtty_tbcc_list_wava_reference + + + pure subroutine planned_supertransition(plan, start_state, input_bits, & + block_length, end_state, tones, tone_word) + type(jtty_tbcc_decoder_plan), intent(in) :: plan + integer(int32), intent(in) :: start_state, input_bits(4), block_length + integer(int32), intent(out) :: end_state, tones(4), tone_word + integer(int32) :: offset, state + + state = start_state + tones = 0_int32 + tone_word = 0_int32 + do offset = 1, block_length + tones(offset) = plan%tone(state, input_bits(offset)) + tone_word = 4_int32*tone_word + tones(offset) + state = plan%next_state(state, input_bits(offset)) + end do + end_state = state + end subroutine planned_supertransition + + subroutine precompute_sequence_energies(plan, correlations, energies) + type(jtty_tbcc_decoder_plan), intent(in) :: plan + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + real(real64), intent(out) :: energies(:) + complex(real32) :: coherent_sum + integer(int32) :: block_index, block_length, block_start + integer(int32) :: offset, sequence_count, sequence_word, tone + + do block_index = 1, plan%block_count + block_start = plan%block_starts(block_index) + block_length = plan%block_lengths(block_index) + sequence_count = shiftl(1_int32, 2_int32*block_length) + do sequence_word = 0, sequence_count - 1 + coherent_sum = cmplx(0.0_real32, 0.0_real32, real32) + do offset = 1, block_length + tone = ibits(sequence_word, 2_int32*(block_length - offset), 2) + coherent_sum = coherent_sum + correlations(tone, block_start + offset - 1_int32) + end do + energies(plan%energy_offsets(block_index) + sequence_word) = & + real(coherent_sum*conjg(coherent_sum), real64) / real(block_length, real64) + end do + end do + end subroutine precompute_sequence_energies + + subroutine score_planned_identity(plan, energies, identity, metric, closed) + type(jtty_tbcc_decoder_plan), intent(in) :: plan + real(real64), intent(in) :: energies(:) + integer(int64), intent(in) :: identity + real(real64), intent(out) :: metric + logical, intent(out) :: closed + integer(int32) :: bit_index, block_index, branch_word, offset, state, start_state + + start_state = 0_int32 + do bit_index = JTTY_TBCC_INFORMATION_BITS - plan%code%memory_nu + 1, & + JTTY_TBCC_INFORMATION_BITS + start_state = iand(ior(shiftl(start_state, 1), & + merge(1_int32, 0_int32, btest(identity, bit_index - 1))), & + plan%state_count - 1_int32) + end do + state = start_state + metric = 0.0_real64 + do block_index = 1, plan%block_count + branch_word = 0_int32 + do offset = 0, plan%block_lengths(block_index) - 1 + branch_word = 2_int32*branch_word + merge(1_int32, 0_int32, & + btest(identity, plan%block_starts(block_index) + offset - 1_int32)) + end do + metric = metric + energies( & + plan%branch_sequence_indices(state, branch_word, block_index)) + state = plan%branch_end_states(state, branch_word, block_index) + end do + closed = state == start_state + end subroutine score_planned_identity + + pure integer(int64) function reverse_identity(key) result(identity) + integer(int64), intent(in) :: key + integer(int32) :: bit_index + + identity = 0_int64 + do bit_index = 0, JTTY_TBCC_INFORMATION_BITS - 1 + if (btest(key, bit_index)) identity = ibset(identity, JTTY_TBCC_INFORMATION_BITS - bit_index - 1) + end do + end function reverse_identity + + pure subroutine unpack_identity(identity, bits) + integer(int64), intent(in) :: identity + integer(int32), intent(out) :: bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bit_index + + do bit_index = 1, JTTY_TBCC_INFORMATION_BITS + bits(bit_index) = merge(1_int32, 0_int32, btest(identity, bit_index - 1)) + end do + end subroutine unpack_identity + + subroutine clear_packed_survivors(survivors) + type(packed_survivor_t), intent(inout) :: survivors(0:, :) + integer(int32) :: rank, state + + do rank = 1, size(survivors, 2) + do state = 0, size(survivors, 1) - 1 + survivors(state, rank)%key = 0_int64 + survivors(state, rank)%metric = NEGATIVE_METRIC + end do + end do + end subroutine clear_packed_survivors + + subroutine reset_packed_frame_identity(survivors) + type(packed_survivor_t), intent(inout) :: survivors(0:, :) + integer(int32) :: rank, state + + do rank = 1, size(survivors, 2) + do state = 0, size(survivors, 1) - 1 + if (.not.btest(survivors(state, rank)%key, PACKED_VALID_BIT)) cycle + survivors(state, rank)%key = ibset(shiftl(int(state, int64), JTTY_TBCC_INFORMATION_BITS), PACKED_VALID_BIT) + end do + end do + end subroutine reset_packed_frame_identity + + subroutine advance_packed_survivors(plan, block_index, prune, energies, previous, current, ordered_metrics) + type(jtty_tbcc_decoder_plan), intent(in) :: plan + integer(int32), intent(in) :: block_index + logical, intent(in) :: prune, ordered_metrics + real(real64), intent(in) :: energies(:) + type(packed_survivor_t), intent(in) :: previous(0:, :) + type(packed_survivor_t), intent(inout) :: current(0:, :) + type(packed_survivor_t) :: selected(4), extension + integer(int32) :: branch_count, branch_word, end_state, state, state_stride + integer(int32) :: rank, width + integer(int64) :: branch_identity + real(real64) :: branch_metric, metric + logical :: prune_block + + width = plan%per_state_width + branch_count = plan%branch_counts(block_index) + state_stride = plan%state_count / branch_count + prune_block = prune .and. block_contains_reserved( & + plan%block_starts(block_index), plan%block_lengths(block_index)) + do end_state = 0, plan%state_count - 1 + selected%key = 0_int64 + branch_word = iand(end_state, branch_count - 1_int32) + branch_identity = plan%branch_identities(branch_word, block_index) + if (.not.(prune_block .and. btest(branch_identity, JTTY_TBCC_INFORMATION_BITS - JTTY_TBCC_RESERVED_BIT))) then + ! The low L destination bits are the input word; the discarded high + ! L source bits enumerate every predecessor in the original order. + do state = end_state / branch_count, plan%state_count - 1, state_stride + branch_metric = energies(plan%branch_sequence_indices(state, branch_word, block_index)) + do rank = 1, width + if (.not.btest(previous(state, rank)%key, PACKED_VALID_BIT)) cycle + metric = previous(state, rank)%metric + branch_metric + if (btest(selected(width)%key, PACKED_VALID_BIT)) then + if (metric < selected(width)%metric) then + ! Lower ranks receive the same branch metric and cannot recover. + if (ordered_metrics) exit + cycle + end if + end if + extension = previous(state, rank) + extension%metric = metric + extension%key = ior(extension%key, branch_identity) + call insert_packed_survivor(selected, width, extension, block_index == 1) + end do + end do + end if + do rank = 1, width + current(end_state, rank) = selected(rank) + end do + end do + end subroutine advance_packed_survivors + + subroutine insert_packed_survivor(survivors, width, candidate, deduplicate) + type(packed_survivor_t), intent(inout) :: survivors(4) + type(packed_survivor_t), intent(in) :: candidate + integer(int32), intent(in) :: width + logical, intent(in) :: deduplicate + integer(int32) :: insertion_slot, slot + + ! Resetting a wrap's origins and identities can duplicate a state's ranks. + ! After the first block, an origin and prefix determine exactly one path, + ! so extending distinct retained paths cannot create another duplicate. + if (deduplicate) then + do slot = 1, width + if (.not.btest(survivors(slot)%key, PACKED_VALID_BIT)) cycle + if (survivors(slot)%key == candidate%key) then + if (candidate%metric <= survivors(slot)%metric) return + do insertion_slot = 1, 3 + if (insertion_slot >= slot .and. insertion_slot < width) & + survivors(insertion_slot) = survivors(insertion_slot + 1) + end do + survivors(width)%key = 0_int64 + exit + end if + end do + end if + + insertion_slot = width + 1_int32 + do slot = 1, width + if (.not.btest(survivors(slot)%key, PACKED_VALID_BIT) .or. & + packed_survivor_precedes(candidate, survivors(slot))) then + insertion_slot = slot + exit + end if + end do + if (insertion_slot > width) return + do slot = 4, 2, -1 + if (slot <= width .and. slot > insertion_slot) survivors(slot) = survivors(slot - 1) + end do + survivors(insertion_slot) = candidate + end subroutine insert_packed_survivor + + pure logical function packed_survivor_precedes(left, right) & + result(precedes) + type(packed_survivor_t), intent(in) :: left, right + + if (left%metric > right%metric) then + precedes = .true. + return + else if (left%metric < right%metric) then + precedes = .false. + return + end if + precedes = left%key < right%key + end function packed_survivor_precedes + + subroutine validate_optimized_storage(plan, workspace, candidate_bits, & + candidate_identities, candidate_clean_metrics, candidate_wava_metrics, & + candidate_start_states, candidate_crc_valid) + type(jtty_tbcc_decoder_plan), intent(in) :: plan + type(jtty_tbcc_decoder_workspace), intent(in) :: workspace + integer(int32), intent(in) :: candidate_bits(:, :) + integer(int64), intent(in) :: candidate_identities(:) + real(real64), intent(in) :: candidate_clean_metrics(:), candidate_wava_metrics(:) + integer(int32), intent(in) :: candidate_start_states(:) + logical, intent(in) :: candidate_crc_valid(:) + + if (.not.plan%initialized) error stop 'TBCC list decoder plan is not initialized' + if (.not.workspace%initialized) & + error stop 'TBCC list decoder workspace is not initialized' + if (size(workspace%previous, 1) /= plan%state_count .or. & + size(workspace%previous, 2) /= plan%per_state_width .or. & + size(workspace%sequence_energies) /= plan%energy_count) & + error stop 'TBCC list decoder workspace does not match plan' + if (size(candidate_bits, 1) /= JTTY_TBCC_INFORMATION_BITS .or. & + size(candidate_bits, 2) < plan%hypothesis_count .or. & + size(candidate_identities) < plan%hypothesis_count .or. & + size(candidate_clean_metrics) < plan%hypothesis_count .or. & + size(candidate_wava_metrics) < plan%hypothesis_count .or. & + size(candidate_start_states) < plan%hypothesis_count .or. & + size(candidate_crc_valid) < plan%hypothesis_count) & + error stop 'TBCC list decoder output storage is too small' + end subroutine validate_optimized_storage + + + subroutine validate_decoder_arguments(code, coherent_length, per_state_width, & + wraps, hypothesis_count) + type(jtty_tbcc_code_profile), intent(in) :: code + integer(int32), intent(in) :: coherent_length, per_state_width, wraps + integer(int32), intent(in) :: hypothesis_count + if (.not.jtty_tbcc_code_profile_is_supported(code)) & + error stop 'TBCC list decoder requires a supported code profile' + if (coherent_length /= 1_int32 .and. coherent_length /= 2_int32 .and. & + coherent_length /= 4_int32) & + error stop 'TBCC list decoder supports coherent lengths 1, 2, and 4' + if (per_state_width < 1_int32 .or. per_state_width > 4_int32) & + error stop 'TBCC list decoder per-state width must be between 1 and 4' + if (wraps < 1_int32 .or. wraps > 2_int32) & + error stop 'TBCC list decoder supports one or two wraps' + if (hypothesis_count < 1_int32 .or. & + hypothesis_count > JTTY_TBCC_MAX_HYPOTHESES) & + error stop 'TBCC list decoder hypothesis count must be between 1 and 4' + end subroutine validate_decoder_arguments + + subroutine clear_survivors(survivors) + type(survivor_t), intent(inout) :: survivors(0:, :) + integer(int32) :: rank, state + + do rank = 1, size(survivors, 2) + do state = 0, size(survivors, 1) - 1 + survivors(state, rank)%valid = .false. + survivors(state, rank)%metric = NEGATIVE_METRIC + survivors(state, rank)%origin_state = -1_int32 + survivors(state, rank)%bits = 0_int32 + end do + end do + end subroutine clear_survivors + + subroutine reset_frame_identity(survivors) + type(survivor_t), intent(inout) :: survivors(0:, :) + integer(int32) :: rank, state + + do rank = 1, size(survivors, 2) + do state = 0, size(survivors, 1) - 1 + if (.not.survivors(state, rank)%valid) cycle + survivors(state, rank)%origin_state = state + survivors(state, rank)%bits = 0_int32 + end do + end do + end subroutine reset_frame_identity + + pure subroutine unpack_branch_word(branch_word, block_length, input_bits) + integer(int32), intent(in) :: branch_word, block_length + integer(int32), intent(out) :: input_bits(4) + integer(int32) :: offset + + input_bits = 0_int32 + do offset = 1, block_length + input_bits(offset) = ibits(branch_word, block_length - offset, 1) + end do + end subroutine unpack_branch_word + + pure logical function block_contains_reserved(block_start, block_length) & + result(contains_reserved) + integer(int32), intent(in) :: block_start, block_length + + contains_reserved = block_start <= JTTY_TBCC_RESERVED_BIT .and. & + block_start + block_length > JTTY_TBCC_RESERVED_BIT + end function block_contains_reserved + + subroutine insert_survivor(survivors, candidate, prefix_length) + type(survivor_t), intent(inout) :: survivors(:) + type(survivor_t), intent(in) :: candidate + integer(int32), intent(in) :: prefix_length + integer(int32) :: slot, insertion_slot + + do slot = 1, size(survivors) + if (.not.survivors(slot)%valid) cycle + if (survivors(slot)%origin_state /= candidate%origin_state) cycle + if (.not.all(survivors(slot)%bits(1:prefix_length) == & + candidate%bits(1:prefix_length))) cycle + if (candidate%metric <= survivors(slot)%metric) return + do insertion_slot = slot, size(survivors) - 1 + survivors(insertion_slot) = survivors(insertion_slot + 1) + end do + survivors(size(survivors))%valid = .false. + survivors(size(survivors))%metric = NEGATIVE_METRIC + survivors(size(survivors))%origin_state = -1_int32 + survivors(size(survivors))%bits = 0_int32 + exit + end do + + insertion_slot = size(survivors) + 1 + do slot = 1, size(survivors) + if (.not.survivors(slot)%valid .or. & + survivor_precedes(candidate, survivors(slot), prefix_length)) then + insertion_slot = slot + exit + end if + end do + if (insertion_slot > size(survivors)) return + do slot = size(survivors), insertion_slot + 1, -1 + survivors(slot) = survivors(slot - 1) + end do + survivors(insertion_slot) = candidate + end subroutine insert_survivor + + pure logical function survivor_precedes(left, right, prefix_length) result(precedes) + type(survivor_t), intent(in) :: left, right + integer(int32), intent(in) :: prefix_length + integer(int32) :: bit_index + + if (left%metric > right%metric) then + precedes = .true. + return + else if (left%metric < right%metric) then + precedes = .false. + return + else + precedes = left%metric > right%metric + end if + if (left%origin_state /= right%origin_state) then + precedes = left%origin_state < right%origin_state + return + end if + do bit_index = 1, prefix_length + if (left%bits(bit_index) == right%bits(bit_index)) cycle + precedes = left%bits(bit_index) < right%bits(bit_index) + return + end do + precedes = .false. + end function survivor_precedes + + subroutine locate_identity(identity, hash_keys, hash_indices, hash_used, & + hash_slot, pool_index, found) + integer(int64), intent(in) :: identity + integer(int64), intent(in) :: hash_keys(:) + integer(int32), intent(in) :: hash_indices(:) + logical, intent(in) :: hash_used(:) + integer(int32), intent(out) :: hash_slot, pool_index + logical, intent(out) :: found + + hash_slot = 1_int32 + int(modulo(identity, int(size(hash_keys), int64)), int32) + do + if (.not.hash_used(hash_slot)) then + pool_index = 0_int32 + found = .false. + return + end if + if (hash_keys(hash_slot) == identity) then + pool_index = hash_indices(hash_slot) + found = .true. + return + end if + hash_slot = hash_slot + 1_int32 + if (hash_slot > size(hash_keys)) hash_slot = 1_int32 + end do + end subroutine locate_identity + + subroutine sort_candidate_order(pool, order, count) + type(pool_candidate_t), intent(in) :: pool(:) + integer(int32), intent(inout) :: order(:) + integer(int32), intent(in) :: count + integer(int32), allocatable :: scratch(:) + + if (count <= 1_int32) return + allocate(scratch(count)) + call sort_candidate_order_with_scratch(pool, order, scratch, count) + deallocate(scratch) + end subroutine sort_candidate_order + + subroutine sort_candidate_order_with_scratch(pool, order, scratch, count) + type(pool_candidate_t), intent(in) :: pool(:) + integer(int32), intent(inout) :: order(:), scratch(:) + integer(int32), intent(in) :: count + integer(int32) :: left, middle, right, width + + if (count <= 1_int32) return + width = 1_int32 + do while (width < count) + left = 1_int32 + do while (left <= count) + middle = min(left + width, count + 1_int32) + right = min(left + 2_int32*width - 1_int32, count) + call merge_candidate_order(pool, order, scratch, left, middle, right) + left = left + 2_int32*width + end do + order(1:count) = scratch(1:count) + width = 2_int32*width + end do + end subroutine sort_candidate_order_with_scratch + + subroutine merge_candidate_order(pool, order, scratch, left, middle, right) + type(pool_candidate_t), intent(in) :: pool(:) + integer(int32), intent(in) :: order(:), left, middle, right + integer(int32), intent(inout) :: scratch(:) + integer(int32) :: left_cursor, right_cursor, output + + left_cursor = left + right_cursor = middle + do output = left, right + if (left_cursor >= middle) then + scratch(output) = order(right_cursor) + right_cursor = right_cursor + 1_int32 + else if (right_cursor > right) then + scratch(output) = order(left_cursor) + left_cursor = left_cursor + 1_int32 + else if (candidate_precedes(pool(order(left_cursor)), & + pool(order(right_cursor)))) then + scratch(output) = order(left_cursor) + left_cursor = left_cursor + 1_int32 + else + scratch(output) = order(right_cursor) + right_cursor = right_cursor + 1_int32 + end if + end do + end subroutine merge_candidate_order + + pure logical function candidate_precedes(left, right) result(precedes) + type(pool_candidate_t), intent(in) :: left, right + + if (left%clean_metric > right%clean_metric) then + precedes = .true. + else if (left%clean_metric < right%clean_metric) then + precedes = .false. + else if (left%identity /= right%identity) then + precedes = left%identity < right%identity + else if (left%start_state /= right%start_state) then + precedes = left%start_state < right%start_state + else + precedes = left%wava_metric > right%wava_metric + end if + end function candidate_precedes + +end module jtty_tbcc_list_decoder diff --git a/lib/jtty/jtty_tx_manual_checks.md b/lib/jtty/jtty_tx_manual_checks.md new file mode 100644 index 00000000..bcb4ff44 --- /dev/null +++ b/lib/jtty/jtty_tx_manual_checks.md @@ -0,0 +1,65 @@ +# JTTY transmit manual checks + +These checks cover MainWindow, PTT, and backend behavior that is outside the +FIFO unit-test boundary. + +- 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 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. +- Native macros: activate each default JTTY F1-F8 template by keyboard and by + clicking its button; verify both paths show the same canonical message and + enqueue the same number of frames. +- Native macros: enter a valid call and serial, send a call-plus-exchange + template, and verify EOM appears only on the final atom. +- Native macros: make a recognized template's runtime call or serial invalid + and verify transmission is rejected rather than sent as literal text. +- Literal fallback: customize a function-key template so it no longer matches + a native form and verify automatic packing preserves its expanded text after + the selected profile's normalization. +- Free entry: with MyCall K1ABC, compare F1 with typing `CQ K1ABC CQ` and + selecting Send message; verify the same text and one frame. Repeat with + `CQ K1ABC CQ CQ K1ABC CQ`, verifying two frames and unchanged spacing. +- External text: send `CQ K1ABC CQ`, `599 123`, `599 MA`, `599 FN42`, and + `1D EMA` from N1MM/MMTTY; verify each uses one frame and preserves the text. + With no special activity or with Field Day, send `599 001`, `599 05`, and + `599 BRUCE`; verify each uses two frames and preserves the text. +- Automatic profile: select RTTY Roundup and send `599 001` and + `K1ABC 599 001`; verify one and two frames respectively. Verify `599 123` + and `599 MA` use SERIAL and STATE_PROVINCE rather than generic atoms. + Verify `599 05` and `599 0123` become `599 005` and `599 123`, each in one + 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 + 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 + `599 001`; verify two and one frames. Exercise `unknown` and `field-day`, + the eight-argument waveform invocation, and rejection of an invalid value. +- Mixed text: send `HI WB9XYZ`, `TEST WB9XYZ`, and `K1ABC HELLO`; verify no + spaces are inserted or lost where TEXT5 and compact atoms meet. Send a + registered control phrase alone and embedded in a longer message. +- Queueing: queue two native messages and verify no visible or transmitted + TEXT5 spacing frame is inserted between them. +- Profile exchange: exercise `%E` with default serial, FIELD_DAY class/section, + and both RTTY serial and state/province payloads; verify canonical rendering + and rejection of a payload from the wrong profile. +- Grid macros: verify `%G` renders field-only GRID4 and exact `599 %G` renders + full-role GRID4; reject malformed locators. +- Settings migration: load unchanged old F2, F6, and F8 defaults using `%N` + and verify migration to `%E`; verify any edited variant remains literal. +- Windows/N1MM: load `JTTY Messages.mc`, exercise every tagged Run and S&P + action, and verify the `[[JTTY:ACTION]]` marker is consumed rather than + transmitted. Reject malformed tags, invalid profile payloads, and unknown + actions; verify untagged TXTEXT remains literal. Verify an all-rejected + transaction completes at OFF, and a rejected action followed by a valid + action still starts and completes only after the accepted audio drains. +- Windows/N1MM: in a two-radio configuration, verify entry-window focus, `!` + and `{CALL}` expansion, queued-call selection, `{LOGTHENPOP}`, and Run/S&P + state changes. Before adding a Run F11 call-stacking macro, capture its + TXTEXT ordering and verify that the leading tag, callsign, and exchange all + refer to the intended queued station. diff --git a/lib/jtty/jttyaudio.c b/lib/jtty/jttyaudio.c new file mode 100644 index 00000000..f4571117 --- /dev/null +++ b/lib/jtty/jttyaudio.c @@ -0,0 +1,376 @@ +#include <stdio.h> +#include <conio.h> +#include "portaudio.h" +#include <string.h> +#include <time.h> + +// Prototypes for Fortran subroutine update +void update_(int* ic1, int* ic2); + +int iaa; +int icc; +int n2send=0; +int ndebug=0; +double total_time=0.0; + +// Definition of structure pointing to the audio data +typedef struct +{ + int *iwrite; + int *itx; + int *TxOK; + int *Transmitting; + int *nwave; + int *nright; + int nring; + int nfs; + short *y1; + short *y2; + short *iwave; +} paTestData; + +// Input callback routine: +static int +SoundIn( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + paTestData *data = (paTestData*)userData; + short *in = (short*)inputBuffer; + unsigned int i; + static int ia=0; + +// Don't save audio input samples when we're transmitting + if(*data->Transmitting) return 0; + + if(outputBuffer == timeInfo) i=0; //Suppress 'unused' warnings + + if(statusFlags!=0) printf("Status flags %d\n",(int)statusFlags); + + if((statusFlags&1) == 0) { + //increment buffer pointers only if data available + ia=*data->iwrite; + if(*data->nright==0) { //Use left channel for input + for(i=0; i<framesPerBuffer; i++) { + data->y1[ia] = (*in++); + data->y2[ia] = (*in++); + ia++; + if(ia >= data->nring) ia=0; //Wrap buffer pointer if necessary + } + } else { //Use right channel + for(i=0; i<framesPerBuffer; i++) { + data->y2[ia] = (*in++); + data->y1[ia] = (*in++); + ia++; + if(ia >= data->nring) ia=0; //Wrap buffer pointer if necessary + } + } + } + + *data->iwrite = ia; //Save buffer pointer + iaa=ia; + total_time += (double)framesPerBuffer/12000.0; + return 0; +} + +// Output callback routine: +static int +SoundOut( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + paTestData *data = (paTestData*)userData; + short *wptr = (short*)outputBuffer; + unsigned int i; + static short int n2; + static int ic=0; + static int TxOKz=0; + static int nsent=0; + + if(inputBuffer == timeInfo) i=0; //Suppress 'unused' warnings + if(statusFlags!=0) printf("Status flags %d\n",(int)statusFlags); + + // if(ndebug>0) printf("SoundOut: %d %d %d\n",TxOKz,*data->TxOK,(int)framesPerBuffer); + + if(*data->TxOK && (!TxOKz)) ic=0; //Reset buffer pointer to start Tx + *data->Transmitting=*data->TxOK; //Set the "transmitting" flag + + if(*data->TxOK) { + if(!TxOKz) { + // Start of a transmission + nsent=0; + if(ndebug>0) printf("Start Tx %d %d\n",TxOKz,*data->TxOK); + } + TxOKz=*data->TxOK; + for(i=0 ; i < framesPerBuffer; i++ ) { + n2=data->iwave[ic]; + // addnoise_(&n2); + *wptr++ = n2; //left + *wptr++ = n2; //right + ic++; + + if(ic > n2send) { + *data->TxOK = 0; + *data->Transmitting = 0; + *data->iwrite = 0; //Reset Rx buffer pointer to 0 + TxOKz=0; //### ??? ### + ic=0; + if(ndebug>0) { + printf("TxT = %7.3f nSent = %d Frames = %7.3f\n",nsent/12000.0, + nsent,nsent/(53.0*384.0)); + } + break; + } + } + nsent += framesPerBuffer; + } else { + memset((void*)outputBuffer, 0, 2*sizeof(short)*framesPerBuffer); + } + *data->itx = icc; //Save buffer pointer + icc=ic; + return 0; +} + +/*******************************************************************/ +int jttyaudio_(int *ndevin, int *ndevout, int *npabuf, int *nright, + short y1[], short y2[], int *nring, int *iwrite, + int *itx, short iwave[], int *nwave, int *nfsample, + int *TxOK, int *Transmitting, int *ngo, int *ndebug0) + +{ + paTestData data; + PaStream *instream, *outstream; + PaStreamParameters inputParameters, outputParameters; + // PaStreamInfo *streamInfo; + + int nfpb = *npabuf; + int nSampleRate = *nfsample; + int ndevice_in = *ndevin; + int ndevice_out = *ndevout; + double dSampleRate = (double) *nfsample; + ndebug = *ndebug0; + PaError err_init, err_open_in, err_open_out, err_start_in, err_start_out; + PaError err = 0; + + data.iwrite = iwrite; + data.itx = itx; + data.TxOK = TxOK; + data.Transmitting = Transmitting; + data.y1 = y1; + data.y2 = y2; + data.nring = *nring; + data.nright = nright; + data.nwave = nwave; + data.iwave = iwave; + data.nfs = nSampleRate; + + err_init = Pa_Initialize(); // Initialize PortAudio + + if(err_init) { + printf("Error initializing PortAudio.\n"); + printf("\tErrortext: %s\n\tNumber: %d\n",Pa_GetErrorText(err_init), + err_init); + Pa_Terminate(); // I don't think we need this but... + return(-1); + } + + // printf("Opening device %d for input, %d for output...\n", + // ndevice_in,ndevice_out); + + inputParameters.device = ndevice_in; + inputParameters.channelCount = 2; + inputParameters.sampleFormat = paInt16; + inputParameters.suggestedLatency = 0.1; + inputParameters.hostApiSpecificStreamInfo = NULL; + +// Test if this configuration actually works, so we do not run into an +// ugly assertion + err_open_in = Pa_IsFormatSupported(&inputParameters, NULL, dSampleRate); + + if (err_open_in == 0) { + err_open_in = Pa_OpenStream( + &instream, //address of stream + &inputParameters, + NULL, + dSampleRate, //Sample rate + nfpb, //Frames per buffer + paNoFlag, + (PaStreamCallback *)SoundIn, //Callback routine + (void *)&data); //address of data structure + + if(err_open_in) { // We should have no error here usually + printf("Error opening input audio stream:\n"); + printf("\tErrortext: %s\n\tNumber: %d\n",Pa_GetErrorText(err_open_in), + err_open_in); + err = 1; + } else { + // printf("Successfully opened audio input.\n"); + } + } else { + printf("Error opening input audio stream.\n"); + printf("\tErrortext: %s\n\tNumber: %d\n",Pa_GetErrorText(err_open_in), + err_open_in); + err = 1; + } + + outputParameters.device = ndevice_out; + outputParameters.channelCount = 2; + outputParameters.sampleFormat = paInt16; + outputParameters.suggestedLatency = 0.2; + outputParameters.hostApiSpecificStreamInfo = NULL; + +// Test if this configuration actually works, so we do not run into an +// ugly assertion. + err_open_out = Pa_IsFormatSupported(NULL, &outputParameters, dSampleRate); + + if (err_open_out == 0) { + err_open_out = Pa_OpenStream( + &outstream, //address of stream + NULL, + &outputParameters, + dSampleRate, //Sample rate + nfpb, //Frames per buffer + paNoFlag, + (PaStreamCallback *)SoundOut, //Callback routine + (void *)&data); //address of data structure + + if(err_open_out) { // We should have no error here usually + printf("Error opening output audio stream!\n"); + printf("\tErrortext: %s\n\tNumber: %d\n",Pa_GetErrorText(err_open_out), + err_open_out); + err += 2; + } else { + // printf("Successfully opened audio output.\n"); + } + } else { + printf("Error opening output audio stream.\n"); + printf("\tErrortext: %s\n\tNumber: %d\n",Pa_GetErrorText(err_open_out), + err_open_out); + err += 2; + } + + // if there was no error in opening both streams start them + if (err == 0) { + err_start_in = Pa_StartStream(instream); //Start input stream + if(err_start_in) { + printf("Error starting input audio stream!\n"); + printf("\tErrortext: %s\n\tNumber: %d\n",Pa_GetErrorText(err_start_in), + err_start_in); + err += 4; + } + + err_start_out = Pa_StartStream(outstream); //Start output stream + if(err_start_out) { + printf("Error starting output audio stream!\n"); + printf("\tErrortext: %s\n\tNumber: %d\n",Pa_GetErrorText(err_start_out), + err_start_out); + err += 8; + } + } + + if (err != 0) printf("Error starting audio input or output.\n"); + + while( Pa_IsStreamActive(instream) && (*ngo != 0) && (err == 0) ) { + int ic1=0; + int ic2=0; + + if(_kbhit()) ic1 = _getch(); + if(_kbhit()) ic2 = _getch(); + + // if(ic1!=0 || ic2!=0) printf("%d %d %d\n",iaa,ic1,ic2); + // if(ic1!=0 && ic2==0) putchar(ic1); + + update_(&ic1,&ic2); + Pa_Sleep(100); + } + + Pa_AbortStream(instream); // Abort input stream + Pa_CloseStream(instream); // Close input stream, we're done. + Pa_AbortStream(outstream); // Abort output stream + Pa_CloseStream(outstream); // Close output stream, we're done. + + Pa_Terminate(); // Terminate PortAudio + + return(err); +} + + +int padevsub_(int *idevin, int *idevout) +{ + int numdev,ndefin,ndefout; + int nchin[101], nchout[101]; + int i, devIdx; + int numDevices; + const PaDeviceInfo *pdi; + PaError err; + + Pa_Initialize(); + numDevices = Pa_GetDeviceCount(); + numdev = numDevices; + + if( numDevices < 0 ) { + err = numDevices; + Pa_Terminate(); + return err; + } + + if ((devIdx = Pa_GetDefaultInputDevice()) > 0) { + ndefin = devIdx; + } else { + ndefin = 0; + } + + if ((devIdx = Pa_GetDefaultOutputDevice()) > 0) { + ndefout = devIdx; + } else { + ndefout = 0; + } + + if(*idevin < 0) { + printf("\nAudio Input Output Device Name\n"); + printf("Device Channels Channels\n"); + printf("------------------------------------------------------------------\n"); + + for( i=0; i < numDevices; i++ ) { + pdi = Pa_GetDeviceInfo(i); +// if(i == Pa_GetDefaultInputDevice()) ndefin = i; +// if(i == Pa_GetDefaultOutputDevice()) ndefout = i; + nchin[i]=pdi->maxInputChannels; + nchout[i]=pdi->maxOutputChannels; + printf(" %2d %2d %2d %s\n",i,nchin[i],nchout[i], + pdi->name); + } + printf("\nDefault devices: Input = %2d Output = %2d\n", + ndefin,ndefout); + } + + // printf("\nUser requested devices: Input = %2d Output = %2d\n", + // *idevin,*idevout); + if((*idevin<0) || (*idevin>=numdev)) *idevin=ndefin; + if((*idevout<0) || (*idevout>=numdev)) *idevout=ndefout; + if((*idevin==0) && (*idevout==0)) { + *idevin=ndefin; + *idevout=ndefout; + } + // printf("Will open devices: Input = %2d Output = %2d\n", + // *idevin,*idevout); + + Pa_Terminate(); + + return 0; +} + +void set_tx_length_(int* nwave) +{ + n2send=*nwave; + // printf("n2send = %d\n",n2send); +} + +void putchar_(int *n) +{ + putchar(*n); +} diff --git a/lib/jtty/jttycom.f90 b/lib/jtty/jttycom.f90 new file mode 100644 index 00000000..d6efab19 --- /dev/null +++ b/lib/jtty/jttycom.f90 @@ -0,0 +1,31 @@ +module jttycom + + implicit none + +! Variable Purpose +!--------------------------------------------------------------------------- + integer NMAX + parameter(NMAX=30*12000) !Ring buffer at 12000 samples/sec + real ftx !Tx audio frequency + integer iwrite !Pointer to Rx ring buffer + integer itx !Pointer to Tx buffer + integer ngo !Set to 0 to terminate audio streams + integer nTransmitting !Actually transmitting? + integer nTxOK !OK to transmit? + integer ndebug + logical ltx(5) !True if msg i has been transmitted + logical lrx(5) !True if msg i has been received + logical autoseq + logical QSO_in_progress + integer*2 y1(NMAX) !Ring buffer for audio channel 0 + integer*2 y2(NMAX) !Ring buffer for audio channel 1 + integer*2 iwave(NMAX) !Data for Tx audio + character*6 mycall + character*6 hiscall + character*6 hiscall_next + character*4 mygrid + character*4 exch + character*80 txmsg + save iwave,y1,y2 + +end module jttycom diff --git a/lib/jtty/portaudio.h b/lib/jtty/portaudio.h new file mode 100644 index 00000000..250fba02 --- /dev/null +++ b/lib/jtty/portaudio.h @@ -0,0 +1,1123 @@ + +#ifndef PORTAUDIO_H +#define PORTAUDIO_H +/* + * $Id: portaudio.h,v 1.1 2005/11/29 21:27:24 joe Exp $ + * PortAudio Portable Real-Time Audio Library + * PortAudio API Header File + * Latest version available at: http://www.portaudio.com/ + * + * Copyright (c) 1999-2002 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** @file + @brief The PortAudio API. +*/ + + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +/** Retrieve the release number of the currently running PortAudio build, + eg 1900. +*/ +int Pa_GetVersion( void ); + + +/** Retrieve a textual description of the current PortAudio build, + eg "PortAudio V19-devel 13 October 2002". +*/ +const char* Pa_GetVersionText( void ); + + +/** Error codes returned by PortAudio functions. + Note that with the exception of paNoError, all PaErrorCodes are negative. +*/ + +typedef int PaError; +typedef enum PaErrorCode +{ + paNoError = 0, + + paNotInitialized = -10000, + paUnanticipatedHostError, + paInvalidChannelCount, + paInvalidSampleRate, + paInvalidDevice, + paInvalidFlag, + paSampleFormatNotSupported, + paBadIODeviceCombination, + paInsufficientMemory, + paBufferTooBig, + paBufferTooSmall, + paNullCallback, + paBadStreamPtr, + paTimedOut, + paInternalError, + paDeviceUnavailable, + paIncompatibleHostApiSpecificStreamInfo, + paStreamIsStopped, + paStreamIsNotStopped, + paInputOverflowed, + paOutputUnderflowed, + paHostApiNotFound, + paInvalidHostApi, + paCanNotReadFromACallbackStream, /**< @todo review error code name */ + paCanNotWriteToACallbackStream, /**< @todo review error code name */ + paCanNotReadFromAnOutputOnlyStream, /**< @todo review error code name */ + paCanNotWriteToAnInputOnlyStream, /**< @todo review error code name */ + paIncompatibleStreamHostApi +} PaErrorCode; + + +/** Translate the supplied PortAudio error code into a human readable + message. +*/ +const char *Pa_GetErrorText( PaError errorCode ); + + +/** Library initialization function - call this before using PortAudio. + This function initialises internal data structures and prepares underlying + host APIs for use. This function MUST be called before using any other + PortAudio API functions. + + If Pa_Initialize() is called multiple times, each successful + call must be matched with a corresponding call to Pa_Terminate(). + Pairs of calls to Pa_Initialize()/Pa_Terminate() may overlap, and are not + required to be fully nested. + + Note that if Pa_Initialize() returns an error code, Pa_Terminate() should + NOT be called. + + @return paNoError if successful, otherwise an error code indicating the cause + of failure. + + @see Pa_Terminate +*/ +PaError Pa_Initialize( void ); + + +/** Library termination function - call this when finished using PortAudio. + This function deallocates all resources allocated by PortAudio since it was + initializied by a call to Pa_Initialize(). In cases where Pa_Initialise() has + been called multiple times, each call must be matched with a corresponding call + to Pa_Terminate(). The final matching call to Pa_Terminate() will automatically + close any PortAudio streams that are still open. + + Pa_Terminate() MUST be called before exiting a program which uses PortAudio. + Failure to do so may result in serious resource leaks, such as audio devices + not being available until the next reboot. + + @return paNoError if successful, otherwise an error code indicating the cause + of failure. + + @see Pa_Initialize +*/ +PaError Pa_Terminate( void ); + + + +/** The type used to refer to audio devices. Values of this type usually + range from 0 to (Pa_DeviceCount-1), and may also take on the PaNoDevice + and paUseHostApiSpecificDeviceSpecification values. + + @see Pa_DeviceCount, paNoDevice, paUseHostApiSpecificDeviceSpecification +*/ +typedef int PaDeviceIndex; + + +/** A special PaDeviceIndex value indicating that no device is available, + or should be used. + + @see PaDeviceIndex +*/ +#define paNoDevice ((PaDeviceIndex)-1) + + +/** A special PaDeviceIndex value indicating that the device(s) to be used + are specified in the host api specific stream info structure. + + @see PaDeviceIndex +*/ +#define paUseHostApiSpecificDeviceSpecification ((PaDeviceIndex)-2) + + +/* Host API enumeration mechanism */ + +/** The type used to enumerate to host APIs at runtime. Values of this type + range from 0 to (Pa_GetHostApiCount()-1). + + @see Pa_GetHostApiCount +*/ +typedef int PaHostApiIndex; + + +/** Retrieve the number of available host APIs. Even if a host API is + available it may have no devices available. + + @return A non-negative value indicating the number of available host APIs + or, a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + @see PaHostApiIndex +*/ +PaHostApiIndex Pa_GetHostApiCount( void ); + + +/** Retrieve the index of the default host API. The default host API will be + the lowest common denominator host API on the current platform and is + unlikely to provide the best performance. + + @return A non-negative value ranging from 0 to (Pa_GetHostApiCount()-1) + indicating the default host API index or, a PaErrorCode (which are always + negative) if PortAudio is not initialized or an error is encountered. +*/ +PaHostApiIndex Pa_GetDefaultHostApi( void ); + + +/** Unchanging unique identifiers for each supported host API. This type + is used in the PaHostApiInfo structure. The values are guaranteed to be + unique and to never change, thus allowing code to be written that + conditionally uses host API specific extensions. + + New type ids will be allocated when support for a host API reaches + "public alpha" status, prior to that developers should use the + paInDevelopment type id. + + @see PaHostApiInfo +*/ +typedef enum PaHostApiTypeId +{ + paInDevelopment=0, /* use while developing support for a new host API */ + paDirectSound=1, + paMME=2, + paASIO=3, + paSoundManager=4, + paCoreAudio=5, + paOSS=7, + paALSA=8, + paAL=9, + paBeOS=10, + paWDMKS=11, + paJACK=12 +} PaHostApiTypeId; + + +/** A structure containing information about a particular host API. */ + +typedef struct PaHostApiInfo +{ + /** this is struct version 1 */ + int structVersion; + /** The well known unique identifier of this host API @see PaHostApiTypeId */ + PaHostApiTypeId type; + /** A textual description of the host API for display on user interfaces. */ + const char *name; + + /** The number of devices belonging to this host API. This field may be + used in conjunction with Pa_HostApiDeviceIndexToDeviceIndex() to enumerate + all devices for this host API. + @see Pa_HostApiDeviceIndexToDeviceIndex + */ + int deviceCount; + + /** The the default input device for this host API. The value will be a + device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice + if no default input device is available. + */ + PaDeviceIndex defaultInputDevice; + + /** The the default output device for this host API. The value will be a + device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice + if no default output device is available. + */ + PaDeviceIndex defaultOutputDevice; + +} PaHostApiInfo; + + +/** Retrieve a pointer to a structure containing information about a specific + host Api. + + @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1) + + @return A pointer to an immutable PaHostApiInfo structure describing + a specific host API. If the hostApi parameter is out of range or an error + is encountered, the function returns NULL. + + The returned structure is owned by the PortAudio implementation and must not + be manipulated or freed. The pointer is only guaranteed to be valid between + calls to Pa_Initialize() and Pa_Terminate(). +*/ +const PaHostApiInfo * Pa_GetHostApiInfo( PaHostApiIndex hostApi ); + + +/** Convert a static host API unique identifier, into a runtime + host API index. + + @param type A unique host API identifier belonging to the PaHostApiTypeId + enumeration. + + @return A valid PaHostApiIndex ranging from 0 to (Pa_GetHostApiCount()-1) or, + a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + The paHostApiNotFound error code indicates that the host API specified by the + type parameter is not available. + + @see PaHostApiTypeId +*/ +PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type ); + + +/** Convert a host-API-specific device index to standard PortAudio device index. + This function may be used in conjunction with the deviceCount field of + PaHostApiInfo to enumerate all devices for the specified host API. + + @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1) + + @param hostApiDeviceIndex A valid per-host device index in the range + 0 to (Pa_GetHostApiInfo(hostApi)->deviceCount-1) + + @return A non-negative PaDeviceIndex ranging from 0 to (Pa_GetDeviceCount()-1) + or, a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + A paInvalidHostApi error code indicates that the host API index specified by + the hostApi parameter is out of range. + + A paInvalidDevice error code indicates that the hostApiDeviceIndex parameter + is out of range. + + @see PaHostApiInfo +*/ +PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi, + int hostApiDeviceIndex ); + + + +/** Structure used to return information about a host error condition. +*/ +typedef struct PaHostErrorInfo{ + PaHostApiTypeId hostApiType; /**< the host API which returned the error code */ + long errorCode; /**< the error code returned */ + const char *errorText; /**< a textual description of the error if available, otherwise a zero-length string */ +}PaHostErrorInfo; + + +/** Return information about the last host error encountered. The error + information returned by Pa_GetLastHostErrorInfo() will never be modified + asyncronously by errors occurring in other PortAudio owned threads + (such as the thread that manages the stream callback.) + + This function is provided as a last resort, primarily to enhance debugging + by providing clients with access to all available error information. + + @return A pointer to an immutable structure constaining information about + the host error. The values in this structure will only be valid if a + PortAudio function has previously returned the paUnanticipatedHostError + error code. +*/ +const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void ); + + + +/* Device enumeration and capabilities */ + +/** Retrieve the number of available devices. The number of available devices + may be zero. + + @return A non-negative value indicating the number of available devices or, + a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. +*/ +PaDeviceIndex Pa_GetDeviceCount( void ); + + +/** Retrieve the index of the default input device. The result can be + used in the inputDevice parameter to Pa_OpenStream(). + + @return The default input device index for the default host API, or paNoDevice + if no default input device is available or an error was encountered. +*/ +PaDeviceIndex Pa_GetDefaultInputDevice( void ); + + +/** Retrieve the index of the default output device. The result can be + used in the outputDevice parameter to Pa_OpenStream(). + + @return The default output device index for the defualt host API, or paNoDevice + if no default output device is available or an error was encountered. + + @note + On the PC, the user can specify a default device by + setting an environment variable. For example, to use device #1. +<pre> + set PA_RECOMMENDED_OUTPUT_DEVICE=1 +</pre> + The user should first determine the available device ids by using + the supplied application "pa_devs". +*/ +PaDeviceIndex Pa_GetDefaultOutputDevice( void ); + + +/** The type used to represent monotonic time in seconds that can be used + for syncronisation. The type is used for the outTime argument to the + PaStreamCallback and as the result of Pa_GetStreamTime(). + + @see PaStreamCallback, Pa_GetStreamTime +*/ +typedef double PaTime; + + +/** A type used to specify one or more sample formats. Each value indicates + a possible format for sound data passed to and from the stream callback, + Pa_ReadStream and Pa_WriteStream. + + The standard formats paFloat32, paInt16, paInt32, paInt24, paInt8 + and aUInt8 are usually implemented by all implementations. + + The floating point representation (paFloat32) uses +1.0 and -1.0 as the + maximum and minimum respectively. + + paUInt8 is an unsigned 8 bit format where 128 is considered "ground" + + The paNonInterleaved flag indicates that a multichannel buffer is passed + as a set of non-interleaved pointers. + + @see Pa_OpenStream, Pa_OpenDefaultStream, PaDeviceInfo + @see paFloat32, paInt16, paInt32, paInt24, paInt8 + @see paUInt8, paCustomFormat, paNonInterleaved +*/ +typedef unsigned long PaSampleFormat; + + +#define paFloat32 ((PaSampleFormat) 0x00000001) /**< @see PaSampleFormat */ +#define paInt32 ((PaSampleFormat) 0x00000002) /**< @see PaSampleFormat */ +#define paInt24 ((PaSampleFormat) 0x00000004) /**< Packed 24 bit format. @see PaSampleFormat */ +#define paInt16 ((PaSampleFormat) 0x00000008) /**< @see PaSampleFormat */ +#define paInt8 ((PaSampleFormat) 0x00000010) /**< @see PaSampleFormat */ +#define paUInt8 ((PaSampleFormat) 0x00000020) /**< @see PaSampleFormat */ +#define paCustomFormat ((PaSampleFormat) 0x00010000)/**< @see PaSampleFormat */ + +#define paNonInterleaved ((PaSampleFormat) 0x80000000) + +/** A structure providing information and capabilities of PortAudio devices. + Devices may support input, output or both input and output. +*/ +typedef struct PaDeviceInfo +{ + int structVersion; /* this is struct version 2 */ + const char *name; + PaHostApiIndex hostApi; /* note this is a host API index, not a type id*/ + + int maxInputChannels; + int maxOutputChannels; + + /* Default latency values for interactive performance. */ + PaTime defaultLowInputLatency; + PaTime defaultLowOutputLatency; + /* Default latency values for robust non-interactive applications (eg. playing sound files). */ + PaTime defaultHighInputLatency; + PaTime defaultHighOutputLatency; + + double defaultSampleRate; +} PaDeviceInfo; + + +/** Retrieve a pointer to a PaDeviceInfo structure containing information + about the specified device. + @return A pointer to an immutable PaDeviceInfo structure. If the device + parameter is out of range the function returns NULL. + + @param device A valid device index in the range 0 to (Pa_GetDeviceCount()-1) + + @note PortAudio manages the memory referenced by the returned pointer, + the client must not manipulate or free the memory. The pointer is only + guaranteed to be valid between calls to Pa_Initialize() and Pa_Terminate(). + + @see PaDeviceInfo, PaDeviceIndex +*/ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device ); + + +/** Parameters for one direction (input or output) of a stream. +*/ +typedef struct PaStreamParameters +{ + /** A valid device index in the range 0 to (Pa_GetDeviceCount()-1) + specifying the device to be used or the special constant + paUseHostApiSpecificDeviceSpecification which indicates that the actual + device(s) to use are specified in hostApiSpecificStreamInfo. + This field must not be set to paNoDevice. + */ + PaDeviceIndex device; + + /** The number of channels of sound to be delivered to the + stream callback or accessed by Pa_ReadStream() or Pa_WriteStream(). + It can range from 1 to the value of maxInputChannels in the + PaDeviceInfo record for the device specified by the device parameter. + */ + int channelCount; + + /** The sample format of the buffer provided to the stream callback, + a_ReadStream() or Pa_WriteStream(). It may be any of the formats described + by the PaSampleFormat enumeration. + */ + PaSampleFormat sampleFormat; + + /** The desired latency in seconds. Where practical, implementations should + configure their latency based on these parameters, otherwise they may + choose the closest viable latency instead. Unless the suggested latency + is greater than the absolute upper limit for the device implementations + shouldround the suggestedLatency up to the next practial value - ie to + provide an equal or higher latency than suggestedLatency whereever possibe. + Actual latency values for an open stream may be retrieved using the + inputLatency and outputLatency fields of the PaStreamInfo structure + returned by Pa_GetStreamInfo(). + @see default*Latency in PaDeviceInfo, *Latency in PaStreamInfo + */ + PaTime suggestedLatency; + + /** An optional pointer to a host api specific data structure + containing additional information for device setup and/or stream processing. + hostApiSpecificStreamInfo is never required for correct operation, + if not used it should be set to NULL. + */ + void *hostApiSpecificStreamInfo; + +} PaStreamParameters; + + +/** Return code for Pa_IsFormatSupported indicating success. */ +#define paFormatIsSupported (0) + +/** Determine whether it would be possible to open a stream with the specified + parameters. + + @param inputParameters A structure that describes the input parameters used to + open a stream. The suggestedLatency field is ignored. See PaStreamParameters + for a description of these parameters. inputParameters must be NULL for + output-only streams. + + @param outputParameters A structure that describes the output parameters used + to open a stream. The suggestedLatency field is ignored. See PaStreamParameters + for a description of these parameters. outputParameters must be NULL for + input-only streams. + + @param sampleRate The required sampleRate. For full-duplex streams it is the + sample rate for both input and output + + @return Returns 0 if the format is supported, and an error code indicating why + the format is not supported otherwise. The constant paFormatIsSupported is + provided to compare with the return value for success. + + @see paFormatIsSupported, PaStreamParameters +*/ +PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); + + + +/* Streaming types and functions */ + + +/** + A single PaStream can provide multiple channels of real-time + streaming audio input and output to a client application. A stream + provides access to audio hardware represented by one or more + PaDevices. Depending on the underlying Host API, it may be possible + to open multiple streams using the same device, however this behavior + is implementation defined. Portable applications should assume that + a PaDevice may be simultaneously used by at most one PaStream. + + Pointers to PaStream objects are passed between PortAudio functions that + operate on streams. + + @see Pa_OpenStream, Pa_OpenDefaultStream, Pa_OpenDefaultStream, Pa_CloseStream, + Pa_StartStream, Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive, + Pa_GetStreamTime, Pa_GetStreamCpuLoad + +*/ +typedef void PaStream; + + +/** Can be passed as the framesPerBuffer parameter to Pa_OpenStream() + or Pa_OpenDefaultStream() to indicate that the stream callback will + accept buffers of any size. +*/ +#define paFramesPerBufferUnspecified (0) + + +/** Flags used to control the behavior of a stream. They are passed as + parameters to Pa_OpenStream or Pa_OpenDefaultStream. Multiple flags may be + ORed together. + + @see Pa_OpenStream, Pa_OpenDefaultStream + @see paNoFlag, paClipOff, paDitherOff, paNeverDropInput, + paPrimeOutputBuffersUsingStreamCallback, paPlatformSpecificFlags +*/ +typedef unsigned long PaStreamFlags; + +/** @see PaStreamFlags */ +#define paNoFlag ((PaStreamFlags) 0) + +/** Disable default clipping of out of range samples. + @see PaStreamFlags +*/ +#define paClipOff ((PaStreamFlags) 0x00000001) + +/** Disable default dithering. + @see PaStreamFlags +*/ +#define paDitherOff ((PaStreamFlags) 0x00000002) + +/** Flag requests that where possible a full duplex stream will not discard + overflowed input samples without calling the stream callback. This flag is + only valid for full duplex callback streams and only when used in combination + with the paFramesPerBufferUnspecified (0) framesPerBuffer parameter. Using + this flag incorrectly results in a paInvalidFlag error being returned from + Pa_OpenStream and Pa_OpenDefaultStream. + + @see PaStreamFlags, paFramesPerBufferUnspecified +*/ +#define paNeverDropInput ((PaStreamFlags) 0x00000004) + +/** Call the stream callback to fill initial output buffers, rather than the + default behavior of priming the buffers with zeros (silence). This flag has + no effect for input-only and blocking read/write streams. + + @see PaStreamFlags +*/ +#define paPrimeOutputBuffersUsingStreamCallback ((PaStreamFlags) 0x00000008) + +/** A mask specifying the platform specific bits. + @see PaStreamFlags +*/ +#define paPlatformSpecificFlags ((PaStreamFlags)0xFFFF0000) + +/** + Timing information for the buffers passed to the stream callback. +*/ +typedef struct PaStreamCallbackTimeInfo{ + PaTime inputBufferAdcTime; + PaTime currentTime; + PaTime outputBufferDacTime; +} PaStreamCallbackTimeInfo; + + +/** + Flag bit constants for the statusFlags to PaStreamCallback. + + @see paInputUnderflow, paInputOverflow, paOutputUnderflow, paOutputOverflow, + paPrimingOutput +*/ +typedef unsigned long PaStreamCallbackFlags; + +/** In a stream opened with paFramesPerBufferUnspecified, indicates that + input data is all silence (zeros) because no real data is available. In a + stream opened without paFramesPerBufferUnspecified, it indicates that one or + more zero samples have been inserted into the input buffer to compensate + for an input underflow. + @see PaStreamCallbackFlags +*/ +#define paInputUnderflow ((PaStreamCallbackFlags) 0x00000001) + +/** In a stream opened with paFramesPerBufferUnspecified, indicates that data + prior to the first sample of the input buffer was discarded due to an + overflow, possibly because the stream callback is using too much CPU time. + Otherwise indicates that data prior to one or more samples in the + input buffer was discarded. + @see PaStreamCallbackFlags +*/ +#define paInputOverflow ((PaStreamCallbackFlags) 0x00000002) + +/** Indicates that output data (or a gap) was inserted, possibly because the + stream callback is using too much CPU time. + @see PaStreamCallbackFlags +*/ +#define paOutputUnderflow ((PaStreamCallbackFlags) 0x00000004) + +/** Indicates that output data will be discarded because no room is available. + @see PaStreamCallbackFlags +*/ +#define paOutputOverflow ((PaStreamCallbackFlags) 0x00000008) + +/** Some of all of the output data will be used to prime the stream, input + data may be zero. + @see PaStreamCallbackFlags +*/ +#define paPrimingOutput ((PaStreamCallbackFlags) 0x00000010) + +/** + Allowable return values for the PaStreamCallback. + @see PaStreamCallback +*/ +typedef enum PaStreamCallbackResult +{ + paContinue=0, + paComplete=1, + paAbort=2 +} PaStreamCallbackResult; + + +/** + Functions of type PaStreamCallback are implemented by PortAudio clients. + They consume, process or generate audio in response to requests from an + active PortAudio stream. + + @param input and @param output are arrays of interleaved samples, + the format, packing and number of channels used by the buffers are + determined by parameters to Pa_OpenStream(). + + @param frameCount The number of sample frames to be processed by + the stream callback. + + @param timeInfo The time in seconds when the first sample of the input + buffer was received at the audio input, the time in seconds when the first + sample of the output buffer will begin being played at the audio output, and + the time in seconds when the stream callback was called. + See also Pa_GetStreamTime() + + @param statusFlags Flags indicating whether input and/or output buffers + have been inserted or will be dropped to overcome underflow or overflow + conditions. + + @param userData The value of a user supplied pointer passed to + Pa_OpenStream() intended for storing synthesis data etc. + + @return + The stream callback should return one of the values in the + PaStreamCallbackResult enumeration. To ensure that the callback continues + to be called, it should return paContinue (0). Either paComplete or paAbort + can be returned to finish stream processing, after either of these values is + returned the callback will not be called again. If paAbort is returned the + stream will finish as soon as possible. If paComplete is returned, the stream + will continue until all buffers generated by the callback have been played. + This may be useful in applications such as soundfile players where a specific + duration of output is required. However, it is not necessary to utilise this + mechanism as Pa_StopStream(), Pa_AbortStream() or Pa_CloseStream() can also + be used to stop the stream. The callback must always fill the entire output + buffer irrespective of its return value. + + @see Pa_OpenStream, Pa_OpenDefaultStream + + @note With the exception of Pa_GetStreamCpuLoad() it is not permissable to call + PortAudio API functions from within the stream callback. +*/ +typedef int PaStreamCallback( + const void *input, void *output, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ); + + +/** Opens a stream for either input, output or both. + + @param stream The address of a PaStream pointer which will receive + a pointer to the newly opened stream. + + @param inputParameters A structure that describes the input parameters used by + the opened stream. See PaStreamParameters for a description of these parameters. + inputParameters must be NULL for output-only streams. + + @param outputParameters A structure that describes the output parameters used by + the opened stream. See PaStreamParameters for a description of these parameters. + outputParameters must be NULL for input-only streams. + + @param sampleRate The desired sampleRate. For full-duplex streams it is the + sample rate for both input and output + + @param framesPerBuffer The number of frames passed to the stream callback + function, or the preferred block granularity for a blocking read/write stream. + The special value paFramesPerBufferUnspecified (0) may be used to request that + the stream callback will recieve an optimal (and possibly varying) number of + frames based on host requirements and the requested latency settings. + Note: With some host APIs, the use of non-zero framesPerBuffer for a callback + stream may introduce an additional layer of buffering which could introduce + additional latency. PortAudio guarantees that the additional latency + will be kept to the theoretical minimum however, it is strongly recommended + that a non-zero framesPerBuffer value only be used when your algorithm + requires a fixed number of frames per stream callback. + + @param streamFlags Flags which modify the behaviour of the streaming process. + This parameter may contain a combination of flags ORed together. Some flags may + only be relevant to certain buffer formats. + + @param streamCallback A pointer to a client supplied function that is responsible + for processing and filling input and output buffers. If this parameter is NULL + the stream will be opened in 'blocking read/write' mode. In blocking mode, + the client can receive sample data using Pa_ReadStream and write sample data + using Pa_WriteStream, the number of samples that may be read or written + without blocking is returned by Pa_GetStreamReadAvailable and + Pa_GetStreamWriteAvailable respectively. + + @param userData A client supplied pointer which is passed to the stream callback + function. It could for example, contain a pointer to instance data necessary + for processing the audio buffers. This parameter is ignored if streamCallback + is NULL. + + @return + Upon success Pa_OpenStream() returns paNoError and places a pointer to a + valid PaStream in the stream argument. The stream is inactive (stopped). + If a call to Pa_OpenStream() fails, a non-zero error code is returned (see + PaError for possible error codes) and the value of stream is invalid. + + @see PaStreamParameters, PaStreamCallback, Pa_ReadStream, Pa_WriteStream, + Pa_GetStreamReadAvailable, Pa_GetStreamWriteAvailable +*/ +PaError Pa_OpenStream( PaStream** stream, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); + + +/** A simplified version of Pa_OpenStream() that opens the default input + and/or output devices. + + @param stream The address of a PaStream pointer which will receive + a pointer to the newly opened stream. + + @param numInputChannels The number of channels of sound that will be supplied + to the stream callback or returned by Pa_ReadStream. It can range from 1 to + the value of maxInputChannels in the PaDeviceInfo record for the default input + device. If 0 the stream is opened as an output-only stream. + + @param numOutputChannels The number of channels of sound to be delivered to the + stream callback or passed to Pa_WriteStream. It can range from 1 to the value + of maxOutputChannels in the PaDeviceInfo record for the default output dvice. + If 0 the stream is opened as an output-only stream. + + @param sampleFormat The sample format of both the input and output buffers + provided to the callback or passed to and from Pa_ReadStream and Pa_WriteStream. + sampleFormat may be any of the formats described by the PaSampleFormat + enumeration. + + @param sampleRate Same as Pa_OpenStream parameter of the same name. + @param framesPerBuffer Same as Pa_OpenStream parameter of the same name. + @param streamCallback Same as Pa_OpenStream parameter of the same name. + @param userData Same as Pa_OpenStream parameter of the same name. + + @return As for Pa_OpenStream + + @see Pa_OpenStream, PaStreamCallback +*/ +PaError Pa_OpenDefaultStream( PaStream** stream, + int numInputChannels, + int numOutputChannels, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamCallback *streamCallback, + void *userData ); + + +/** Closes an audio stream. If the audio stream is active it + discards any pending buffers as if Pa_AbortStream() had been called. +*/ +PaError Pa_CloseStream( PaStream *stream ); + + +/** Functions of type PaStreamFinishedCallback are implemented by PortAudio + clients. They can be registered with a stream using the Pa_SetStreamFinishedCallback + function. Once registered they are called when the stream becomes inactive + (ie once a call to Pa_StopStream() will not block). + A stream will become inactive after the stream callback returns non-zero, + or when Pa_StopStream or Pa_AbortStream is called. For a stream providing audio + output, if the stream callback returns paComplete, or Pa_StopStream is called, + the stream finished callback will not be called until all generated sample data + has been played. + + @param userData The userData parameter supplied to Pa_OpenStream() + + @see Pa_SetStreamFinishedCallback +*/ +typedef void PaStreamFinishedCallback( void *userData ); + + +/** Register a stream finished callback function which will be called when the + stream becomes inactive. See the description of PaStreamFinishedCallback for + further details about when the callback will be called. + + @param stream a pointer to a PaStream that is in the stopped state - if the + stream is not stopped, the stream's finished callback will remain unchanged + and an error code will be returned. + + @param streamFinishedCallback a pointer to a function with the same signature + as PaStreamFinishedCallback, that will be called when the stream becomes + inactive. Passing NULL for this parameter will un-register a previously + registered stream finished callback function. + + @return on success returns paNoError, otherwise an error code indicating the cause + of the error. + + @see PaStreamFinishedCallback +*/ +PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback ); + + +/** Commences audio processing. +*/ +PaError Pa_StartStream( PaStream *stream ); + + +/** Terminates audio processing. It waits until all pending + audio buffers have been played before it returns. +*/ +PaError Pa_StopStream( PaStream *stream ); + + +/** Terminates audio processing immediately without waiting for pending + buffers to complete. +*/ +PaError Pa_AbortStream( PaStream *stream ); + + +/** Determine whether the stream is stopped. + A stream is considered to be stopped prior to a successful call to + Pa_StartStream and after a successful call to Pa_StopStream or Pa_AbortStream. + If a stream callback returns a value other than paContinue the stream is NOT + considered to be stopped. + + @return Returns one (1) when the stream is stopped, zero (0) when + the stream is running or, a PaErrorCode (which are always negative) if + PortAudio is not initialized or an error is encountered. + + @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive +*/ +PaError Pa_IsStreamStopped( PaStream *stream ); + + +/** Determine whether the stream is active. + A stream is active after a successful call to Pa_StartStream(), until it + becomes inactive either as a result of a call to Pa_StopStream() or + Pa_AbortStream(), or as a result of a return value other than paContinue from + the stream callback. In the latter case, the stream is considered inactive + after the last buffer has finished playing. + + @return Returns one (1) when the stream is active (ie playing or recording + audio), zero (0) when not playing or, a PaErrorCode (which are always negative) + if PortAudio is not initialized or an error is encountered. + + @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamStopped +*/ +PaError Pa_IsStreamActive( PaStream *stream ); + + + +/** A structure containing unchanging information about an open stream. + @see Pa_GetStreamInfo +*/ + +typedef struct PaStreamInfo +{ + /** this is struct version 1 */ + int structVersion; + + /** The input latency of the stream in seconds. This value provides the most + accurate estimate of input latency available to the implementation. It may + differ significantly from the suggestedLatency value passed to Pa_OpenStream(). + The value of this field will be zero (0.) for output-only streams. + @see PaTime + */ + PaTime inputLatency; + + /** The output latency of the stream in seconds. This value provides the most + accurate estimate of output latency available to the implementation. It may + differ significantly from the suggestedLatency value passed to Pa_OpenStream(). + The value of this field will be zero (0.) for input-only streams. + @see PaTime + */ + PaTime outputLatency; + + /** The sample rate of the stream in Hertz (samples per second). In cases + where the hardware sample rate is inaccurate and PortAudio is aware of it, + the value of this field may be different from the sampleRate parameter + passed to Pa_OpenStream(). If information about the actual hardware sample + rate is not available, this field will have the same value as the sampleRate + parameter passed to Pa_OpenStream(). + */ + double sampleRate; + +} PaStreamInfo; + + +/** Retrieve a pointer to a PaStreamInfo structure containing information + about the specified stream. + @return A pointer to an immutable PaStreamInfo structure. If the stream + parameter invalid, or an error is encountered, the function returns NULL. + + @param stream A pointer to an open stream previously created with Pa_OpenStream. + + @note PortAudio manages the memory referenced by the returned pointer, + the client must not manipulate or free the memory. The pointer is only + guaranteed to be valid until the specified stream is closed. + + @see PaStreamInfo +*/ +const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream ); + + +/** Determine the current time for the stream according to the same clock used + to generate buffer timestamps. This time may be used for syncronising other + events to the audio stream, for example synchronizing audio to MIDI. + + @return The stream's current time in seconds, or 0 if an error occurred. + + @see PaTime, PaStreamCallback +*/ +PaTime Pa_GetStreamTime( PaStream *stream ); + + +/** Retrieve CPU usage information for the specified stream. + The "CPU Load" is a fraction of total CPU time consumed by a callback stream's + audio processing routines including, but not limited to the client supplied + stream callback. This function does not work with blocking read/write streams. + + This function may be called from the stream callback function or the + application. + + @return + A floating point value, typically between 0.0 and 1.0, where 1.0 indicates + that the stream callback is consuming the maximum number of CPU cycles possible + to maintain real-time operation. A value of 0.5 would imply that PortAudio and + the stream callback was consuming roughly 50% of the available CPU time. The + return value may exceed 1.0. A value of 0.0 will always be returned for a + blocking read/write stream, or if an error occurrs. +*/ +double Pa_GetStreamCpuLoad( PaStream* stream ); + + +/** Read samples from an input stream. The function doesn't return until + the entire buffer has been filled - this may involve waiting for the operating + system to supply the data. + + @param stream A pointer to an open stream previously created with Pa_OpenStream. + + @param buffer A pointer to a buffer of sample frames. The buffer contains + samples in the format specified by the inputParameters->sampleFormat field + used to open the stream, and the number of channels specified by + inputParameters->numChannels. If non-interleaved samples were requested, + buffer is a pointer to the first element of an array of non-interleaved + buffer pointers, one for each channel. + + @param frames The number of frames to be read into buffer. This parameter + is not constrained to a specific range, however high performance applications + will want to match this parameter to the framesPerBuffer parameter used + when opening the stream. + + @return On success PaNoError will be returned, or PaInputOverflowed if input + data was discarded by PortAudio after the previous call and before this call. +*/ +PaError Pa_ReadStream( PaStream* stream, + void *buffer, + unsigned long frames ); + + +/** Write samples to an output stream. This function doesn't return until the + entire buffer has been consumed - this may involve waiting for the operating + system to consume the data. + + @param stream A pointer to an open stream previously created with Pa_OpenStream. + + @param buffer A pointer to a buffer of sample frames. The buffer contains + samples in the format specified by the outputParameters->sampleFormat field + used to open the stream, and the number of channels specified by + outputParameters->numChannels. If non-interleaved samples were requested, + buffer is a pointer to the first element of an array of non-interleaved + buffer pointers, one for each channel. + + @param frames The number of frames to be written from buffer. This parameter + is not constrained to a specific range, however high performance applications + will want to match this parameter to the framesPerBuffer parameter used + when opening the stream. + + @return On success PaNoError will be returned, or paOutputUnderflowed if + additional output data was inserted after the previous call and before this + call. +*/ +PaError Pa_WriteStream( PaStream* stream, + const void *buffer, + unsigned long frames ); + + +/** Retrieve the number of frames that can be read from the stream without + waiting. + + @return Returns a non-negative value representing the maximum number of frames + that can be read from the stream without blocking or busy waiting or, a + PaErrorCode (which are always negative) if PortAudio is not initialized or an + error is encountered. +*/ +signed long Pa_GetStreamReadAvailable( PaStream* stream ); + + +/** Retrieve the number of frames that can be written to the stream without + waiting. + + @return Returns a non-negative value representing the maximum number of frames + that can be written to the stream without blocking or busy waiting or, a + PaErrorCode (which are always negative) if PortAudio is not initialized or an + error is encountered. +*/ +signed long Pa_GetStreamWriteAvailable( PaStream* stream ); + + +/* Miscellaneous utilities */ + + +/** Retrieve the size of a given sample format in bytes. + + @return The size in bytes of a single sample in the specified format, + or paSampleFormatNotSupported if the format is not supported. +*/ +PaError Pa_GetSampleSize( PaSampleFormat format ); + + +/** Put the caller to sleep for at least 'msec' milliseconds. This function is + provided only as a convenience for authors of portable code (such as the tests + and examples in the PortAudio distribution.) + + The function may sleep longer than requested so don't rely on this for accurate + musical timing. +*/ +void Pa_Sleep( long msec ); + + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PORTAUDIO_H */ diff --git a/lib/jtty/rjtty.f90 b/lib/jtty/rjtty.f90 new file mode 100644 index 00000000..16c6263e --- /dev/null +++ b/lib/jtty/rjtty.f90 @@ -0,0 +1,85 @@ +program rjtty + +! Decode JTTY data in one or more WAV files. + + use wavhdr + use jtty_mod + use jtty_mdec + +! MAX_FRAMES = 16 in pack_jtty. Each frame is +! 59 symbols (13 sync + 46 codeword). +! Maximum length of a transmission is +! 16*59*(symbol_duration). +! With baud rate 31.25 s^-1, symbol duration = 32 ms, +! so maximum txt = 16*59*0.032 = 30.208 s. + + parameter (NMAX=180*12000) !Max length of data + type(hdr) h + character*80 fname + character*8 arg + integer*2 iwave(NMAX) + logical success,newsig + + f0=1500.0 + ftol=50.0 + nsps = 384 + nfa=200 + nfb=2800 + + nargs=iargc() + if(nargs.lt.6) then + print*,'Usage: rjtty smin ndebug nsps f0 ftol fname [...]' + print*,'Examples: rjtty 4.6 0 384 1500 50 000000_000001.wav' + print*,' rjtty 4.6 1 240 1500 50 *.wav' + print*,'nsps choices are: 240, 320, 384, 480 samples/symbol' + go to 999 + endif + call getarg(1,arg) + read(arg,*) smin + call getarg(2,arg) + read(arg,*) ndebug + call getarg(3,arg) + read(arg,*) nsps + if(nsps .ne. 240 .and. nsps .ne. 320 .and. nsps .ne. 384 .and. nsps .ne. 480) then + print*,'nsps choices are: 240, 320, 384, 480 samples/symbol' + endif + call getarg(4,arg) + read(arg,*) f0 + call getarg(5,arg) + read(arg,*) ftol + + nframe = 59*nsps + nchunk = nframe + nframe/4 + ndecodes = 0 + + do ifile=1,nargs-5 + call getarg(ifile+5,fname) + open(10,file=fname,status='old',access='stream') + read(10) h + nwave=min(h%ndata/2,NMAX) + read(10) iwave(1:nwave) + close(10) + if(ndebug.gt.0) then + n=len_trim(fname) + write(*,'(a)') fname(n-16:n) + endif + if(nwave.lt.NMAX) iwave(nwave+1:NMAX) = 0 + ndecodes=0 + kchar=0 + istart=1 + nsync=0 + f1good = -99. + xdtgood = -99. + missed_syncs = 0 + newsig = .false. + +! Process data on the fly, one buffer at a time: + do while (istart+nchunk-1 .le. nwave) + success=.false. + call jtty_mdecode_step(iwave,nwave,istart,1,nchunk,nsps,ndebug,nfa,nfb,f0,ftol,smin) + call discard_pending_updates() + istart=istart+nframe/4 + enddo + enddo !ifile + +999 end program rjtty diff --git a/lib/jtty/rjtty_sub.f90 b/lib/jtty/rjtty_sub.f90 new file mode 100644 index 00000000..333d38b4 --- /dev/null +++ b/lib/jtty/rjtty_sub.f90 @@ -0,0 +1,102 @@ +subroutine rjtty_sub(iwave,kz,nsps,nfa,nfb,f0,ftol) + ! Unwindowed entry point: scans the whole buffer, exactly as before. + integer*2 iwave(kz) + call rjtty_core(iwave,kz,nsps,nfa,nfb,f0,ftol,1,kz) +end subroutine rjtty_sub + +subroutine rjtty_sub_windowed(iwave,kz,nsps,nfa,nfb,f0,ftol,istart0,istop) + ! Bounds the scan to [istart0,istop] (sample indices into iwave) instead + ! of the whole buffer -- e.g. a WideGraph click-driven re-decode that only + ! needs a window around a known time, not a full "decode again" pass. + integer*2 iwave(kz) + integer, intent(in) :: istart0,istop + call rjtty_core(iwave,kz,nsps,nfa,nfb,f0,ftol,istart0,istop) +end subroutine rjtty_sub_windowed + +subroutine rjtty_core(iwave,kz,nsps,nfa,nfb,f0,ftol,istart0,istop) + + use jtty_mdec + integer*2 iwave(kz) + integer, intent(in) :: istart0,istop + data kz0/9999999/,missed_syncs/0/,istart0_save/0/ + save istart,kz0,kchar,missed_syncs,ndtol,istart0_save + + if(nsps.ne.240 .and. nsps.ne.320 .and. nsps.ne.384 .and. nsps.ne.480) return + + nframe = 59*nsps + nchunk = nframe + nframe/4 + smin=4.6 + + ! A shorter/new buffer always restarts; a windowed call whose window has + ! moved (a new click) also restarts, even mid-buffer, so active assemblies + ! are not polluted by a previous window's in-progress messages. + if(kz .le. kz0 .or. istart0.ne.istart0_save) then + kz0=kz + istart=istart0 + kchar=0 + ndtol=0 + call reset_decode_search_state() + istart0_save=istart0 + go to 999 + endif + kzeff=min(kz,istop) + if(kzeff-istart+1 .lt. nchunk) return ! wait for enough data + + nsync=0 + do while (istart+nchunk-1 .le. kzeff) + ndebug=-1 + snr=-99.0 + call jtty_mdecode_step(iwave,kz,istart,istart0,nchunk,nsps,ndebug,nfa,nfb, & + f0,ftol,smin) + istart=istart+nframe/4 + enddo + +999 return +end subroutine rjtty_core + +subroutine jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + + use iso_fortran_env, only: int64 + use jtty_mdec + integer, parameter :: BATCH_SIZE = 30 + integer, parameter :: MESSAGE_LENGTH = 80 + character(len=BATCH_SIZE*MESSAGE_LENGTH), intent(out) :: text_blocks + integer(int64), intent(out) :: message_ids(BATCH_SIZE) + real, intent(out) :: frequencies(BATCH_SIZE) + real, intent(out) :: start_tsync(BATCH_SIZE) + logical*1, intent(out) :: eom(BATCH_SIZE) + integer, intent(out) :: count + character(len=MESSAGE_LENGTH) :: msg + integer :: i,index,offset + + text_blocks='' + message_ids=0_int64 + frequencies=0.0 + start_tsync=0.0 + eom=.false. + count=min(npending,BATCH_SIZE) + + do i=1,count + index=pending_first+i-1 + msg=display_message_text(pending_updates(index)%decoded) + offset=(i-1)*MESSAGE_LENGTH + text_blocks(offset+1:offset+MESSAGE_LENGTH)=msg + message_ids(i)=pending_updates(index)%message_id + frequencies(i)=pending_updates(index)%f1 + start_tsync(i)=pending_updates(index)%start_tsync + eom(i)=pending_updates(index)%complete + enddo + + ! Pending membership is the delivery guarantee; remove records only after copying them out. + pending_first=pending_first+count + npending=npending-count + if(npending.eq.0) then + pending_first=1 + if(allocated(pending_updates)) then + if(size(pending_updates).gt.MAX_ACTIVE_MESSAGES) then + deallocate(pending_updates) + allocate(pending_updates(MAX_ACTIVE_MESSAGES)) + endif + endif + endif +end subroutine jtty_get_updates diff --git a/lib/jtty/sjtty.f90 b/lib/jtty/sjtty.f90 new file mode 100644 index 00000000..16d4324a --- /dev/null +++ b/lib/jtty/sjtty.f90 @@ -0,0 +1,258 @@ +program sjtty + + ! Simulate received data for JTTY, a mode operationally similar to RTTY + ! but providing much better performance and reliability. + + ! Messages are source-encoded into 34-bit blocks. A 12-bit CRC is + ! added to create a 46 bit payload, which is then FEC-encoded using + ! a tail-biting rate-1/2 convolutional code (K=10) to create 92-bit + ! (46-symbol) codewords. + + ! Modulation is 4FSK at 12000/NSPS = 31.25 baud. Each transmitted frame + ! consists of 13 sync symbols followed by 46 codeword symbols. + + use wavhdr + use jtty_mod ! This module provides NSPS + use jtty_fec + + parameter (MAX_TONES=59*16) !Max number of channel symbols + character*12 arg !Command line argument + character*2 arg4 !The 4th command-line argument + character*80 umsg !User-formatted message + character(len=80) :: profile_option + integer :: exchange_profile,arg_offset + character*40 fname !Output file name + character*34 c32(16) + complex, allocatable :: cwave(:) !Complex generated waveform (12000 Hz) + complex, allocatable :: c0(:) !With propagation degradation + complex, allocatable :: c(:) !With propagation degradation + real, allocatable :: wave(:) !Real generated waveform (12000 Hz) + type(hdr) h !Header for .wav file + integer itone(MAX_TONES) !Array of tone frequencies for this message + integer*2, allocatable :: iwave(:) !Data written to the *.wav file + integer payload(PAYLOAD_BITS) + integer tone_symbols(TOTAL_K) + logical itu_model !True if fdop, delay are from an ITU model + + nargs=iargc() + exchange_profile=JTTY_EXCHANGE_UNKNOWN + arg_offset=0 + if(nargs.gt.0) then + call getarg(1,profile_option) + if(index(profile_option,'--exchange-profile=').eq.1) then + select case(trim(profile_option(20:))) + case('unknown'); exchange_profile=JTTY_EXCHANGE_UNKNOWN + case('field-day'); exchange_profile=JTTY_EXCHANGE_FIELD_DAY + case('rtty-roundup'); exchange_profile=JTTY_EXCHANGE_RTTY + case default + print*,'Invalid exchange profile: use unknown, field-day, or rtty-roundup' + stop 1 + end select + arg_offset=1 + nargs=nargs-1 + endif + endif + if(nargs.eq.1) then + call getarg(1+arg_offset,umsg) + call pack_jtty(umsg,c32,nframes,exchange_profile) + if(nframes.lt.0) then + print*,'Message exceeds JTTY encoding limits after exchange normalization' + stop 1 + endif + call unpack_jtty(c32,nframes,umsg) + do while (index(umsg,'~') .ne. 0) + i1=index(umsg,'~') + umsg(i1:i1)=' ' + enddo + write(*,'(a,a)') "Message after pack/unpack : ",trim(umsg) + nsps=384 + if(nframes.eq.1) then + write(*,'(i4,a,f5.2,a)') nframes," frame, Transmission length ", & + 59*nframes*nsps/12000.0," seconds" + else + write(*,'(i4,a,f5.2,a)') nframes," frames, Transmission length ", & + 59*nframes*nsps/12000.0," seconds" + endif + go to 999 + else if(nargs.ne.8) then + print*,'Usage: sjtty message' + print*,'Example: sjtty "CQ DX KA1ABC"' + print*,'or' + print*,'Usage: sjtty message f0 DT fdop del nsps nfiles SNR' + print*,'Example: sjtty "CQ K1ABC CQ" 1500 0.0 0.5 1 384 10 -10' + print*,'Optional first argument: --exchange-profile=unknown|field-day|rtty-roundup' + print*,'ITU propagation models: set fdop to AW LQ LM LD MQ MM MD HQ HM HD' + print*,'nsps: 240, 320, 384, or 480' + go to 999 + endif + + call getarg(1+arg_offset,umsg) !User message + call getarg(2+arg_offset,arg) + read(arg,*) f0 !Frequency of lowest tone + call getarg(3+arg_offset,arg) + read(arg,*) xdt !Time offset (positive only) + call getarg(4+arg_offset,arg) + itu_model=.true. + arg4=arg(1:2) + if(arg(1:2).eq.'LQ') then !ITU params for Low Latitude Quiet + fspread=0.5 + delay=0.5 + else if(arg(1:2).eq.'LM') then !Low Latitude Moderate + fspread=1.5 + delay=2.0 + else if(arg(1:2).eq.'LD') then !Low Latitude Disturbed + fspread=10.0 + delay=6.0 + else if(arg(1:2).eq.'MQ') then !Mid Latitude ... etc. + fspread=0.1 + delay=0.5 + else if(arg(1:2).eq.'MM') then + fspread=0.5 + delay=1.0 + else if(arg(1:2).eq.'MD') then + fspread=1.0 + delay=2.0 + else if(arg(1:2).eq.'HQ') then + fspread=0.5 + delay=1.0 + else if(arg(1:2).eq.'HM') then + fspread=10.0 + delay=3.0 + else if(arg(1:2).eq.'HD') then + fspread=30.0 + delay=7.0 + else if(arg(1:2).eq.'AW') then + fspread=0.0 + delay=0.0 + else + itu_model=.false. + read(arg,*) fspread !Watterson frequency spread (Hz) + call getarg(5+arg_offset,arg) + read(arg,*) delay !Watterson delay (ms) + endif + call getarg(6+arg_offset,arg) + read(arg,*) nsps !Number of files + if(nsps.ne.240 .and. nsps.ne.320 .and. nsps.ne.384 .and. nsps.ne.480) then + print*,'nsps: 240, 320, 384, or 480' + stop + endif + call getarg(7+arg_offset,arg) + read(arg,*) nfiles !Number of files + call getarg(8+arg_offset,arg) + read(arg,*) snrdb !SNR in 2500 Hz bandwidth + + fsample=12000.0 + dt=1.0/fsample + twopi=8.0*atan(1.0) + bandwidth_ratio=2500.0/(fsample/2.0) + sig=sqrt(2*bandwidth_ratio) * 10.0**(0.05*snrdb) + if(snrdb.gt.90.0) sig=1.0 + + bt=2.0 !Default bt=2 (smaller ==> more smoothing) + baud=fsample/nsps !Symbol rate + bw=4.0*baud !Signal bandwidth + hmod=1.0 !Modulation index + + call pack_jtty(umsg,c32,nframes,exchange_profile) + if(nframes.lt.0) then + print*,'Message exceeds JTTY encoding limits after exchange normalization' + stop 1 + endif + nsym=0 + do i=1,nframes + read(c32(i),'(34i1)') payload + call tbcc_encode(payload,tone_symbols,JTTY_TBCC_PROFILE_1167_1545_80F) + ib=(i-1)*59+1 ! 59 tones per frame + itone(ib:ib+12)=is13 + itone(ib+13:ib+58)=tone_symbols + nsym=nsym+59 + enddo + + txt=nsym*nsps*dt !Transmission length (s) + numsg=len(trim(umsg)) + write(*,1012) trim(umsg) +1012 format('User message: ',a) + write(*,1013) nsps,txt,nsym,itone(1:nsym) +1013 format('nsps:',i5,' samples/symbol ','Transmission length:',f5.1, & + ' s,',i5,' channel symbols:'/ & + (30i2)) + + nwave=nsps*nsym !Length of i*2 data written to *.wav file + npts=2**(int(log(float(nwave)+xdt/dt)/log(2.0) + 0.9999)) !Round up to integer power of 2 + iz=nint(xdt/dt) + nwave + nsps*59 !Add one frame of noise at end + nbuf=max(nwave,npts,iz) + + allocate(cwave(0:nwave-1)) + allocate(c0(0:nbuf-1)) + allocate(c(0:nbuf-1)) + allocate(wave(1:nbuf)) + allocate(iwave(1:nbuf)) + + icmplx=1 + call gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave) + + + write(*,1000) f0,xdt,txt,snrdb,bw +1000 format('f0:',f7.1,' DT:',f6.2,' TxT:',f6.1,' SNR:',f6.1,' BW:',f6.1) + cps=baud/7.0 + cps_effective=numsg/txt + write(*,1001) cps,cps_effective +1001 format('Raw character rate:',f5.1,' c/s Effective character rate:',f5.1,' c/s') + write(*,1002) fspread,delay +1002 format('Fspread:',f5.1,' Hz Delay:',f5.1,' ms') + if(itu_model) write(*,1003) arg4 +1003 format('ITU propagation model: ',a2) + write(*,*) + +! call sgran() + + do ifile=1,nfiles + c0=0. + c0(0:nwave-1)=cwave(0:nwave-1) + c0=cshift(c0,-nint(xdt/dt)) + if(fspread.ne.0.0 .or. delay.ne.0.0) then + ! Apply channel propagation + call watterson(c0,npts,nwave,fsample,delay,fspread) + endif + c=0. + c=sig*c0 !Scale to specified SNR + wave=0. + wave=imag(c) !Signal with SNR and prop degradation + + if(snrdb.lt.90) then + do i=1,iz !Add gaussian noise for specified SNR + xnoise=gran() + wave(i)=wave(i) + xnoise + enddo + endif + + gain=100.0 + if(snrdb.lt.90.0) then + wave(1:iz)=gain*wave(1:iz) + else + datpk=maxval(abs(wave(1:iz))) + fac=32766.9/datpk + wave(1:iz)=fac*wave(1:iz) + endif + + iwave(1:iz)=nint(wave(1:iz)) +! call jtty_spec(iwave,iz) + h=default_header(12000,iz) + write(fname,1102) ifile +1102 format('000000_',i6.6,'.wav') + open(10,file=fname,status='replace',access='stream') + write(10) h,iwave(1:iz) !Save to *.wav file + close(10) + write(*,1110) ifile,xdt,f0,snrdb,fname +1110 format(i4,f7.2,f8.2,f7.1,2x,a17) + enddo + +999 if (allocated(cwave)) deallocate(cwave) + if (allocated(c0)) deallocate(c0) + if (allocated(c)) deallocate(c) + if (allocated(wave)) deallocate(wave) + if (allocated(iwave)) deallocate(iwave) + +end program sjtty + +!include 'jtty_spec.f90' diff --git a/lib/jtty/sjtty_qrm.f90 b/lib/jtty/sjtty_qrm.f90 new file mode 100644 index 00000000..d4038b0b --- /dev/null +++ b/lib/jtty/sjtty_qrm.f90 @@ -0,0 +1,238 @@ +program sjtty_qrm + + ! Simulate received data for JTTY, a mode operationally similar to RTTY + ! but providing much better performance and reliability. + + ! Messages are source-encoded into 34-bit blocks. A 12-bit CRC is + ! added to create a 46 bit payload, which is then FEC-encoded using + ! a tail-biting rate-1/2 convolutional code (K=10) to create 92-bit + ! (46-symbol) codewords. + + ! Modulation is 4FSK at 12000/NSPS = 31.25 baud. Each transmitted frame + ! consists of 13 sync symbols followed by 46 codeword symbols. + + ! This version generates multiple signals spread across nfa to nfb Hz. + ! One signal falls at f0 = 1500 Hz and has the message "599 123" (or, if + ! an 8th command-line argument is given, that text instead -- a longer, + ! multi-frame message there is useful for exercising continuation-frame + ! logic, e.g. the sticky-sync retry, that a single-frame message never + ! reaches). Others are spread in frequency and DT, and contain just a + ! callsign. + + use wavhdr + use jtty_mod + use jtty_fec + + parameter (NMAX=131072) !Max size of .wav file + parameter (MAX_TONES=59*16) !Max number of channel symbols + parameter (MAX_SIGS=20) !Max number of signals + character*12 arg !Command line argument + character*2 arg4 !The 4th command-line argument + character*80 umsg !User-formatted message + character*80 msg_override !Optional 8th-arg override for f0=1500 signal + character*17 fname !Output file name, + character*10 flags !Single-character shorthand flags + character*34 c32(16) + character*6 xcall(25) + complex cwave(0:NMAX-1) !Complex generated waveform (12000 Hz) + complex c0(0:NMAX-1) !With propagation degradation + complex cdat(0:NMAX-1) + real wave (NMAX) !Real generated waveform (12000 Hz) + real xnoise(NMAX) + type(hdr) h !Header for .wav file + integer itone(MAX_TONES) !Array of tone frequencies for this message + integer*2 iwave(NMAX) !Data written to the *.wav file + integer payload(PAYLOAD_BITS) + integer tone_symbols(TOTAL_K) + data flags/'!@#$%^&*()'/ + data idum/-1/ + + ! Some arbitrary callsigns: + data xcall/'AC9QI ','CF7GEM','EA1AAE','GI4FUE','IU8CNE','K2AK ', & + 'K5CIA ','K7CAH ','KA9KQH','KE0N ','KM2J ','KP4SX ', & + 'LV7QFH','N2PPI ','N6GP ','N8HMG ','NV8B ','PA2GP ', & + 'PY7BC ','W0OGH ','W4EIS ','W6RYO ','W8OI ','WA2HIP', & + 'WB2KSP'/ + + nargs=iargc() + if(nargs.ne.7 .and. nargs.ne.8) then + print*,'Usage: sjtty_qrm nsps prop nfa nfb nsigs nfiles snr [message]' + print*,'Example: sjtty_qrm 384 MM 1200 1800 5 10 -5' + print*,'Example: sjtty_qrm 384 MM 1200 1800 5 10 -5 ', & + '"LET''S ASK BRIAN WHAT HE THINKS"' + print*,'NSPS must be 240, 320, 384, or 480' + print*,'ITU propagation models: AW LQ LM LD MQ MM MD HQ HM HD' + print*,'Main signal at f0 = 1500 Hz and specified SNR, message' + print*,'"599 123" unless the optional 8th argument overrides it --' + print*,'quote it if it contains spaces. A message long enough to' + print*,'need more than one frame exercises continuation-frame' + print*,'decoder logic that "599 123" alone never reaches; frames' + print*,'beyond what the fixed-size output buffer can hold at this' + print*,'signal''s randomly-drawn DT are silently dropped (matches a' + print*,'transmission truncated by a WAV-file boundary), with a' + print*,'warning printed when that happens.' + print*,'Off-freq signals at random freqs in range nfa to nfb Hz.' + print*,'Off-freq SNRs randomized by +/- 5 dB around specified value' + print*,'DT values random in range 0.1 to 1.0 s.' + go to 999 + endif + + call getarg(1,arg) + read(arg,*) nsps + call getarg(2,arg) + arg4=arg(1:2) + if(arg(1:2).eq.'LQ') then !ITU params for Low Latitude Quiet + fspread=0.5 + delay=0.5 + else if(arg(1:2).eq.'LM') then !Low Latitude Moderate + fspread=1.5 + delay=2.0 + else if(arg(1:2).eq.'LD') then !Low Latitude Disturbed + fspread=10.0 + delay=6.0 + else if(arg(1:2).eq.'MQ') then !Mid Latitude ... etc. + fspread=0.1 + delay=0.5 + else if(arg(1:2).eq.'MM') then + fspread=0.5 + delay=1.0 + else if(arg(1:2).eq.'MD') then + fspread=1.0 + delay=2.0 + else if(arg(1:2).eq.'HQ') then + fspread=0.5 + delay=1.0 + else if(arg(1:2).eq.'HM') then + fspread=10.0 + delay=3.0 + else if(arg(1:2).eq.'HD') then + fspread=30.0 + delay=7.0 + else if(arg(1:2).eq.'AW') then + fspread=0.0 + delay=0.0 + endif + call getarg(3,arg) + read(arg,*) nfa + call getarg(4,arg) + read(arg,*) nfb + call getarg(5,arg) + read(arg,*) nsigs + call getarg(6,arg) + read(arg,*) nfiles + call getarg(7,arg) + read(arg,*) snrdb + if(nfa.lt.0 .or. nfb.lt.0) then + print*,'Frequency range endpoints must be nonnegative.' + stop 1 + endif + msg_override=' ' + if(nargs.eq.8) call getarg(8,msg_override) + + fsample=12000.0 + dt=1.0/fsample + twopi=8.0*atan(1.0) + bandwidth_ratio=2500.0/(fsample/2.0) + if(snrdb.gt.90.0) sig=1.0 + bt=2.0 !Default bt=2 (smaller ==> more smoothing) + baud=fsample/nsps !Symbol rate + bw=4.0*baud !Signal bandwidth + hmod=1.0 !Modulation index + + npts=131072 + do ifile=1,nfiles + write(fname,1002) ifile !Output filename +1002 format('000000_',i6.6,'.wav') + open(10,file=fname,access='stream',status='replace') + write(*,1004) ifile,fname +1004 format(i3,2x,a17) + xnoise=0. + if(snrdb.lt.90) then + do i=1,NMAX + xnoise(i)=gran() !Generate gaussian noise, rms=1.0 + enddo + endif + cdat=0. + i0=25.0*ran1(idum) + + do isig=1,nsigs + f0=nfa + (nfb-nfa)*ran1(idum) + xdt=0.1 + 3.9*ran1(idum) + snr=snrdb + 10.0*(ran1(idum)-0.5) + i0=i0+1 + if(i0.gt.25) i0=1 + umsg=xcall(i0) + if(isig.eq.1) then + f0=1500.0 + snr=snrdb + umsg='599 123' + if(len_trim(msg_override).gt.0) umsg=msg_override + endif + sig=sqrt(2*bandwidth_ratio) * 10.0**(0.05*snr) + write(*,1006) isig,f0,xdt,snr,sig,trim(umsg) +1006 format(i4,f8.1,f8.3,f7.1,f10.3,2x,a) + + i1=nint(xdt/dt) + call pack_jtty(umsg,c32,nframes) + ! itone/cwave/c0 are all fixed at NMAX -- gen_jttywave trusts its + ! caller's nwave completely, with no bounds checking of its own, + ! so a long enough message combined with this signal's own + ! (randomly drawn) start offset i1 could otherwise write past the + ! end of those arrays. Clamp to however many frames actually fit + ! before building itone, rather than risk that: this can only + ! happen with a message overriding the default "599 123" (that + ! one frame always fits), so it's silent for existing callers. + nframes_fit=max(0,(NMAX-i1)/(nsps*59)) + if(nframes.gt.nframes_fit) then + write(*,1007) nframes,nframes_fit +1007 format(' WARNING: message needs ',i2,' frames but only ', & + i2,' fit in the output buffer at this DT -- truncating') + nframes=nframes_fit + endif + if(nframes.lt.1) then + print*,' WARNING: no room for this signal at this DT -- skipping' + cycle + endif + nsym=0 + do i=1,nframes + read(c32(i),'(34i1)') payload + call tbcc_encode(payload,tone_symbols,JTTY_TBCC_PROFILE_1167_1545_80F) + ib=(i-1)*59+1 ! 59 tones per frame + itone(ib:ib+12)=is13 + itone(ib+13:ib+58)=tone_symbols + nsym=nsym+59 + enddo + nwave=nsps*nsym + icmplx=1 + call gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave) + c0=0. + c0(i1:nwave+i1-1)=cwave(0:nwave-1)! + if(fspread.ne.0.0 .or. delay.ne.0.0) then + ! Apply channel propagation + call watterson(c0,npts,nwave,fsample,delay,fspread) + endif + cdat=cdat + sig*c0 + enddo ! isig + + c0=cdat + wave=0. + wave=aimag(c0) !Signal with SNR and prop degradation + iz=10*12000 + if(snrdb.lt.90) wave = wave + xnoise + + gain=100.0 + if(snrdb.lt.90.0) then + wave(1:iz)=gain*wave(1:iz) + else + datpk=maxval(abs(wave(1:iz))) + fac=32766.9/datpk + wave(1:iz)=fac*wave(1:iz) + endif + + iwave(1:iz)=nint(wave(1:iz)) + h=default_header(12000,iz) + write(10) h,iwave(1:iz) !Save to *.wav file + close(10) + enddo + +999 end program sjtty_qrm diff --git a/lib/jtty/subtract_jtty.f90 b/lib/jtty/subtract_jtty.f90 new file mode 100644 index 00000000..eeb062a0 --- /dev/null +++ b/lib/jtty/subtract_jtty.f90 @@ -0,0 +1,99 @@ +subroutine subtract_jtty(c0, n, nvalid, tone_symbols, nsym_total, nss, f1, xdt) + +! Subtract a decoded JTTY signal from the complex analytic buffer c0 (at +! 6000 Sa/s -- the domain jtty_mdecode.f90 already works in, produced from +! the raw audio by ana64a), so a second, weaker signal at a different +! time/frequency can be recovered in a follow-up decode pass over the +! residual. Modeled on lib/ft8/subtractft8.f90: build a unit-amplitude +! reference waveform for the already re-encoded (error-corrected) tone +! sequence, estimate its actual complex (amplitude+phase) channel gain via +! a matched-filter/low-pass correlation against c0, then subtract. +! +! Measured signal : c0(t) = a(t) * cref(t) + noise +! Reference signal : cref(t) = exp( j*(2*pi*f1*t+phi(t)) ), unit amplitude +! Complex gain : cfilt(t) = LPF[ c0(t) * CONJG(cref(t)) ] +! Subtract : c0(t) = c0(t) - cref(t) * cfilt(t) +! +! Unlike subtractft8 (a real-valued passband buffer, hence its factor-of-2 +! real-part subtraction to reconstruct a real signal from an analytic +! estimate), c0 here is already complex analytic, so the full complex +! estimate is subtracted directly with no real-part/factor-of-2 step. +! +! Input: complex c0(0:n-1) In/out: buffer to subtract from +! integer n Size of c0 (must be a power of 2) +! integer nvalid Number of valid samples in c0 (<=n) +! integer tone_symbols(nsym_total) Full frame: sync + info tones +! integer nsym_total Total symbols/frame (sync+info) +! integer nss Samples per symbol at 6000 Sa/s +! real f1 Signal's estimated audio frequency, Hz +! real xdt Signal's estimated DT (start time), s + + implicit none + integer, intent(in) :: n, nvalid, nsym_total, nss + complex, intent(inout) :: c0(0:n-1) + integer, intent(in) :: tone_symbols(nsym_total) + real, intent(in) :: f1, xdt + + real, parameter :: FSAMPLE6 = 6000.0 + integer, save :: nframe_save=-1, nfft_save=-1 + complex, allocatable, save :: cref(:), camp(:), cfilt(:), cw(:) + real, allocatable, save :: window(:) + integer :: nframe, nfft, nfilt, i, j, nstart + real :: pi, fac, sumw, xjunk(1) + complex :: z + + nframe=nsym_total*nss + nfft=n + ! ~2 symbol periods, matching subtractft8's NFILT (4000 samples @ 12000 + ! Sa/s = 333 ms) being ~2 FT8 symbol periods (160 ms each) -- smooths the + ! channel-gain estimate enough to track slow fading without blurring out + ! genuine amplitude structure within the frame. + nfilt=2*nss + + if(nframe.ne.nframe_save .or. nfft.ne.nfft_save) then + if(allocated(cref)) deallocate(cref,camp,cfilt,cw,window) + allocate(cref(nframe), camp(nfft), cfilt(nfft), cw(nfft)) + allocate(window(-nfilt/2:nfilt/2)) + pi=4.0*atan(1.0) + fac=1.0/float(nfft) + sumw=0.0 + do j=-nfilt/2,nfilt/2 + window(j)=cos(pi*j/nfilt)**2 + sumw=sumw+window(j) + enddo + cw=0. + cw(1:nfilt+1)=window/sumw + cw=cshift(cw,nfilt/2+1) + call four2a(cw,nfft,1,-1,1) + cw=cw*fac + nframe_save=nframe + nfft_save=nfft + endif + +! Generate a unit-amplitude complex reference waveform for the full frame +! (sync + info tones), at this signal's own estimated frequency. + call gen_jttywave(tone_symbols, nsym_total, nss, 2.0, FSAMPLE6, f1, & + cref, xjunk, 1, nframe) + + nstart=nint(xdt*FSAMPLE6) ! 0-based c0 index of the frame's first sample + camp=(0.,0.) + do i=1,nframe + j=nstart+i-1 + if(j.ge.0 .and. j.lt.nvalid) camp(i)=c0(j)*conjg(cref(i)) + enddo + + cfilt=camp + call four2a(cfilt,nfft,1,-1,1) ! forward FFT + cfilt=cfilt*cw ! apply the low-pass filter + call four2a(cfilt,nfft,1,1,1) ! inverse FFT -> smoothed complex gain + + do i=1,nframe + j=nstart+i-1 + if(j.ge.0 .and. j.lt.nvalid) then + z=cfilt(i)*cref(i) + c0(j)=c0(j)-z !Subtract the reconstructed signal + endif + enddo + + return +end subroutine subtract_jtty diff --git a/lib/jtty/tbcc.f90 b/lib/jtty/tbcc.f90 new file mode 100644 index 00000000..c3a89c0c --- /dev/null +++ b/lib/jtty/tbcc.f90 @@ -0,0 +1,422 @@ +module tbcc + ! Tail-biting rate-1/2 convolutional code: encode, WAVA/list decode, + ! CRC-12 append/check, and generator-polynomial selection. Used by JTTY + ! mode (lib/jtty/jtty_fec_mod.f90 and callers) and by the standalone + ! research tools under lib/jtty/wava/. + use, intrinsic :: iso_fortran_env, only: real32, int32, int16 + use jtty_tbcc_code_profiles, only: jtty_tbcc_code_profile, & + jtty_tbcc_code_profile_is_supported, & + PROFILE_PAYLOAD_BITS => JTTY_TBCC_PAYLOAD_BITS, & + PROFILE_OUTER_CHECK_BITS => JTTY_TBCC_OUTER_CHECK_BITS, & + PROFILE_INFORMATION_BITS => JTTY_TBCC_INFORMATION_BITS + !$ use omp_lib + implicit none + + ! Fixed frame parameters, shared with every caller. + integer(int32), parameter :: PAYLOAD_BITS = PROFILE_PAYLOAD_BITS + integer(int32), parameter :: CRC_BITS = PROFILE_OUTER_CHECK_BITS + integer(int32), parameter :: TOTAL_K = PROFILE_INFORMATION_BITS + integer(int32), parameter :: TBCC_OUTER_POLYNOMIAL_80F = int(Z"80F", int32) + + ! Standalone simulation tools retain runtime nu selection through tbcc_init. + ! JTTY production callers pass a complete selected profile instead. + integer(int32) :: memory_nu, num_states, g0_poly, g1_poly, reg_mask + + integer(int32), allocatable, protected :: incoming_tones(:,:) + + type candidate_t + real(real32) :: metric + integer(int32) :: bits(TOTAL_K) + end type candidate_t + + ! Per-thread RNG state (xorshift32), used only by the channel-simulation + ! helpers below (box_muller/generate_random_bits/seed_random_generator). + ! tbcc_encode/tbcc_wava_fsk_decode/encode_crc12 never touch it -- a + ! production caller that never runs the simulator helpers pays nothing + ! for this. The RANDOM_NUMBER intrinsic keeps a single shared generator + ! state and is not safe to call concurrently from multiple OpenMP + ! threads, so each thread gets its own independent stream instead. + ! Threadprivate module variables retain that property for every program + ! unit that USEs this module. + integer(int32), save :: rng_state = 0 + !$omp threadprivate(rng_state) + +contains + + subroutine tbcc_init(nu) + ! Sets memory_nu, num_states, g0_poly, g1_poly, and reg_mask for the + ! chosen constraint length K = nu+1. Call once, before any + ! encode/decode. + integer(int32), intent(in) :: nu + memory_nu = nu + num_states = 2**nu + call select_generator_polynomials(nu, g0_poly, g1_poly) + reg_mask = 2**(nu + 1) - 1 + if (allocated(incoming_tones)) deallocate(incoming_tones) + allocate(incoming_tones(0:1, 0:num_states-1)) + call build_incoming_tones(memory_nu, num_states, g0_poly, g1_poly, incoming_tones) + end subroutine tbcc_init + + subroutine tbcc_encode(payload, tone_symbols, code_profile, encoded_bits) + ! Encodes a PAYLOAD_BITS-bit payload into a TOTAL_K-symbol 4-FSK + ! tone sequence: CRC-12 append, then tail-biting rate-1/2 + ! convolutional encode with a Gray-coded 2-bit-per-symbol tone + ! mapping (00/01/11/10 -> 0/1/2/3). A caller that omits code_profile + ! must first initialize the standalone simulation code with tbcc_init(). + integer(int32), intent(in) :: payload(PAYLOAD_BITS) + integer(int32), intent(out) :: tone_symbols(TOTAL_K) + type(jtty_tbcc_code_profile), intent(in), optional :: code_profile + integer(int32), intent(out), optional :: encoded_bits(2, TOTAL_K) + integer(int32) :: info_bits(2, TOTAL_K) + integer(int32) :: state, t, bit, g0_out, out_b0, out_b1 + integer(int32) :: selected_nu, selected_state_count, selected_g0, selected_g1 + integer(int32) :: selected_register_mask, outer_polynomial, outer_check_bits + integer(int32) :: outer_top_bit_mask, outer_register_mask + + call resolve_code_definition(code_profile, selected_nu, selected_state_count, & + selected_g0, selected_g1, selected_register_mask, outer_polynomial, & + outer_check_bits, outer_top_bit_mask, outer_register_mask) + call encode_crc12(payload, info_bits, code_profile) + + ! Tail-biting initialization: preload the shift register with the + ! message's own last nu bits, so the encoder's starting + ! state equals what it would be after wrapping around the circular + ! frame. + state = 0 + do t = 0, selected_nu - 1 + bit = info_bits(1, TOTAL_K - (selected_nu - 1) + t) + state = iand(ior(ishft(state, 1), bit), selected_state_count-1) + end do + + do t = 1, TOTAL_K + bit = info_bits(1, t) + g0_out = iand(ior(ishft(state, 1), bit), selected_register_mask) + out_b0 = parity_bit(iand(g0_out, selected_g0)) + out_b1 = parity_bit(iand(g0_out, selected_g1)) + state = iand(ior(ishft(state, 1), bit), selected_state_count-1) + if (present(encoded_bits)) encoded_bits(:, t) = [out_b0, out_b1] + + if (out_b0 == 0 .and. out_b1 == 0) tone_symbols(t) = 0 + if (out_b0 == 0 .and. out_b1 == 1) tone_symbols(t) = 1 + if (out_b0 == 1 .and. out_b1 == 1) tone_symbols(t) = 2 + if (out_b0 == 1 .and. out_b1 == 0) tone_symbols(t) = 3 + end do + end subroutine tbcc_encode + + subroutine tbcc_wava_fsk_decode(tone_energies, list_size, max_wava_iters, & + final_payload, success, reserved_zero_bit, code_profile) + real(real32), intent(in) :: tone_energies(0:3, TOTAL_K) + integer(int32), intent(in) :: list_size + integer(int32), intent(in) :: max_wava_iters + integer(int32), intent(out) :: final_payload(PAYLOAD_BITS) + logical, intent(out) :: success + ! Failed decodes return an all-zero payload; success determines validity. + ! Optional 1-based position (within PAYLOAD_BITS) of a payload bit + ! that the caller guarantees is always transmitted as 0. When + ! present, a list candidate is only accepted if it also satisfies + ! this in addition to CRC==0, rather than accepting the first + ! CRC-clean candidate regardless -- roughly halves the undetected- + ! error rate, since a wrong candidate must now also hit this bit by + ! chance. Absent (the default) reproduces the original CRC-only + ! behavior exactly. + integer(int32), intent(in), optional :: reserved_zero_bit + type(jtty_tbcc_code_profile), intent(in), optional :: code_profile + + real(real32), allocatable :: prev_m(:), curr_m(:) + integer(int16), allocatable :: traceback_table(:,:) + type(candidate_t), allocatable :: sorted_list(:) + integer(int32) :: iter, t, s, bit_in, prev_s, curr_s, l, crc_reg, i + integer(int32), allocatable :: profile_tones(:,:) + integer(int32) :: selected_nu, selected_state_count, selected_g0, selected_g1 + integer(int32) :: selected_register_mask, outer_polynomial, outer_check_bits + integer(int32) :: outer_top_bit_mask, outer_register_mask + real(real32) :: m0, m1 + integer(int32) :: tmp_bits(TOTAL_K) + + final_payload = 0_int32 + success = .false. + call resolve_code_definition(code_profile, selected_nu, selected_state_count, & + selected_g0, selected_g1, selected_register_mask, outer_polynomial, & + outer_check_bits, outer_top_bit_mask, outer_register_mask) + ! Zero iterations means the WAVA loop below never runs, leaving + ! curr_m/traceback_table unread-by-design -- but the traceback and + ! list-selection code after the loop unconditionally reads them + ! regardless. Bail out before allocating rather than let that read + ! uninitialized memory (production always passes max_wava_iters=2; + ! only reachable via the CLI simulator's --iters option, which + ! accepts any caller-supplied value; found by David Christle, PR + ! #337, who confirmed it otherwise returns success=.true. with an + ! all-zero payload). + if (max_wava_iters < 1) return + allocate(prev_m(0:selected_state_count-1), curr_m(0:selected_state_count-1)) + allocate(traceback_table(0:selected_state_count-1, TOTAL_K), sorted_list(list_size)) + + allocate(profile_tones(0:1,0:selected_state_count-1)) + if (present(code_profile)) then + call build_incoming_tones(selected_nu, selected_state_count, & + selected_g0, selected_g1, profile_tones) + else + profile_tones = incoming_tones + end if + prev_m = 0.0_real32 + + do l = 1, list_size + sorted_list(l)%metric = -1.0e30_real32 + end do + + ! Forward Trellis WAVA loop + do iter = 1, max_wava_iters + do t = 1, TOTAL_K + curr_m = -1.0e30_real32 + do s = 0, selected_state_count-1 + ! For a destination state 's' at time 't' under a left-shift model, + ! the two possible predecessor states at time 't-1' are determined + ! by shifting 's' right and checking both options for the bit that + ! left the window. + prev_s = iand(ishft(s, -1), selected_state_count-1) + + m0 = prev_m(prev_s) + tone_energies(profile_tones(0, s), t) + prev_s = ior(prev_s, ishft(1, selected_nu-1)) + m1 = prev_m(prev_s) + tone_energies(profile_tones(1, s), t) + + ! Select and record maximum likelihood trajectory decision + if (m0 > m1) then + curr_m(s) = m0 + ! Picked path from state with dropped bit 0 + traceback_table(s, t) = 0_int16 + else + curr_m(s) = m1 + ! Picked path from state with dropped bit 1 + traceback_table(s, t) = 1_int16 + end if + end do + prev_m = curr_m + end do + end do + + ! REVISED TRACEBACK ALIGNMENT + do s = 0, selected_state_count-1 + curr_s = s + do t = TOTAL_K, 1, -1 + ! The input bit that caused the transition into 'curr_s' is its LSB (bit 0) + bit_in = iand(curr_s, 1) + tmp_bits(t) = bit_in + + ! Recover the parent state index using the recorded history bit flag + prev_s = iand(ishft(curr_s, -1), selected_state_count-1) + if (traceback_table(curr_s, t) == 1_int16) then + prev_s = ior(prev_s, ishft(1, selected_nu-1)) + end if + curr_s = prev_s + end do + + ! Check if circular tail-biting constraint condition holds valid + if (curr_s == s) then + do l = 1, list_size + if (curr_m(s) > sorted_list(l)%metric) then + do i = list_size, l+1, -1 + sorted_list(i) = sorted_list(i-1) + end do + sorted_list(l)%metric = curr_m(s) + sorted_list(l)%bits = tmp_bits + exit + end if + end do + end if + end do + + ! Serial CRC (and, if requested, reserved-bit) filtering pass + do l = 1, list_size + if (sorted_list(l)%metric <= -1.0e29_real32) cycle + if (present(reserved_zero_bit)) then + if (sorted_list(l)%bits(reserved_zero_bit) /= 0) cycle + end if + crc_reg = 0 + do i = 1, TOTAL_K + crc_reg = ieor(crc_reg, ishft(sorted_list(l)%bits(i), & + outer_check_bits - 1)) + if (iand(crc_reg, outer_top_bit_mask) /= 0) then + crc_reg = ieor(ishft(crc_reg, 1), outer_polynomial) + else + crc_reg = ishft(crc_reg, 1) + end if + crc_reg = iand(crc_reg, outer_register_mask) + end do + + if (crc_reg == 0) then + final_payload = sorted_list(l)%bits(1:PAYLOAD_BITS) + success = .true. + exit + end if + end do + + deallocate(prev_m, curr_m, traceback_table, sorted_list) + end subroutine tbcc_wava_fsk_decode + + subroutine encode_crc12(payload, out_buf, code_profile) + integer(int32), intent(in) :: payload(PAYLOAD_BITS) + integer(int32), intent(out) :: out_buf(2, TOTAL_K) + type(jtty_tbcc_code_profile), intent(in), optional :: code_profile + integer(int32) :: crc_reg, i + integer(int32) :: selected_nu, selected_state_count, selected_g0, selected_g1 + integer(int32) :: selected_register_mask, outer_polynomial, outer_check_bits + integer(int32) :: outer_top_bit_mask, outer_register_mask + + call resolve_code_definition(code_profile, selected_nu, selected_state_count, & + selected_g0, selected_g1, selected_register_mask, outer_polynomial, & + outer_check_bits, outer_top_bit_mask, outer_register_mask) + out_buf(1, 1:PAYLOAD_BITS) = payload + crc_reg = 0 + do i = 1, PAYLOAD_BITS + crc_reg = ieor(crc_reg, ishft(payload(i), outer_check_bits - 1)) + if (iand(crc_reg, outer_top_bit_mask) /= 0) then + crc_reg = ieor(ishft(crc_reg, 1), outer_polynomial) + else + crc_reg = ishft(crc_reg, 1) + end if + crc_reg = iand(crc_reg, outer_register_mask) + end do + do i = 1, outer_check_bits + out_buf(1, PAYLOAD_BITS + i) = & + iand(ishft(crc_reg, -(outer_check_bits - i)), 1) + end do + end subroutine encode_crc12 + + subroutine resolve_code_definition(code_profile, selected_nu, selected_state_count, & + selected_g0, selected_g1, selected_register_mask, outer_polynomial, & + outer_check_bits, outer_top_bit_mask, outer_register_mask) + type(jtty_tbcc_code_profile), intent(in), optional :: code_profile + integer(int32), intent(out) :: selected_nu, selected_state_count + integer(int32), intent(out) :: selected_g0, selected_g1, selected_register_mask + integer(int32), intent(out) :: outer_polynomial, outer_check_bits + integer(int32), intent(out) :: outer_top_bit_mask, outer_register_mask + + if (present(code_profile)) then + if (.not.jtty_tbcc_code_profile_is_supported(code_profile)) & + error stop 'unsupported JTTY TBCC code profile' + selected_nu = code_profile%memory_nu + selected_state_count = code_profile%state_count + selected_g0 = code_profile%generator_0 + selected_g1 = code_profile%generator_1 + selected_register_mask = code_profile%register_mask + outer_polynomial = code_profile%outer_polynomial + outer_check_bits = code_profile%outer_check_bits + outer_top_bit_mask = code_profile%outer_top_bit_mask + outer_register_mask = code_profile%outer_register_mask + else + selected_nu = memory_nu + selected_state_count = num_states + selected_g0 = g0_poly + selected_g1 = g1_poly + selected_register_mask = reg_mask + outer_polynomial = TBCC_OUTER_POLYNOMIAL_80F + outer_check_bits = CRC_BITS + outer_top_bit_mask = shiftl(1_int32, CRC_BITS - 1_int32) + outer_register_mask = shiftl(1_int32, CRC_BITS) - 1_int32 + end if + end subroutine resolve_code_definition + + subroutine build_incoming_tones(nu, state_count, g0, g1, tones) + integer(int32), intent(in) :: nu, state_count, g0, g1 + integer(int32), intent(out) :: tones(0:1,0:state_count-1) + integer(int32) :: state, dropped_bit, register_value, b0, b1 + integer(int32), parameter :: gray_tones(0:3) = [0, 1, 3, 2] + + do state = 0, state_count-1 + do dropped_bit = 0, 1 + register_value = ior(state, ishft(dropped_bit, nu)) + b0 = parity_bit(iand(register_value, g0)) + b1 = parity_bit(iand(register_value, g1)) + tones(dropped_bit, state) = gray_tones(2*b0+b1) + end do + end do + end subroutine build_incoming_tones + + subroutine box_muller(rand_normal) + real(real32), intent(out) :: rand_normal + real(real32) :: u1, u2 + u1 = thread_uniform(); u2 = thread_uniform() + if (u1 < 1.0e-30_real32) u1 = 1.0e-30_real32 + rand_normal = sqrt(-2.0_real32 * log(u1)) * cos(6.28318530718_real32 * u2) + end subroutine box_muller + + subroutine generate_random_bits(vec, n) + integer(int32), intent(out) :: vec(n) + integer(int32) :: n, i + do i = 1, n + vec(i) = merge(1, 0, thread_uniform() >= 0.5_real32) + end do + end subroutine generate_random_bits + + function thread_uniform() result(u) + ! Fast per-thread xorshift32 generator returning a uniform value on + ! [0,1]. rng_state is !$omp threadprivate, so this advances each + ! thread's own independent stream with no shared mutable state and + ! no locking -- the replacement for RANDOM_NUMBER, which is not + ! safe to call from a parallel region. + real(real32) :: u + rng_state = ieor(rng_state, ishft(rng_state, 13)) + rng_state = ieor(rng_state, ishft(rng_state, -17)) + rng_state = ieor(rng_state, ishft(rng_state, 5)) + u = real(iand(rng_state, huge(rng_state)), real32) / real(huge(rng_state), real32) + end function thread_uniform + + subroutine select_generator_polynomials(nu, g0, g1) + ! Optimal (maximum free distance, noncatastrophic) rate-1/2 + ! generator polynomials, indexed by memory order nu (constraint + ! length K = nu+1). K=12 (nu=11) keeps this file's original pair + ! (octal 7173,5261), unchanged, so results already gathered at + ! that setting stay reproducible. K=10, 11, 13 are the standard + ! maximum-dfree pairs from the Larsen/Odenwalder rate-1/2 tables + ! (as tabulated in e.g. Proakis "Digital Communications" and Lin & + ! Costello "Error Control Coding"): + ! K=10 (nu= 9): octal 1167,1545 dfree=12 + ! K=11 (nu=10): octal 2335,3661 dfree=14 + ! K=12 (nu=11): octal 7173,5261 (this file's existing pair) + ! K=13 (nu=12): octal 10533,17661 dfree=16 + integer(int32), intent(in) :: nu + integer(int32), intent(out) :: g0, g1 + select case (nu) + case (9) ! K = 10, dfree = 12 + g0 = int(Z"277", int32); g1 = int(Z"365", int32) + case (10) ! K = 11, dfree = 14 + g0 = int(Z"4DD", int32); g1 = int(Z"7B1", int32) + case (11) ! K = 12 -- this file's original constants + g0 = int(Z"E7B", int32); g1 = int(Z"AB1", int32) + case (12) ! K = 13, dfree = 16 + g0 = int(Z"115B", int32); g1 = int(Z"1FB1", int32) + case default + print *, "No optimal generator polynomial pair defined for memory_nu =", nu + print *, "Supported values: 9, 10, 11, 12 (K = 10, 11, 12, 13)" + stop 1 + end select + end subroutine select_generator_polynomials + + pure integer(int32) function parity_bit(val) + integer(int32), intent(in) :: val + integer(int32) :: temp, p + temp = val; p = 0 + do while (temp > 0) + if (iand(temp, 1) /= 0) p = ieor(p, 1) + temp = ishft(temp, -1) + end do + parity_bit = p + end function parity_bit + + subroutine seed_random_generator() + ! Give every OpenMP thread its own distinct, deterministic, nonzero + ! xorshift32 seed -- rng_state is threadprivate, so this assignment + ! runs once per thread. Reproducible for a fixed thread count; + ! changing OMP_NUM_THREADS changes how frames are partitioned across + ! streams, so per-frame outcomes differ (though aggregate statistics + ! over num_frames should not, within Monte Carlo noise). + ! In a non-OpenMP build, !$ lines and !$omp directives are comments, + ! so use a deterministic single-thread seed without requiring libgomp. + rng_state = 9999_int32 + !$omp parallel default(shared) + !$ rng_state = 9999_int32 + 104729_int32 * int(omp_get_thread_num(), int32) + if (rng_state == 0_int32) rng_state = 1_int32 + !$omp end parallel + end subroutine seed_random_generator + +end module tbcc diff --git a/lib/jtty/transmit.f90 b/lib/jtty/transmit.f90 new file mode 100644 index 00000000..98136ba0 --- /dev/null +++ b/lib/jtty/transmit.f90 @@ -0,0 +1,55 @@ +subroutine transmit(nfunc) + + use jttycom + parameter (MAX_TONES=85*7) !Max number of channel symbols + integer itone(MAX_TONES) !Channel symbols (tone frequencies) + character*17 cdatetime + real wave(NMAX) + complex cwave(NMAX) + + if(ntransmitting.eq.1) return !Ignore if we're already transmitting + +! if(nfunc.eq.1) txmsg='CQ '//trim(mycall)//' '//mygrid +! if(nfunc.eq.2) txmsg=trim(hiscall)//' '//trim(mycall)// & +! ' 599 '//trim(exch) +! if(nfunc.eq.3) txmsg=trim(hiscall)//' '//trim(mycall)// & +! ' R 599 '//trim(exch) +! if(nfunc.eq.4) txmsg=trim(hiscall)//' '//trim(mycall)//' RR73' +! if(nfunc.eq.5) txmsg='TNX 73 GL' + + if(nfunc.eq.1) txmsg='CQ '//trim(mycall)//' CQ' + if(nfunc.eq.2) txmsg=mycall + if(nfunc.eq.3) txmsg=trim(hiscall)//' 599 123' + if(nfunc.eq.4) txmsg='599 456' + if(nfunc.eq.5) txmsg=trim(hiscall)//' TU '//trim(mycall)//' CQ' + + call genjtty(txmsg,itone,nsym) + + nsps=384 !Samples per symbol at 12000 Hz + nwave=nsps*nsym !Length of i*2 data written to *.wav file + txt=nwave/12000.0 + + icmplx=0 + bt=2.0 + fsample=12000.0 + f0=ftx + call gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave) + + iwave(1:nwave)=1000.0*wave(1:nwave) + iwave(nwave:)=0 + call set_tx_length(nwave) + ntxok=1 + n=len(trim(txmsg)) + + write(*,1010) trim(txmsg) +1010 format('Tx: ',a) + + write(12,1020) cdatetime(),0,0.0,nint(ftx),trim(txmsg) +1020 format(a17,i4,f6.2,i5,' Tx ',a) + if(nfunc.ge.1 .and. nfunc.le.4) ntxed=nfunc + if(nfunc.ge.1 .and. nfunc.le.5) ltx(nfunc)=.true. + if(nfunc.eq.2 .or. nfunc.eq.3) QSO_in_progress=.true. + txmsg="" + + return +end subroutine transmit diff --git a/lib/jtty/update.f90 b/lib/jtty/update.f90 new file mode 100644 index 00000000..a95b0519 --- /dev/null +++ b/lib/jtty/update.f90 @@ -0,0 +1,144 @@ +subroutine update(ic1,ic2) + + ! When the audio streams are active, this routine gets called + ! approximately every 100 ms -- determined by this statement + ! near the end of C function jttyaudio_(): + ! Pa_Sleep(100); + + ! It functions somewhat like the GUIupdate() loop in WSJT-X, calling + ! Rx or Tx routines as needed. + + use jttycom + integer*2 id(30000) + logical level +! character*50 line + character*80 umsg +! character cdatetime*17 + logical synced,eom + data iwrite00/9999999/ + data level/.false./,idone/0/ + data synced/.false./,eom/.false./ + data umsg/' '/,m/0/,nt0/-1/ + save level,iwrite00,iwrite0,synced,m,nt0,idone + + if(ndebug.gt.0 .and. ntransmitting.eq.0 .and. & + (abs(iwrite-iwrite00).ge.12000 .or. iwrite.lt.iwrite00)) then + write(*,1000) iwrite,ntxok,ntransmitting,ndebug,ic1,ic2 +1000 format('Receiving iwrite:',i8,5i5) + iwrite00=iwrite + endif + +! Some keyboard Scan Codes: ic1=0, ic2 as follows +! 13 27 59 60 61 62 63 64 65 66 67 68 +! = ESC F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 + + if(ic1.ne.0 .or. ic2.ne.0) then + if(ic1.eq.27 .and. ic2.eq.0) ngo=0 !ESC ==> terminate program + if(nTxOK.eq.0 .and. ntransmitting.eq.0) then + nfunc=0 + if(ic1.eq.0 .and. ic2.eq.59) nfunc=1 !F1 has Scan Code = 59 + if(ic1.eq.0 .and. ic2.eq.60) nfunc=2 !F2 + if(ic1.eq.0 .and. ic2.eq.61) nfunc=3 !F3 + if(ic1.eq.0 .and. ic2.eq.62) nfunc=4 !F4 + if(ic1.eq.0 .and. ic2.eq.63) nfunc=5 !F5 + if(ic1.eq.0 .and. ic2.eq.64) hiscall=txmsg(1:6) !F6 + if(nfunc.eq.1 .or. (nfunc.ge.2 .and. hiscall.ne.' ')) then + call transmit(nfunc) + endif + endif + if(ic1.eq.13 .and. ic2.eq.0) hiscall=hiscall_next !Enter key + if((ic1.eq.97 .or. ic1.eq.65) .and. ic2.eq.0) autoseq=.not.autoseq !a or A + if(ic1.eq.76 .and. ic2.eq.0) level=.not.level !l or L + + if(ic2.eq.0) then + if(ic1.eq.13) then + call putchar(13) ! CR + call putchar(12) ! LF + call transmit(0) + m=0 + elseif(ic1.eq.8) then + txmsg(m:m)=' ' + if(m.ge.1) m=m-1 + call putchar(ic1) + call putchar(32) + call putchar(ic1) + else + m=m+1 + if(ic1.ge.97 .and. ic1.le.122) ic1=ic1-32 + txmsg(m:m)=char(ic1) + call putchar(ic1) + endif + endif + endif + + nready=iwrite-idone + if(nready.lt.0) nready=nready+NMAX + if(nready.lt.59*384) go to 100 + + ! Call the jtty decoder here, using code from rjtty. + ! ### Maybe call rjtty_sub(y1,iwrite,line1) ??? ### + + iz=30240 !### TEMPORARY ### + k=iwrite-12000 + if(k.lt.1) k=k+NMAX + do i=1,12000 + k=k+1 + if(k.gt.NMAX) k=k-NMAX + id(i)=y1(k) + enddo + nutc=0 + nfqso=1500 + nrx=-1 + k0=0 + k1=0 + eom=.false. + f0=1500.0 + ftol=100.0 + smin=0 + xdt=0. + f1=0. +!### WORK NEEDED HERE ### + call jtty_decode(id,iz,f0,ftol,smin,synced,xdt,f1,snr,umsg) +! fname=cdatetime() +! fname(14:17)='.wav' +! open(13,file=fname,status='unknown',access='stream') +! h=default_header(12000,nwave) +! write(13) h,id +! close(13) + if(autoseq .and.nrx.eq.2) QSO_in_progress=.true. + if(autoseq .and. QSO_in_progress .and. nrx.ge.1 .and. nrx.le.4) then + lrx(nrx)=.true. + if(ntxed.eq.1) then + if(nrx.eq.2) then + call transmit(3) + else + call transmit(1) + endif + endif + if(ntxed.eq.2) then + if(nrx.eq.3) then + call transmit(4) + QSO_in_progress=.false. + write(*,1032) +1032 format('QSO complete: S+P side') + else + call transmit(2) + endif + endif + if(ntxed.eq.3) then + if(nrx.eq.4) then + QSO_in_progress=.false. + write(*,1034) +1034 format('QSO complete: CQ side') + else + call transmit(3) + endif + endif + endif + nt0=nt + idone=iwrite + +100 iwrite0=iwrite + + return +end subroutine update diff --git a/lib/jtty/wava/plot_results.py b/lib/jtty/wava/plot_results.py new file mode 100644 index 00000000..0ef97628 --- /dev/null +++ b/lib/jtty/wava/plot_results.py @@ -0,0 +1,57 @@ + +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/rcu_bound_4fsk.f90 b/lib/jtty/wava/rcu_bound_4fsk.f90 new file mode 100644 index 00000000..ae58793f --- /dev/null +++ b/lib/jtty/wava/rcu_bound_4fsk.f90 @@ -0,0 +1,217 @@ +program rcu_bound_4fsk + ! Random Coding Union (RCU) achievability bound (Polyanskiy-Poor-Verdu + ! 2010, eq. 2) for noncoherent 4-FSK over AWGN and Rayleigh-fading + ! channels, matched to the exact channel model and SNR convention used + ! in tbcc_4fsk_simulation.f90. This bounds the frame-error probability + ! of the BEST POSSIBLE code at (n=46 symbols, M=2^k messages) -- a + ! benchmark for how close an actual code+decoder gets to optimal, not a + ! statement about any particular code. + ! + ! Method: for a fixed received sequence r^n, each per-symbol term of the + ! competitor information density i(X_bar_t; r_t) is an exact discrete + ! 4-valued random variable (X_bar_t uniform over the 4 tones), so its + ! mean/variance are closed-form -- no inner Monte Carlo. Summing 46 such + ! terms and invoking the CLT gives the inner tail probability via erfc. + ! Only the outer expectation (over the true (x^n, r^n) pair) needs Monte + ! Carlo. + use, intrinsic :: iso_fortran_env, only: real32, real64, int32 + use omp_lib + implicit none + + integer(int32), save :: rng_state = 0 + !$omp threadprivate(rng_state) + + integer(int32), parameter :: N_SYM = 46 ! channel uses; matches TOTAL_K + + character(len=8) :: channel_type + character(len=16) :: arg + integer(int32) :: nargs, num_trials, kbits, e, s + real(real64) :: Mminus1, rcu + real(real32) :: snr_2500_db, esno_linear + real(real64) :: t_wall_start, t_wall_end + + nargs = iargc() + if (nargs /= 2) then + print *, 'Usage: rcu_bound_4fsk <num_trials> <k_bits>' + print *, ' k_bits: log2(number of equiprobable messages), e.g. 34' + stop + end if + call getarg(1, arg); read(arg,*) num_trials + call getarg(2, arg); read(arg,*) kbits + Mminus1 = 2.0_real64**kbits - 1.0_real64 + + call seed_random_generator() + + print *, "==========================================================================" + print *, "RCU achievability bound: noncoherent 4-FSK, n =", N_SYM, " symbols" + print *, "M = 2^", kbits, "equiprobable messages | OpenMP threads:", omp_get_max_threads() + print *, "==========================================================================" + + open(unit=25, file="rcu_bound_results.csv", status="unknown", action="write") + write(25,'(A)') "channel,snr_db,rcu_bound" + + t_wall_start = omp_get_wtime() + + do e = 1, 2 + channel_type = merge("AWGN ", "RAYLEIGH", e == 1) + print *, "" + print *, "--- Channel: ", trim(channel_type), " ---" + write(*,'(A10,A16)') "SNR_2500", "RCU bound" + do s = -5, -20, -1 + snr_2500_db = real(s, real32) + esno_linear = (10.0_real32**(snr_2500_db/10.0_real32)) * 80.0_real32 + call compute_rcu(channel_type, esno_linear, Mminus1, num_trials, rcu) + write(*,'(F10.1,ES16.5)') snr_2500_db, rcu + write(25,'(A,A,F6.1,A,ES14.6)') trim(channel_type), ",", snr_2500_db, ",", rcu + end do + end do + + close(25) + t_wall_end = omp_get_wtime() + print '(A,F8.2,A)', "Total wall-clock time: ", t_wall_end - t_wall_start, " s" + +contains + + subroutine compute_rcu(channel_type, esno, Mm1, ntrials, rcu_out) + character(len=*), intent(in) :: channel_type + real(real32), intent(in) :: esno + real(real64), intent(in) :: Mm1 + integer(int32), intent(in) :: ntrials + real(real64), intent(out) :: rcu_out + + integer(int32) :: trial, t, x_true, j + real(real32) :: r(0:3), n_i, n_q, hfade + real(real64) :: logL(0:3), S, i_true, mu_t, var_t, term + real(real64) :: T_sum, MU_sum, VAR_sum, tail, bound_val, acc + + acc = 0.0_real64 + + !$omp parallel do default(shared) & + !$omp private(trial, t, x_true, j, r, n_i, n_q, hfade, logL, S, & + !$omp i_true, mu_t, var_t, term, T_sum, MU_sum, VAR_sum, & + !$omp tail, bound_val) & + !$omp reduction(+:acc) schedule(static) + do trial = 1, ntrials + T_sum = 0.0_real64 + MU_sum = 0.0_real64 + VAR_sum = 0.0_real64 + + do t = 1, N_SYM + x_true = int(thread_uniform()*4.0_real32) + if (x_true > 3) x_true = 3 + + if (channel_type == "AWGN") then + hfade = 1.0_real32 + else + call box_muller(n_i); call box_muller(n_q) + hfade = sqrt(0.5_real32*(n_i**2 + n_q**2)) + end if + + do j = 0, 3 + call box_muller(n_i); call box_muller(n_q) + n_i = n_i*sqrt(0.5_real32); n_q = n_q*sqrt(0.5_real32) + if (j == x_true) then + r(j) = (hfade*sqrt(esno) + n_i)**2 + n_q**2 + else + r(j) = n_i**2 + n_q**2 + end if + end do + + ! log-likelihood-ratio log L(r) = log f_sig(r) - log f_noise(r) + do j = 0, 3 + if (channel_type == "AWGN") then + logL(j) = -real(esno,real64) & + + log_bessel_i0(2.0_real64*sqrt(real(esno,real64)*real(r(j),real64))) + else + logL(j) = -log(1.0_real64+real(esno,real64)) & + + real(r(j),real64)*real(esno,real64)/(1.0_real64+real(esno,real64)) + end if + end do + + S = logsumexp4(logL) ! log( sum_j L(r_j) ) + i_true = log(4.0_real64) + logL(x_true) - S + + mu_t = 0.0_real64 + do j = 0, 3 + mu_t = mu_t + (log(4.0_real64) + logL(j) - S) + end do + mu_t = mu_t/4.0_real64 + + var_t = 0.0_real64 + do j = 0, 3 + term = (log(4.0_real64) + logL(j) - S) - mu_t + var_t = var_t + term*term + end do + var_t = var_t/4.0_real64 + + T_sum = T_sum + i_true + MU_sum = MU_sum + mu_t + VAR_sum = VAR_sum + var_t + end do + + ! CLT approximation to Pr[ sum_t i(X_bar_t;r_t) >= T_sum ] + tail = 0.5_real64*erfc( (T_sum-MU_sum) / sqrt(2.0_real64*VAR_sum) ) + bound_val = min(1.0_real64, Mm1*tail) + acc = acc + bound_val + end do + !$omp end parallel do + + rcu_out = acc/real(ntrials, real64) + end subroutine compute_rcu + + pure function logsumexp4(v) result(s) + real(real64), intent(in) :: v(0:3) + real(real64) :: s, m + m = maxval(v) + s = m + log(sum(exp(v-m))) + end function logsumexp4 + + ! log(I0(x)), x>=0, via the standard Abramowitz & Stegun 9.8.1/9.8.2 + ! rational approximations (~1.6e-7 relative accuracy), evaluated in log + ! space for large x to avoid overflowing exp(x). + pure function log_bessel_i0(x) result(logi0) + real(real64), intent(in) :: x + real(real64) :: logi0, ax, y, bessi0 + + ax = abs(x) + if (ax < 3.75_real64) then + y = (x/3.75_real64)**2 + bessi0 = 1.0_real64 + y*(3.5156229_real64 + y*(3.0899424_real64 + & + y*(1.2067492_real64 + y*(0.2659732_real64 + & + y*(0.0360768_real64 + y*0.0045813_real64))))) + logi0 = log(bessi0) + else + y = 3.75_real64/ax + logi0 = ax - 0.5_real64*log(ax) + & + log(0.39894228_real64 + y*(0.01328592_real64 + & + y*(0.00225319_real64 + y*(-0.00157565_real64 + & + y*(0.00916281_real64 + y*(-0.02057706_real64 + & + y*(0.02635537_real64 + y*(-0.01647633_real64 + & + y*0.00392377_real64)))))))) + end if + end function log_bessel_i0 + + subroutine box_muller(rand_normal) + real(real32), intent(out) :: rand_normal + real(real32) :: u1, u2 + u1 = thread_uniform(); u2 = thread_uniform() + if (u1 < 1.0e-30_real32) u1 = 1.0e-30_real32 + rand_normal = sqrt(-2.0_real32*log(u1)) * cos(6.28318530718_real32*u2) + end subroutine box_muller + + function thread_uniform() result(u) + real(real32) :: u + rng_state = ieor(rng_state, ishft(rng_state, 13)) + rng_state = ieor(rng_state, ishft(rng_state, -17)) + rng_state = ieor(rng_state, ishft(rng_state, 5)) + u = real(iand(rng_state, huge(rng_state)), real32) / real(huge(rng_state), real32) + end function thread_uniform + + subroutine seed_random_generator() + !$omp parallel default(shared) + rng_state = 9999_int32 + 104729_int32*int(omp_get_thread_num(), int32) + if (rng_state == 0_int32) rng_state = 1_int32 + !$omp end parallel + end subroutine seed_random_generator + +end program rcu_bound_4fsk diff --git a/lib/jtty/wava/tbcc_4fsk_simulation.f90 b/lib/jtty/wava/tbcc_4fsk_simulation.f90 new file mode 100644 index 00000000..d6512f27 --- /dev/null +++ b/lib/jtty/wava/tbcc_4fsk_simulation.f90 @@ -0,0 +1,167 @@ +program tbcc_4fsk_simulation + + use, intrinsic :: iso_fortran_env, only: real32, int32, real64 + use omp_lib + use tbcc + implicit none + + real(real64) :: t_wall_start, t_wall_end + + character(len=8) :: channel_type + character(len=8) :: arg + real(real32) :: snr_2500_db, esno_linear + + + integer(int32) :: tx_payload(PAYLOAD_BITS), tx_symbols(TOTAL_K) + real(real32) :: rx_tone_energies(0:3, TOTAL_K) + integer(int32) :: rx_decoded(PAYLOAD_BITS) + + integer(int32) :: correct_frames, undetected_errors, total_detected_errors, total_frames + integer(int32) :: num_frames, L_size, wava_iters, isnr1, isnr2 + real(real32) :: p_correct, uer + integer(int32) :: f, e, t, s, i, nargs + real(real32) :: n_i, n_q, h_fade, ch_i, ch_q, xsnr + logical :: decode_success, payload_match + + nargs=iargc() + if(nargs.ne.5) then + print*,'Usage: tbcc_sim nu L iters Nmax SNR' + print*,'Example: tbcc_sim 9 4 2 10000 0' + stop + endif + + call getarg(1,arg) + read(arg,*) memory_nu + call getarg(2,arg) + read(arg,*) L_size ! List size + call getarg(3,arg) + read(arg,*) wava_iters ! Trellis wraps for tail-biting convergence + call getarg(4,arg) + read(arg,*) num_frames + call getarg(5,arg) + read(arg,*) xsnr + + call seed_random_generator() + + print *, "==========================================================================" + print *, "Tail-Biting Convolutional Code (92,46) Noncoherent 4-FSK Simulation Suite" + print *, "Symbol Rate = 31.25 Baud | Reference Bandwidth = 2500 Hz" + print *, "OpenMP threads available: ", omp_get_max_threads() + print *, "Writing data logs directly to simulation_results.csv..." + print *, "==========================================================================" + + ! Open CSV data output buffer file + open(unit=24, file="simulation_results.dat", status="unknown", action="write") + open(unit=25, file="simulation_results.csv", status="unknown", action="write") + write(24, '(A)') "snr,frames,good,uer" + write(25, '(A)') "channel,snr_db,p_correct,uer_pct" + + t_wall_start = omp_get_wtime() + call tbcc_init(memory_nu) + total_frames = 0 + + do e = 1, 2 + channel_type = merge("AWGN ", "RAYLEIGH", e == 1) + print *, "" + print *, "--- Channel Profile: ", trim(channel_type), " ---" + write(24,'(a,a,a)') "--- Channel Profile: ", trim(channel_type), " ---" + + write(*,1000) + write(24,1000) +1000 format(' SNR_2500 Frames Good UER '/39('-')) + + isnr1 = -5 + isnr2 = -20 + do s = isnr1, isnr2, -1 + snr_2500_db = s + if(xsnr.ne.0.0) snr_2500_db = xsnr + esno_linear = (10.0_real32 ** (snr_2500_db / 10.0_real32)) * 80.0_real32 + correct_frames = 0 + undetected_errors = 0 + total_detected_errors = 0 + + ! Each frame (generate -> encode -> channel -> WAVA decode) is + ! completely independent of every other frame, so the frame loop + ! is embarrassingly parallel. Every array/scalar that a single + ! frame writes must be private -- otherwise threads clobber each + ! other's tx_payload/tx_encoded/etc. The three tallies are + ! combined across threads via REDUCTION. + + !$omp parallel do default(shared) & + !$omp private(f, t, i, n_i, n_q, h_fade, ch_i, ch_q, decode_success, payload_match, & + !$omp tx_payload, tx_symbols, rx_tone_energies, rx_decoded) & + !$omp reduction(+:correct_frames, undetected_errors, total_detected_errors) & + !$omp schedule(static) + do f = 1, num_frames + call generate_random_bits(tx_payload, PAYLOAD_BITS) + call tbcc_encode(tx_payload, tx_symbols) + + ! Channel Simulation + do t = 1, TOTAL_K + if (channel_type == "AWGN") then + h_fade = 1.0_real32 + else + call box_muller(n_i) + call box_muller(n_q) + h_fade = sqrt(0.5_real32 * (n_i**2 + n_q**2)) + end if + + do i = 0, 3 + call box_muller(n_i) + call box_muller(n_q) + n_i = n_i * sqrt(0.5_real32) + n_q = n_q * sqrt(0.5_real32) + + if (i == tx_symbols(t)) then + ch_i = (h_fade * sqrt(esno_linear)) + n_i + ch_q = n_q + else + ch_i = n_i + ch_q = n_q + end if + rx_tone_energies(i, t) = ch_i**2 + ch_q**2 + end do + end do + + ! Decoding Execution + call tbcc_wava_fsk_decode(rx_tone_energies, L_size, wava_iters, & + rx_decoded, decode_success) + + if (decode_success) then + payload_match = all(tx_payload == rx_decoded) + if (payload_match) then + correct_frames = correct_frames + 1 + else + undetected_errors = undetected_errors + 1 + end if + else + total_detected_errors = total_detected_errors + 1 + end if + end do + !$omp end parallel do + + p_correct = real(correct_frames, real32) / real(num_frames, real32) + uer = real(undetected_errors, real32) / real(num_frames, real32) + total_frames = total_frames + num_frames + + write(*,1001) snr_2500_db, num_frames, p_correct, uer + write(24,1001) snr_2500_db, num_frames, p_correct, uer +1001 format(f8.1,i10,2f10.6) + + ! Write tracking vectors to the spreadsheet data table (Multiplying UER by + ! 100 for percentage scale) + write(25, '(A,A,F6.1,A,F7.5,A,F7.5)') trim(channel_type), ",", snr_2500_db, & + ",", p_correct, ",", uer * 100.0_real32 + if(xsnr.ne.0.0) exit + end do !Loop over SNRs + end do !Loop over channel types (AWGN, then Rayleigh) + + close(24) + close(25) + + t_wall_end = omp_get_wtime() + print '(A,F8.2,A)', "Total wall-clock time: ", t_wall_end - t_wall_start, " s" + print '(a,f7.3,a)' ,"Average time per frame: ", & + 1000.0*(t_wall_end - t_wall_start)/total_frames, " ms" + +end program tbcc_4fsk_simulation diff --git a/lib/jtty/wava/tbcc_performance_curves.png b/lib/jtty/wava/tbcc_performance_curves.png Binary files differnew file mode 100644 index 00000000..88d63b07 --- /dev/null +++ b/lib/jtty/wava/tbcc_performance_curves.png |
