summaryrefslogtreecommitdiff
path: root/lib/wsprd
diff options
context:
space:
mode:
authorhibby <d@vehibberd.com>2026-10-06 21:24:40 +0100
committerhibby <d@vehibberd.com>2026-10-06 21:24:40 +0100
commitc25cbdf6fb6d946175f4335fab77bfea601b56db (patch)
tree6f7a94b7b81f999e434f61b73d47e337dfd26bf2 /lib/wsprd
parent71f5689252c9f13e70e1c24856904475b2307809 (diff)
parent0685fcada9f95fe90f70b387cd7d757da8209624 (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/wsprd')
-rw-r--r--lib/wsprd/Makefile9
-rw-r--r--lib/wsprd/Makefile.MinGW8
-rw-r--r--lib/wsprd/Makefile.win3211
-rw-r--r--lib/wsprd/nhash.c383
-rw-r--r--lib/wsprd/osdwspr.f902
-rw-r--r--lib/wsprd/wsprd.c180
-rw-r--r--lib/wsprd/wsprd_stream.c571
-rw-r--r--lib/wsprd/wsprd_stream.h33
-rw-r--r--lib/wsprd/wsprd_utils.c156
-rw-r--r--lib/wsprd/wsprd_utils.h10
-rw-r--r--lib/wsprd/wsprsimf.f904
11 files changed, 884 insertions, 483 deletions
diff --git a/lib/wsprd/Makefile b/lib/wsprd/Makefile
index c8e15723..cf8d5edb 100644
--- a/lib/wsprd/Makefile
+++ b/lib/wsprd/Makefile
@@ -20,17 +20,20 @@ LIBS = -lfftw3f -lm -lgfortran
all: wsprd wsprsim
-DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h
+DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h ../lookup3.h
+
+lookup3.o: ../lookup3.c ../lookup3.h
+ ${CC} ${CFLAGS} -c $< -o $@
indexx.o: ../indexx.f90
${FC} -o indexx.o ${FFLAGS} -c ../indexx.f90
-OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o indexx.o osdwspr.o
+OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o lookup3.o indexx.o osdwspr.o
wsprd: $(OBJS1)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
-OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o
+OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o lookup3.o
wsprsim: $(OBJS2)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
diff --git a/lib/wsprd/Makefile.MinGW b/lib/wsprd/Makefile.MinGW
index d9fd6b83..4ba8f87c 100644
--- a/lib/wsprd/Makefile.MinGW
+++ b/lib/wsprd/Makefile.MinGW
@@ -21,8 +21,12 @@ LIBS = c:/JTSDK/fftw3f/libfftw3-3.dll -lm
all: wsprd
-DEPS = fano.h
-OBJS1 = wsprd.o wsprd_utils.o fano.o tab.o nhash.o
+DEPS = fano.h nhash.h ../lookup3.h
+
+lookup3.o: ../lookup3.c ../lookup3.h
+ ${CC} ${CFLAGS} -c $< -o $@
+
+OBJS1 = wsprd.o wsprd_utils.o fano.o tab.o nhash.o lookup3.o
wsprd: $(OBJS1)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
diff --git a/lib/wsprd/Makefile.win32 b/lib/wsprd/Makefile.win32
index 8d600d71..a9beb435 100644
--- a/lib/wsprd/Makefile.win32
+++ b/lib/wsprd/Makefile.win32
@@ -21,18 +21,21 @@ LIBS = c:/JTSDK/fftw3f/libfftw3-3.dll -lm
all: wsprd.exe wsprsim.exe wsprd_exp.exe
-DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h
+DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h ../lookup3.h
-OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o
+lookup3.o: ../lookup3.c ../lookup3.h
+ ${CC} ${CFLAGS} -c $< -o $@
+
+OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o lookup3.o
wsprd.exe: $(OBJS1)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
-OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o
+OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o lookup3.o
wsprsim.exe: $(OBJS2)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
OBJS3 = wsprd_exp.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o \
- nhash.o
+ nhash.o lookup3.o
wsprd_exp.exe: $(OBJS3)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
diff --git a/lib/wsprd/nhash.c b/lib/wsprd/nhash.c
index 5bf6ce04..ca52f262 100644
--- a/lib/wsprd/nhash.c
+++ b/lib/wsprd/nhash.c
@@ -1,383 +1,10 @@
-/*
- This file is part of wsprd.
-
- File name: nhash.c
-
- *------------------------------------------------------------------------------
- *
- * This file is part of the WSPR application, Weak Signal Propogation Reporter
- *
- * File Name: nhash.c
- * Description: Functions to produce 32-bit hashes for hash table lookup
- *
- * Copyright (C) 2008-2014 Joseph Taylor, K1JT
- * License: GNU GPL v3+
- *
- * This program is free software; you can redistribute it and/or modify it under
- * the terms of the GNU General Public License as published by the Free Software
- * Foundation; either version 3 of the License, or (at your option) any later
- * version.
- *
- * This program is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
- * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
- * details.
- *
- * You should have received a copy of the GNU General Public License along with
- * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
- * Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Files: lookup3.c
- * Copyright: Copyright (C) 2006 Bob Jenkins <bob_jenkins@burtleburtle.net>
- * License: public-domain
- * You may use this code any way you wish, private, educational, or commercial.
- * It's free.
- *
- *-------------------------------------------------------------------------------
-*/
-
-/*
-These are functions for producing 32-bit hashes for hash table lookup.
-hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
-are externally useful functions. Routines to test the hash are included
-if SELF_TEST is defined. You can use this free for any purpose. It's in
-the public domain. It has no warranty.
-
-You probably want to use hashlittle(). hashlittle() and hashbig()
-hash byte arrays. hashlittle() is is faster than hashbig() on
-little-endian machines. Intel and AMD are little-endian machines.
-On second thought, you probably want hashlittle2(), which is identical to
-hashlittle() except it returns two 32-bit hashes for the price of one.
-You could implement hashbig2() if you wanted but I haven't bothered here.
-
-If you want to find a hash of, say, exactly 7 integers, do
- a = i1; b = i2; c = i3;
- mix(a,b,c);
- a += i4; b += i5; c += i6;
- mix(a,b,c);
- a += i7;
- final(a,b,c);
-then use c as the hash value. If you have a variable length array of
-4-byte integers to hash, use hashword(). If you have a byte array (like
-a character string), use hashlittle(). If you have several byte arrays, or
-a mix of things, see the comments above hashlittle().
-
-Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
-then mix those integers. This is fast (you can do a lot more thorough
-mixing with 12*3 instructions on 3 integers than you can with 3 instructions
-on 1 byte), but shoehorning those bytes into integers efficiently is messy.
-*/
-
-#define SELF_TEST 1
-
-#include <stdio.h> /* defines printf for tests */
-#include <time.h> /* defines time_t for timings in the test */
#include "nhash.h"
-//#include <sys/param.h> /* attempt to define endianness */
-//#ifdef linux
-//# include <endian.h> /* attempt to define endianness */
-//#endif
-
-#define HASH_LITTLE_ENDIAN 1
-
-#define hashsize(n) ((uint32_t)1<<(n))
-#define hashmask(n) (hashsize(n)-1)
-#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
-
-/*
--------------------------------------------------------------------------------
-mix -- mix 3 32-bit values reversibly.
-
-This is reversible, so any information in (a,b,c) before mix() is
-still in (a,b,c) after mix().
-
-If four pairs of (a,b,c) inputs are run through mix(), or through
-mix() in reverse, there are at least 32 bits of the output that
-are sometimes the same for one pair and different for another pair.
-This was tested for:
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
-satisfy this are
- 4 6 8 16 19 4
- 9 15 3 18 27 15
- 14 9 3 7 17 3
-Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
-for "differ" defined as + with a one-bit base and a two-bit delta. I
-used http://burtleburtle.net/bob/hash/avalanche.html to choose
-the operations, constants, and arrangements of the variables.
-
-This does not achieve avalanche. There are input bits of (a,b,c)
-that fail to affect some output bits of (a,b,c), especially of a. The
-most thoroughly mixed value is c, but it doesn't really even achieve
-avalanche in c.
-
-This allows some parallelism. Read-after-writes are good at doubling
-the number of bits affected, so the goal of mixing pulls in the opposite
-direction as the goal of parallelism. I did what I could. Rotates
-seem to cost as much as shifts on every machine I could lay my hands
-on, and rotates are much kinder to the top and bottom bits, so I used
-rotates.
--------------------------------------------------------------------------------
-*/
-#define mix(a,b,c) \
-{ \
- a -= c; a ^= rot(c, 4); c += b; \
- b -= a; b ^= rot(a, 6); a += c; \
- c -= b; c ^= rot(b, 8); b += a; \
- a -= c; a ^= rot(c,16); c += b; \
- b -= a; b ^= rot(a,19); a += c; \
- c -= b; c ^= rot(b, 4); b += a; \
-}
-
-/*
--------------------------------------------------------------------------------
-final -- final mixing of 3 32-bit values (a,b,c) into c
-
-Pairs of (a,b,c) values differing in only a few bits will usually
-produce values of c that look totally different. This was tested for
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-These constants passed:
- 14 11 25 16 4 14 24
- 12 14 25 16 4 14 24
-and these came close:
- 4 8 15 26 3 22 24
- 10 8 15 26 3 22 24
- 11 8 15 26 3 22 24
--------------------------------------------------------------------------------
-*/
-#define final(a,b,c) \
-{ \
- c ^= b; c -= rot(b,14); \
- a ^= c; a -= rot(c,11); \
- b ^= a; b -= rot(a,25); \
- c ^= b; c -= rot(b,16); \
- a ^= c; a -= rot(c,4); \
- b ^= a; b -= rot(a,14); \
- c ^= b; c -= rot(b,24); \
-}
-/*
--------------------------------------------------------------------------------
-hashlittle() -- hash a variable-length key into a 32-bit value
- k : the key (the unaligned variable-length array of bytes)
- length : the length of the key, counting by bytes
- initval : can be any 4-byte value
-Returns a 32-bit value. Every bit of the key affects every bit of
-the return value. Two keys differing by one or two bits will have
-totally different hash values.
+#include "../lookup3.h"
-The best hash table sizes are powers of 2. There is no need to do
-mod a prime (mod is sooo slow!). If you need less than 32 bits,
-use a bitmask. For example, if you need only 10 bits, do
- h = (h & hashmask(10));
-In which case, the hash table should have hashsize(10) elements.
-
-If you are hashing n strings (uint8_t **)k, do it like this:
- for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
-
-By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
-code any way you wish, private, educational, or commercial. It's free.
-
-Use for hash table lookup, or anything where one collision in 2^^32 is
-acceptable. Do NOT use for cryptographic purposes.
--------------------------------------------------------------------------------
-*/
-
-uint32_t nhash( const void *key, size_t length, uint32_t initval)
+uint32_t nhash(const void *key, size_t length, uint32_t initval)
{
- uint32_t a,b,c; /* internal state */
- union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
-
- /* Set up the internal state */
- a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
-
- u.ptr = key;
- if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
- const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
-
- /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- b += k[1];
- c += k[2];
- mix(a,b,c);
- length -= 12;
- k += 3;
- }
-
- /*----------------------------- handle the last (probably partial) block */
- /*
- * "k[2]&0xffffff" actually reads beyond the end of the string, but
- * then masks off the part it's not allowed to read. Because the
- * string is aligned, the masked-off tail is in the same word as the
- * rest of the string. Every machine with memory protection I've seen
- * does it on word boundaries, so is OK with this. But VALGRIND will
- * still catch it and complain. The masking trick does make the hash
- * noticably faster for short strings (like English words).
- */
-#ifndef VALGRIND
-
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
- case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
- case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
- case 6 : b+=k[1]&0xffff; a+=k[0]; break;
- case 5 : b+=k[1]&0xff; a+=k[0]; break;
- case 4 : a+=k[0]; break;
- case 3 : a+=k[0]&0xffffff; break;
- case 2 : a+=k[0]&0xffff; break;
- case 1 : a+=k[0]&0xff; break;
- case 0 : return c; /* zero length strings require no mixing */
- }
-
-#else /* make valgrind happy */
-
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]; break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
- case 1 : a+=k8[0]; break;
- case 0 : return c;
- }
-
-#endif /* !valgrind */
-
- } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
- const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
- const uint8_t *k8;
-
- /*--------------- all but last block: aligned reads and different mixing */
- while (length > 12)
- {
- a += k[0] + (((uint32_t)k[1])<<16);
- b += k[2] + (((uint32_t)k[3])<<16);
- c += k[4] + (((uint32_t)k[5])<<16);
- mix(a,b,c);
- length -= 12;
- k += 6;
- }
-
- /*----------------------------- handle the last (probably partial) block */
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[4]+(((uint32_t)k[5])<<16);
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=k[4];
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=k[2];
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=k[0];
- break;
- case 1 : a+=k8[0];
- break;
- case 0 : return c; /* zero length requires no mixing */
- }
-
- } else { /* need to read the key one byte at a time */
- const uint8_t *k = (const uint8_t *)key;
-
- /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- a += ((uint32_t)k[1])<<8;
- a += ((uint32_t)k[2])<<16;
- a += ((uint32_t)k[3])<<24;
- b += k[4];
- b += ((uint32_t)k[5])<<8;
- b += ((uint32_t)k[6])<<16;
- b += ((uint32_t)k[7])<<24;
- c += k[8];
- c += ((uint32_t)k[9])<<8;
- c += ((uint32_t)k[10])<<16;
- c += ((uint32_t)k[11])<<24;
- mix(a,b,c);
- length -= 12;
- k += 12;
- }
-
- /*-------------------------------- last block: affect all 32 bits of (c) */
- switch(length) /* all the case statements fall through */
- {
- case 12: c+=((uint32_t)k[11])<<24;
- /* fall through */
- case 11: c+=((uint32_t)k[10])<<16;
- /* fall through */
- case 10: c+=((uint32_t)k[9])<<8;
- /* fall through */
- case 9 : c+=k[8];
- /* fall through */
- case 8 : b+=((uint32_t)k[7])<<24;
- /* fall through */
- case 7 : b+=((uint32_t)k[6])<<16;
- /* fall through */
- case 6 : b+=((uint32_t)k[5])<<8;
- /* fall through */
- case 5 : b+=k[4];
- /* fall through */
- case 4 : a+=((uint32_t)k[3])<<24;
- /* fall through */
- case 3 : a+=((uint32_t)k[2])<<16;
- /* fall through */
- case 2 : a+=((uint32_t)k[1])<<8;
- /* fall through */
- case 1 : a+=k[0];
- break;
- case 0 : return c;
- }
- }
-
- final(a,b,c);
- c=(32767&c);
-
- return c;
+ /* WSPR table indices use 15 bits; empty keys historically bypass the mask. */
+ uint32_t hash = wsjt_hashlittle(key, length, initval);
+ return length == 0 ? hash : hash & (uint32_t)0x7fff;
}
diff --git a/lib/wsprd/osdwspr.f90 b/lib/wsprd/osdwspr.f90
index 2a2d712d..31ece6a0 100644
--- a/lib/wsprd/osdwspr.f90
+++ b/lib/wsprd/osdwspr.f90
@@ -133,6 +133,8 @@ elseif(ndeep.eq.5) then
nt=66
ntheta=22
ntau=16
+else
+ goto 998
endif
do iorder=1,nord
diff --git a/lib/wsprd/wsprd.c b/lib/wsprd/wsprd.c
index 13f8d8b3..d442c70b 100644
--- a/lib/wsprd/wsprd.c
+++ b/lib/wsprd/wsprd.c
@@ -42,6 +42,7 @@
#include "nhash.h"
#include "wsprd_utils.h"
#include "wsprsim_utils.h"
+#include "wsprd_stream.h"
#define max(x,y) ((x) > (y) ? (x) : (y))
@@ -727,6 +728,23 @@ void usage(void)
printf(" -v verbose mode (shows dupes)\n");
printf(" -w wideband mode - decode signals within +/- 150 Hz of center\n");
printf(" -z x (x is fano metric table bias, default is 0.45)\n");
+ printf(" -0 streaming mode: read PCM audio from stdin per the\n");
+ printf(" streaming framing protocol; emit decodes as NDJSON\n");
+ printf(" on stdout. Replaces the positional\n");
+ printf(" input file argument.\n");
+}
+
+static int build_data_path(char *destination, size_t capacity,
+ const char *data_dir, const char *filename)
+{
+ const char *base = data_dir ? data_dir : ".";
+ int written = snprintf(destination, capacity, "%s/%s", base, filename);
+ if (written < 0 || (size_t)written >= capacity) {
+ fprintf(stderr, "Error: data path for '%s' exceeds %zu bytes\n",
+ filename, capacity - 1);
+ return -1;
+ }
+ return 0;
}
//***************************************************************************
@@ -740,13 +758,15 @@ int main(int argc, char *argv[])
unsigned char *symbols, *decdata, *channel_symbols, *apmask, *cw;
signed char message[]={-9,13,-35,123,57,-39,64,0,0,0,0};
char *callsign, *grid, *call_loc_pow;
- char *ptr_to_infile,*ptr_to_infile_suffix;
+ char *ptr_to_infile = NULL, *ptr_to_infile_suffix = NULL;
char *data_dir=".";
char wisdom_fname[200],all_fname[200],spots_fname[200];
char timer_fname[200],hash_fname[200];
char uttime[5],date[7];
int c,delta,maxpts=65536,verbose=0,quickmode=0,more_candidates=0, stackdecoder=0;
int usehashtable=1,wspr_type=2, ipass, nblocksize;
+ int stream_mode = 0;
+ struct wsprd_stream_config stream_cfg = {0};
int nhardmin,ihash;
int writec2=0,maxdrift;
int shift1, lagmin, lagmax, lagstep, ifmin, ifmax, not_decoded;
@@ -777,10 +797,9 @@ int main(int argc, char *argv[])
struct result decodes[50];
char *hashtab;
- hashtab=calloc(32768*13,sizeof(char));
+ hashtab=calloc(WSPRD_HASH_COUNT*WSPRD_CALLSIGN_SIZE,sizeof(char));
char *loctab;
- loctab=calloc(32768*5,sizeof(char));
- int nh;
+ loctab=calloc(WSPRD_HASH_COUNT*WSPRD_GRID4_SIZE,sizeof(char));
symbols=calloc(nbits*2,sizeof(unsigned char));
apmask=calloc(162,sizeof(unsigned char));
cw=calloc(162,sizeof(unsigned char));
@@ -818,8 +837,26 @@ int main(int argc, char *argv[])
idat=calloc(maxpts,sizeof(float));
qdat=calloc(maxpts,sizeof(float));
+ if (!hashtab || !loctab || !symbols || !apmask || !cw || !decdata ||
+ !channel_symbols || !callsign || !grid || !call_loc_pow ||
+ !idat || !qdat) {
+ fprintf(stderr, "Error: unable to allocate wsprd decoder buffers\n");
+ free(hashtab);
+ free(loctab);
+ free(symbols);
+ free(apmask);
+ free(cw);
+ free(decdata);
+ free(channel_symbols);
+ free(callsign);
+ free(grid);
+ free(call_loc_pow);
+ free(idat);
+ free(qdat);
+ return EXIT_FAILURE;
+ }
- while ( (c = getopt(argc, argv, "a:BcC:de:f:HJmo:qstwvz:")) !=-1 ) {
+ while ( (c = getopt(argc, argv, "a:BcC:de:f:HJmo:qstwvz:0")) !=-1 ) {
switch (c) {
case 'a':
data_dir = optarg;
@@ -872,6 +909,9 @@ int main(int argc, char *argv[])
case 'z':
bias=strtod(optarg,NULL); //fano metric bias (default is 0.45)
break;
+ case '0': // --stream (long-name parity with jt9 --stream)
+ stream_mode = 1;
+ break;
case '?':
usage();
return 1;
@@ -884,15 +924,19 @@ int main(int argc, char *argv[])
return EXIT_FAILURE;
}
- if( optind+1 > argc) {
+ if( !stream_mode && optind+1 > argc) {
usage();
return 1;
- } else {
+ } else if (!stream_mode) {
ptr_to_infile=argv[optind];
}
if( stackdecoder ) {
stack=calloc(stacksize,sizeof(struct snode));
+ if (!stack) {
+ fprintf(stderr, "Error: unable to allocate wsprd stack decoder\n");
+ return EXIT_FAILURE;
+ }
}
// setup metric table
@@ -902,23 +946,18 @@ int main(int argc, char *argv[])
}
FILE *fp_fftwf_wisdom_file, *fall_wspr, *fwsprd, *fhash, *ftimer;
- strcpy(wisdom_fname,".");
- strcpy(all_fname,".");
- strcpy(spots_fname,".");
- strcpy(timer_fname,".");
- strcpy(hash_fname,".");
- if(data_dir != NULL) {
- strncpy(wisdom_fname,data_dir, sizeof wisdom_fname);
- strncpy(all_fname,data_dir, sizeof all_fname);
- strncpy(spots_fname,data_dir, sizeof spots_fname);
- strncpy(timer_fname,data_dir, sizeof timer_fname);
- strncpy(hash_fname,data_dir, sizeof hash_fname);
+ if (build_data_path(wisdom_fname, sizeof wisdom_fname, data_dir,
+ "wspr_wisdom.dat") != 0 ||
+ build_data_path(all_fname, sizeof all_fname, data_dir,
+ "ALL_WSPR.TXT") != 0 ||
+ build_data_path(spots_fname, sizeof spots_fname, data_dir,
+ "wspr_spots.txt") != 0 ||
+ build_data_path(timer_fname, sizeof timer_fname, data_dir,
+ "wspr_timer.out") != 0 ||
+ build_data_path(hash_fname, sizeof hash_fname, data_dir,
+ "hashtable.txt") != 0) {
+ return EXIT_FAILURE;
}
- strncat(wisdom_fname,"/wspr_wisdom.dat",20);
- strncat(all_fname,"/ALL_WSPR.TXT",20);
- strncat(spots_fname,"/wspr_spots.txt",20);
- strncat(timer_fname,"/wspr_timer.out",20);
- strncat(hash_fname,"/hashtable.txt",20);
if ((fp_fftwf_wisdom_file = fopen(wisdom_fname, "r"))) { //Open FFTW wisdom
fftwf_import_wisdom_from_file(fp_fftwf_wisdom_file);
fclose(fp_fftwf_wisdom_file);
@@ -938,17 +977,35 @@ int main(int argc, char *argv[])
}
ftimer=fopen(timer_fname,"w");
- if( strstr(ptr_to_infile,".wav") ) {
+ if (stream_mode) {
+ // Read PCM from stdin per the streaming protocol. Configure frame
+ // supplies date/time/dialfreq/wspr_type; audio frames carry int16
+ // PCM @ 12 kHz mono.
+ wsprd_stream_emit_ready();
+ t0 = clock();
+ npoints = wsprd_stream_read(&stream_cfg, idat, qdat);
+ treadwav += (float)(clock()-t0)/CLOCKS_PER_SEC;
+ if (npoints == 1) return 1;
+ wspr_type = stream_cfg.wspr_type;
+ dialfreq = stream_cfg.dialfreq - (dialfreq_error * 1.0e-06);
+ strncpy(date, stream_cfg.date, 6); date[6] = '\0';
+ strncpy(uttime, stream_cfg.uttime, 4); uttime[4] = '\0';
+ } else if( strstr(ptr_to_infile,".wav") ) {
ptr_to_infile_suffix=strstr(ptr_to_infile,".wav");
-
+
t0 = clock();
npoints=readwavfile(ptr_to_infile, wspr_type, idat, qdat);
treadwav += (float)(clock()-t0)/CLOCKS_PER_SEC;
-
+
if( npoints == 1 ) {
return 1;
}
dialfreq=dialfreq_cmdline - (dialfreq_error*1.0e-06);
+ // Parse date and time from given filename
+ strncpy(date,ptr_to_infile_suffix-11,6);
+ strncpy(uttime,ptr_to_infile_suffix-4,4);
+ date[6]='\0';
+ uttime[4]='\0';
} else if ( strstr(ptr_to_infile,".c2") !=0 ) {
ptr_to_infile_suffix=strstr(ptr_to_infile,".c2");
npoints=readc2file(ptr_to_infile, idat, qdat, &dialfreq, &wspr_type);
@@ -956,23 +1013,34 @@ int main(int argc, char *argv[])
return 1;
}
dialfreq -= (dialfreq_error*1.0e-06);
+ // Parse date and time from given filename
+ strncpy(date,ptr_to_infile_suffix-11,6);
+ strncpy(uttime,ptr_to_infile_suffix-4,4);
+ date[6]='\0';
+ uttime[4]='\0';
} else {
printf("Error: Failed to open %s\n",ptr_to_infile);
printf("WSPR file must have suffix .wav or .c2\n");
return 1;
}
- // Parse date and time from given filename
- strncpy(date,ptr_to_infile_suffix-11,6);
- strncpy(uttime,ptr_to_infile_suffix-4,4);
- date[6]='\0';
- uttime[4]='\0';
-
// Do windowed ffts over 2 symbols, stepped by half symbols
int nffts=4*floor(npoints/512)-1;
fftin=(fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex)*512);
fftout=(fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex)*512);
+ if (!fftin || !fftout) {
+ fprintf(stderr, "Error: unable to allocate wsprd FFT buffers\n");
+ if (fftin) fftwf_free(fftin);
+ if (fftout) fftwf_free(fftout);
+ return EXIT_FAILURE;
+ }
PLAN3 = fftwf_plan_dft_1d(512, fftin, fftout, FFTW_FORWARD, PATIENCE);
+ if (!PLAN3) {
+ fprintf(stderr, "Error: unable to create wsprd FFT plan\n");
+ fftwf_free(fftin);
+ fftwf_free(fftout);
+ return EXIT_FAILURE;
+ }
float ps[512][nffts];
float w[512];
@@ -981,13 +1049,10 @@ int main(int argc, char *argv[])
}
if( usehashtable ) {
- char line[80], hcall[13], hgrid[5];
+ char line[80];
if( (fhash=fopen(hash_fname,"r+")) ) {
while (fgets(line, sizeof(line), fhash) != NULL) {
- hgrid[0]='\0';
- sscanf(line,"%d %s %s",&nh,hcall,hgrid);
- strcpy(hashtab+nh*13,hcall);
- if(strlen(hgrid)>0) strcpy(loctab+nh*5,hgrid);
+ wsprd_load_hash_line(line, hashtab, loctab);
}
} else {
fhash=fopen(hash_fname,"w+");
@@ -1003,7 +1068,7 @@ int main(int argc, char *argv[])
maxdrift=4;
minsync2=0.12;
}
- if(ipass == 2 ) {
+ else {
nblocksize=4; // try 3 blocksizes plus bitbybit normalization
maxdrift=0; // no drift for smaller frequency estimator variance
minsync2=0.10;
@@ -1444,7 +1509,8 @@ int main(int argc, char *argv[])
if(!strcmp(callsign,allcalls[i]) &&
(fabs(f1-allfreqs[i]) <4.0)) dupe=1;
}
- if( (verbose || !dupe) && !noprint) {
+ if( (verbose || !dupe) && !noprint &&
+ uniques < (int)(sizeof decodes / sizeof decodes[0]) ) {
strcpy(allcalls[uniques],callsign);
allfreqs[uniques]=f1;
uniques++;
@@ -1502,9 +1568,16 @@ int main(int argc, char *argv[])
}
for (i=0; i<uniques; i++) {
- printf("%4s %3.0f %4.1f %10.6f %2d %-s \n",
- decodes[i].time, decodes[i].snr,decodes[i].dt, decodes[i].freq,
- (int)decodes[i].drift, decodes[i].message);
+ if (stream_mode) {
+ wsprd_stream_emit_decode(date, decodes[i].time,
+ decodes[i].snr, decodes[i].dt,
+ decodes[i].freq, (int)decodes[i].drift,
+ decodes[i].message);
+ } else {
+ printf("%4s %3.0f %4.1f %10.6f %2d %-s \n",
+ decodes[i].time, decodes[i].snr,decodes[i].dt, decodes[i].freq,
+ (int)decodes[i].drift, decodes[i].message);
+ }
fprintf(fall_wspr,
"%6s %4s %3.0f %5.2f %11.7f %-22s %2d %5.2f %2d %2d %4d %2d %3d %5u %5d\n",
decodes[i].date, decodes[i].time, decodes[i].snr,
@@ -1521,7 +1594,11 @@ int main(int argc, char *argv[])
decodes[i].jitter);
}
- printf("<DecodeFinished>\n");
+ if (stream_mode) {
+ wsprd_stream_emit_decode_finished(date, uttime);
+ } else {
+ printf("<DecodeFinished>\n");
+ }
fftwf_free(fftin);
fftwf_free(fftout);
@@ -1553,15 +1630,17 @@ int main(int argc, char *argv[])
fclose(fwsprd);
// fclose(fdiag);
fclose(ftimer);
- fftwf_destroy_plan(PLAN1);
- fftwf_destroy_plan(PLAN2);
- fftwf_destroy_plan(PLAN3);
+ if (PLAN1) fftwf_destroy_plan(PLAN1);
+ if (PLAN2) fftwf_destroy_plan(PLAN2);
+ if (PLAN3) fftwf_destroy_plan(PLAN3);
if( usehashtable ) {
fhash=fopen(hash_fname,"w");
- for (i=0; i<32768; i++) {
- if( strncmp(hashtab+i*13,"\0",1) != 0 ) {
- fprintf(fhash,"%5d %s %s\n",i,hashtab+i*13,loctab+i*5);
+ for (i=0; i<WSPRD_HASH_COUNT; i++) {
+ if( strncmp(hashtab+i*WSPRD_CALLSIGN_SIZE,"\0",1) != 0 ) {
+ fprintf(fhash,"%5d %s %s\n",i,
+ hashtab+i*WSPRD_CALLSIGN_SIZE,
+ loctab+i*WSPRD_GRID4_SIZE);
}
}
fclose(fhash);
@@ -1570,9 +1649,12 @@ int main(int argc, char *argv[])
free(hashtab);
free(loctab);
free(symbols);
+ free(apmask);
+ free(cw);
free(decdata);
free(channel_symbols);
free(callsign);
+ free(grid);
free(call_loc_pow);
free(idat);
free(qdat);
diff --git a/lib/wsprd/wsprd_stream.c b/lib/wsprd/wsprd_stream.c
new file mode 100644
index 00000000..8d4628a2
--- /dev/null
+++ b/lib/wsprd/wsprd_stream.c
@@ -0,0 +1,571 @@
+/*
+ * wsprd streaming layer.
+ *
+ * Adds `wsprd --stream` mode: read PCM audio from stdin (per the
+ * streaming framing) instead of from a .wav/.c2 file, run the
+ * standard wsprd decode pipeline, and emit decodes as NDJSON on stdout
+ * (matching the jt9 --stream protocol).
+ *
+ * Streaming protocol summary:
+ * 1. WSJT session header (8 bytes): magic 'WSJT' + fmt + ch + rate_kHz
+ * LE u16. fmt=0x00 = int16 PCM (same as jt9). For wsprd, audio is
+ * always 12 kHz mono int16.
+ * 2. Frames: [type:1][len:4 LE][body:len]
+ * type 0x01 = audio chunk (int16 PCM samples)
+ * type 0x02 = control JSON (configure / halt)
+ * 3. Configure frame schema (subset of jt9):
+ * {"t":"configure","date":"YYMMDD","time":"HHMM",
+ * "dialfreq":14.0956,"wspr_type":2,
+ * "mycall":"K1JT","mygrid":"FN20"}
+ * The configure frame must arrive before enough audio for one period.
+ * 4. Halt frame: {"t":"halt"} — drains current period if data buffered,
+ * emits decode_finished, exits clean.
+ *
+ * NDJSON schema (v=1, mirrors jt9):
+ * {"v":1,"t":"ready","modes":["WSPR"],"protocol":1}
+ * {"v":1,"t":"decode","mode":"WSPR","date":"YYMMDD","time":"HHMM",
+ * "snr":-12,"dt":0.6,"freq":14.097103,"drift":0,"message":"K1JT FN20 33"}
+ * {"v":1,"t":"decode_finished","date":"YYMMDD","time":"HHMM"}
+ * {"v":1,"t":"error","msg":"..."}
+ *
+ * Scope:
+ * - One period per session. Halt after the first period's decode.
+ * Multi-period (continuous) is a refinement.
+ * - PCM input only (fmt=0x00). C2 baseband (fmt=0x02) is a refinement.
+ * - Hand-rolled JSON parsing (strstr-based). Acceptable for the closed
+ * configure schema.
+ * - All diagnostics go to stderr (consumers MUST drain).
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include <errno.h>
+#include <limits.h>
+#include <math.h>
+#include <fftw3.h>
+#ifdef _WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+
+#include "wsprd_stream.h"
+
+#define WSJT_MAGIC "WSJT"
+#define WSJT_FMT_PCM 0x00
+#define FRAME_AUDIO 0x01
+#define FRAME_CONTROL 0x02
+
+// Buffer the producer's audio chunks. Sized for WSPR-15 worst case
+// (8 * 114 * 12000 = 10,944,000 samples). WSPR-2 needs only 1,368,000.
+#define MAX_PCM_SAMPLES (8 * 114 * 12000)
+#define MAX_CONTROL_FRAME 1024U
+
+// ============================================================
+// JSON parsing for the flat, ASCII streaming control schema.
+// ============================================================
+
+static const char *skip_space(const char *p) {
+ while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
+ return p;
+}
+
+static const char *skip_json_string(const char *p) {
+ if (*p != '"') return NULL;
+ for (p++; *p; p++) {
+ if (*p == '\\' && p[1]) {
+ p++;
+ } else if (*p == '"') {
+ return p + 1;
+ }
+ }
+ return NULL;
+}
+
+static const char *json_find_key(const char *json, const char *key) {
+ const size_t key_len = strlen(key);
+ const char *p = skip_space(json);
+ if (*p != '{') return NULL;
+ p++;
+
+ for (;;) {
+ p = skip_space(p);
+ if (*p == ',') {
+ p = skip_space(p + 1);
+ }
+ if (*p == '}') return NULL;
+ if (*p != '"') return NULL;
+
+ const char *name = p + 1;
+ const char *after_name = skip_json_string(p);
+ if (!after_name) return NULL;
+ const size_t name_len = (size_t)(after_name - name - 1);
+ p = skip_space(after_name);
+ if (*p != ':') return NULL;
+ const char *value = skip_space(p + 1);
+ if (name_len == key_len && memcmp(name, key, key_len) == 0) {
+ return *value ? value : NULL;
+ }
+
+ if (*value == '"') {
+ p = skip_json_string(value);
+ if (!p) return NULL;
+ } else {
+ p = value;
+ while (*p && *p != ',' && *p != '}') p++;
+ }
+ if (*p == '}') return NULL;
+ }
+}
+
+static int json_get_string(const char *json, const char *key,
+ char *out, size_t out_size) {
+ const char *p = json_find_key(json, key);
+ if (!p || *p != '"') return -1;
+ p++;
+ size_t i = 0;
+ while (*p && *p != '"' && i + 1 < out_size) {
+ out[i++] = *p++;
+ }
+ out[i] = '\0';
+ return (*p == '"') ? 0 : -1;
+}
+
+static int json_get_int(const char *json, const char *key, int *out) {
+ const char *p = json_find_key(json, key);
+ if (!p) return -1;
+ char *end = NULL;
+ errno = 0;
+ long v = strtol(p, &end, 10);
+ if (end == p || errno == ERANGE || v < INT_MIN || v > INT_MAX) return -1;
+ end = (char *)skip_space(end);
+ if (*end != ',' && *end != '}') return -1;
+ *out = (int) v;
+ return 0;
+}
+
+static int json_get_double(const char *json, const char *key, double *out) {
+ const char *p = json_find_key(json, key);
+ if (!p) return -1;
+ char *end = NULL;
+ double v = strtod(p, &end);
+ if (end == p) return -1;
+ *out = v;
+ return 0;
+}
+
+// ============================================================
+// Frame I/O.
+// ============================================================
+
+static void set_stdin_binary(void) {
+#ifdef _WIN32
+ _setmode(_fileno(stdin), _O_BINARY);
+#endif
+}
+
+static int wsjt_header_read(FILE *fp) {
+ unsigned char hdr[8];
+ if (fread(hdr, 1, 8, fp) != 8) {
+ fprintf(stderr, "wsprd --stream: short read on WSJT header\n");
+ return -1;
+ }
+ if (memcmp(hdr, WSJT_MAGIC, 4) != 0) {
+ fprintf(stderr, "wsprd --stream: bad magic; expected 'WSJT'\n");
+ return -1;
+ }
+ unsigned char fmt = hdr[4];
+ unsigned char ch = hdr[5];
+ uint16_t rate_khz = (uint16_t)hdr[6] | ((uint16_t)hdr[7] << 8);
+ if (fmt != WSJT_FMT_PCM) {
+ fprintf(stderr,
+ "wsprd --stream: unsupported fmt=0x%02x (only 0x00 PCM today)\n",
+ fmt);
+ return -1;
+ }
+ if (ch != 1) {
+ fprintf(stderr,
+ "wsprd --stream: unsupported channels=%u (only mono supported)\n",
+ ch);
+ return -1;
+ }
+ if (rate_khz != 12) {
+ fprintf(stderr,
+ "wsprd --stream: unsupported rate=%u kHz (only 12 kHz supported)\n",
+ rate_khz);
+ return -1;
+ }
+ fprintf(stderr,
+ "wsprd --stream: header ok (fmt=%u ch=%u rate=%u kHz)\n",
+ fmt, ch, rate_khz);
+ return 0;
+}
+
+// Reads one frame envelope. *body is malloc'd on success; caller frees.
+// Returns 0 ok, -1 err, +1 EOF (clean producer-disconnect).
+static int frame_read(FILE *fp, unsigned char *type, void **body, uint32_t *len) {
+ unsigned char hdr[5];
+ size_t nr = fread(hdr, 1, 5, fp);
+ if (nr == 0) return 1; // clean EOF
+ if (nr != 5) {
+ fprintf(stderr, "wsprd --stream: short read on frame header\n");
+ return -1;
+ }
+ *type = hdr[0];
+ *len = (uint32_t)hdr[1] | ((uint32_t)hdr[2] << 8) |
+ ((uint32_t)hdr[3] << 16) | ((uint32_t)hdr[4] << 24);
+ const uint32_t max_len = *type == FRAME_CONTROL
+ ? MAX_CONTROL_FRAME
+ : (uint32_t)(MAX_PCM_SAMPLES * sizeof(int16_t));
+ if (*len > max_len) {
+ char detail[160];
+ snprintf(detail, sizeof detail,
+ "frame length %u exceeds type capacity %u", *len, max_len);
+ wsprd_stream_emit_error_code("frame_too_large", detail);
+ fprintf(stderr, "wsprd --stream: %s\n", detail);
+ return -1;
+ }
+ if (*len == 0) {
+ *body = NULL;
+ return 0;
+ }
+ *body = malloc(*len);
+ if (!*body) {
+ fprintf(stderr, "wsprd --stream: alloc %u bytes failed\n", *len);
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate frame body");
+ return -1;
+ }
+ if (fread(*body, 1, *len, fp) != *len) {
+ fprintf(stderr, "wsprd --stream: short read on frame body (%u bytes)\n",
+ *len);
+ free(*body);
+ *body = NULL;
+ wsprd_stream_emit_error_code("frame_read_error",
+ "short read on frame body");
+ return -1;
+ }
+ return 0;
+}
+
+// ============================================================
+// PCM → I/Q FFT/extract/IFFT (mirrors readwavfile lines 155-188).
+// ============================================================
+
+static unsigned long pcm_to_iq(int16_t *pcm, size_t npcm, int ntrmin,
+ float *idat, float *qdat) {
+ int nfft1, nfft2 = 46080, nh2 = nfft2 / 2, i0;
+ double df;
+ size_t expected_npcm;
+ float *realin = NULL;
+ fftwf_complex *fftout = NULL;
+ fftwf_complex *fftin = NULL;
+ fftwf_complex *fftout2 = NULL;
+ fftwf_plan plan_fwd = NULL;
+ fftwf_plan plan_inv = NULL;
+ unsigned long result = 1;
+
+ if (ntrmin == 2) {
+ nfft1 = nfft2 * 32;
+ df = 12000.0 / nfft1;
+ i0 = 1500.0 / df + 0.5;
+ expected_npcm = 114 * 12000;
+ } else if (ntrmin == 15) {
+ nfft1 = nfft2 * 8 * 32;
+ df = 12000.0 / nfft1;
+ i0 = (1500.0 + 112.5) / df + 0.5;
+ expected_npcm = 8 * 114 * 12000;
+ } else {
+ fprintf(stderr, "wsprd --stream: invalid wspr_type=%d\n", ntrmin);
+ wsprd_stream_emit_error_code("invalid_wspr_type",
+ "wspr_type must be 2 or 15");
+ return 1;
+ }
+
+ if (npcm < expected_npcm) {
+ fprintf(stderr,
+ "wsprd --stream: short PCM (got %zu, expected %zu for WSPR-%d)\n",
+ npcm, expected_npcm, ntrmin);
+ wsprd_stream_emit_error_code("insufficient_audio",
+ "not enough PCM samples for the configured WSPR type");
+ return 1;
+ }
+
+ realin = fftwf_malloc(sizeof(float) * (size_t)nfft1);
+ fftout = fftwf_malloc(sizeof(fftwf_complex) * ((size_t)nfft1 / 2 + 1));
+ if (!realin || !fftout) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate streaming FFT buffers");
+ goto cleanup;
+ }
+ plan_fwd = fftwf_plan_dft_r2c_1d(nfft1, realin, fftout, FFTW_ESTIMATE);
+ if (!plan_fwd) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to create streaming forward FFT plan");
+ goto cleanup;
+ }
+
+ for (size_t i = 0; i < expected_npcm; i++) realin[i] = pcm[i] / 32768.0f;
+ for (size_t i = expected_npcm; i < (size_t)nfft1; i++) realin[i] = 0.0f;
+
+ fftwf_execute(plan_fwd);
+ fftwf_destroy_plan(plan_fwd);
+ plan_fwd = NULL;
+ fftwf_free(realin);
+ realin = NULL;
+
+ fftin = fftwf_malloc(sizeof(fftwf_complex) * (size_t)nfft2);
+ if (!fftin) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate streaming inverse FFT input");
+ goto cleanup;
+ }
+ for (size_t i = 0; i < (size_t)nfft2; i++) {
+ size_t j = i0 + i;
+ if (i > (size_t)nh2) j = j - nfft2;
+ fftin[i][0] = fftout[j][0];
+ fftin[i][1] = fftout[j][1];
+ }
+ fftwf_free(fftout);
+ fftout = NULL;
+
+ fftout2 = fftwf_malloc(sizeof(fftwf_complex) * (size_t)nfft2);
+ if (!fftout2) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate streaming inverse FFT output");
+ goto cleanup;
+ }
+ plan_inv = fftwf_plan_dft_1d(nfft2, fftin, fftout2, FFTW_BACKWARD,
+ FFTW_ESTIMATE);
+ if (!plan_inv) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to create streaming inverse FFT plan");
+ goto cleanup;
+ }
+ fftwf_execute(plan_inv);
+ fftwf_destroy_plan(plan_inv);
+ plan_inv = NULL;
+
+ for (size_t i = 0; i < (size_t)nfft2; i++) {
+ idat[i] = fftout2[i][0] / 1000.0f;
+ qdat[i] = fftout2[i][1] / 1000.0f;
+ }
+ result = (unsigned long)nfft2;
+
+cleanup:
+ if (plan_fwd) fftwf_destroy_plan(plan_fwd);
+ if (plan_inv) fftwf_destroy_plan(plan_inv);
+ if (realin) fftwf_free(realin);
+ if (fftout) fftwf_free(fftout);
+ if (fftin) fftwf_free(fftin);
+ if (fftout2) fftwf_free(fftout2);
+ return result;
+}
+
+// ============================================================
+// Public API (declared in wsprd_stream.h).
+// ============================================================
+
+void wsprd_stream_emit_ready(void) {
+ fputs("{\"v\":1,\"t\":\"ready\",\"modes\":[\"WSPR\"],\"protocol\":1}\n",
+ stdout);
+ fflush(stdout);
+}
+
+// JSON-escape a string into out. Best-effort: handles ASCII printable
+// and the must-escape control chars per RFC 8259.
+static void json_escape_into(const char *src, char *out, size_t out_size) {
+ size_t o = 0;
+ for (const char *p = src; *p && o + 6 < out_size; p++) {
+ unsigned char c = (unsigned char) *p;
+ if (c == '"' || c == '\\') {
+ if (o + 2 < out_size) { out[o++] = '\\'; out[o++] = c; }
+ } else if (c < 0x20) {
+ o += snprintf(out + o, out_size - o, "\\u%04x", c);
+ } else {
+ out[o++] = c;
+ }
+ }
+ out[o] = '\0';
+}
+
+void wsprd_stream_emit_decode(const char *date, const char *uttime,
+ float snr, float dt, double freq,
+ int drift, const char *message) {
+ char esc_msg[80];
+ json_escape_into(message ? message : "", esc_msg, sizeof esc_msg);
+ fprintf(stdout,
+ "{\"v\":1,\"t\":\"decode\",\"mode\":\"WSPR\","
+ "\"date\":\"%s\",\"time\":\"%s\","
+ "\"snr\":%.0f,\"dt\":%.1f,\"freq\":%.6f,"
+ "\"drift\":%d,\"message\":\"%s\"}\n",
+ date ? date : "",
+ uttime ? uttime : "",
+ snr, dt, freq, drift, esc_msg);
+ fflush(stdout);
+}
+
+void wsprd_stream_emit_decode_finished(const char *date, const char *uttime) {
+ fprintf(stdout,
+ "{\"v\":1,\"t\":\"decode_finished\","
+ "\"date\":\"%s\",\"time\":\"%s\"}\n",
+ date ? date : "",
+ uttime ? uttime : "");
+ fflush(stdout);
+}
+
+void wsprd_stream_emit_error(const char *msg) {
+ char esc[256];
+ json_escape_into(msg ? msg : "", esc, sizeof esc);
+ fprintf(stdout, "{\"v\":1,\"t\":\"error\",\"msg\":\"%s\"}\n", esc);
+ fflush(stdout);
+}
+
+void wsprd_stream_emit_error_code(const char *code, const char *detail) {
+ char esc_code[80];
+ char esc_detail[256];
+ json_escape_into(code ? code : "", esc_code, sizeof esc_code);
+ json_escape_into(detail ? detail : "", esc_detail, sizeof esc_detail);
+ fprintf(stdout,
+ "{\"v\":1,\"t\":\"error\",\"code\":\"%s\",\"detail\":\"%s\"}\n",
+ esc_code, esc_detail);
+ fflush(stdout);
+}
+
+// Read header + frames from stdin until configure + enough audio + halt
+// (or audio-exhaustion + EOF) are received. Populates *cfg and the
+// supplied I/Q buffers via FFT/extract/IFFT. Returns nfft2 (number of
+// complex samples populated) on success; 1 on protocol error.
+unsigned long wsprd_stream_read(struct wsprd_stream_config *cfg,
+ float *idat, float *qdat) {
+ set_stdin_binary();
+ if (wsjt_header_read(stdin) != 0) return 1;
+
+ int16_t *pcm = calloc(MAX_PCM_SAMPLES, sizeof(int16_t));
+ if (!pcm) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate PCM accumulation buffer");
+ return 1;
+ }
+
+ memset(cfg, 0, sizeof *cfg);
+ cfg->wspr_type = 2;
+ int have_date = 0;
+ int have_time = 0;
+ int have_dialfreq = 0;
+ int halted = 0;
+ int wspr_type_value = 0;
+ size_t pcm_n = 0;
+
+ while (!halted) {
+ unsigned char type;
+ void *body = NULL;
+ uint32_t len = 0;
+ int rc = frame_read(stdin, &type, &body, &len);
+ if (rc < 0) {
+ free(pcm);
+ return 1;
+ }
+ if (rc > 0) break; // EOF without halt — treat as drain-and-decode
+
+ if (type == FRAME_CONTROL) {
+ char *json = malloc((size_t)len + 1);
+ if (!json) {
+ free(body);
+ free(pcm);
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate control JSON buffer");
+ return 1;
+ }
+ if (len != 0) {
+ memcpy(json, body, len);
+ }
+ json[len] = '\0';
+ free(body);
+
+ char event_type[16];
+ if (json_get_string(json, "t", event_type, sizeof event_type) != 0) {
+ free(json);
+ wsprd_stream_emit_error_code("control_parse_error",
+ "control frame is missing a string t field");
+ continue;
+ }
+ if (strcmp(event_type, "halt") == 0) {
+ halted = 1;
+ free(json);
+ continue;
+ }
+ if (strcmp(event_type, "configure") == 0) {
+ if (json_get_string(json, "date", cfg->date,
+ sizeof cfg->date) == 0) {
+ have_date = 1;
+ }
+ if (json_get_string(json, "time", cfg->uttime,
+ sizeof cfg->uttime) == 0) {
+ have_time = 1;
+ }
+ if (json_get_double(json, "dialfreq", &cfg->dialfreq) == 0) {
+ have_dialfreq = 1;
+ }
+ if (json_find_key(json, "wspr_type")) {
+ if (json_get_int(json, "wspr_type", &wspr_type_value) != 0 ||
+ (wspr_type_value != 2 && wspr_type_value != 15)) {
+ free(json);
+ free(pcm);
+ wsprd_stream_emit_error_code("invalid_wspr_type",
+ "wspr_type must be 2 or 15");
+ return 1;
+ }
+ cfg->wspr_type = wspr_type_value;
+ }
+ json_get_string(json, "mycall", cfg->mycall, sizeof cfg->mycall);
+ json_get_string(json, "mygrid", cfg->mygrid, sizeof cfg->mygrid);
+ cfg->configure_received = 1;
+ }
+ free(json);
+ continue;
+ }
+
+ if (type == FRAME_AUDIO) {
+ // body is raw int16 LE PCM. len must be even (whole samples).
+ if (len % sizeof(int16_t) != 0) {
+ free(body);
+ wsprd_stream_emit_error_code("odd_audio_frame",
+ "audio frame length must contain whole int16 samples");
+ free(pcm);
+ return 1;
+ }
+ size_t nsamples = len / sizeof(int16_t);
+ if (pcm_n + nsamples > MAX_PCM_SAMPLES) {
+ nsamples = MAX_PCM_SAMPLES - pcm_n;
+ }
+ if (nsamples != 0) {
+ memcpy(pcm + pcm_n, body, nsamples * sizeof(int16_t));
+ }
+ pcm_n += nsamples;
+ free(body);
+ continue;
+ }
+
+ // Unknown frame type — ignore (forward-compat).
+ free(body);
+ }
+
+ if (!cfg->configure_received) {
+ free(pcm);
+ wsprd_stream_emit_error_code("missing_configure",
+ "no configure frame received before halt or EOF");
+ return 1;
+ }
+ if (!have_date || !have_time || !have_dialfreq) {
+ free(pcm);
+ wsprd_stream_emit_error_code("incomplete_configure",
+ "configure frame missing date, time, or dialfreq");
+ return 1;
+ }
+
+ unsigned long npoints = pcm_to_iq(pcm, pcm_n, cfg->wspr_type, idat, qdat);
+ free(pcm);
+ return npoints;
+}
diff --git a/lib/wsprd/wsprd_stream.h b/lib/wsprd/wsprd_stream.h
new file mode 100644
index 00000000..0eed120e
--- /dev/null
+++ b/lib/wsprd/wsprd_stream.h
@@ -0,0 +1,33 @@
+/*
+ * wsprd streaming layer — public API consumed by wsprd.c.
+ * See wsprd_stream.c for protocol + scope notes.
+ */
+#ifndef WSPRD_STREAM_H
+#define WSPRD_STREAM_H
+
+struct wsprd_stream_config {
+ char date[7]; // YYMMDD\0
+ char uttime[5]; // HHMM\0
+ double dialfreq; // MHz
+ int wspr_type; // 2 or 15
+ char mycall[13]; // up to 12-char callsign + NUL
+ char mygrid[7]; // up to 6-char grid + NUL
+ int configure_received;
+};
+
+void wsprd_stream_emit_ready(void);
+void wsprd_stream_emit_decode(const char *date, const char *uttime,
+ float snr, float dt, double freq,
+ int drift, const char *message);
+void wsprd_stream_emit_decode_finished(const char *date, const char *uttime);
+void wsprd_stream_emit_error(const char *msg);
+void wsprd_stream_emit_error_code(const char *code, const char *detail);
+
+// Reads WSJT header + frames from stdin until halt or EOF. On success,
+// populates *cfg and the supplied I/Q buffers (idat/qdat must hold
+// at least 46080 floats each). Returns the number of complex samples
+// populated (nfft2 = 46080), or 1 on protocol error.
+unsigned long wsprd_stream_read(struct wsprd_stream_config *cfg,
+ float *idat, float *qdat);
+
+#endif
diff --git a/lib/wsprd/wsprd_utils.c b/lib/wsprd/wsprd_utils.c
index 64e809f8..bd17890d 100644
--- a/lib/wsprd/wsprd_utils.c
+++ b/lib/wsprd/wsprd_utils.c
@@ -27,11 +27,96 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "wsprd_utils.h"
+#include <errno.h>
+#include <stdarg.h>
#ifndef int32_t
#define int32_t int
#endif
+static int format_checked(char *dest, size_t dest_size, char const *format, ...)
+{
+ va_list args;
+ va_start(args, format);
+ int nwritten = vsnprintf(dest, dest_size, format, args);
+ va_end(args);
+ return nwritten >= 0 && (size_t)nwritten < dest_size;
+}
+
+static int read_bounded_token(char const **cursor, char *dest,
+ size_t dest_size, int required)
+{
+ char const *p = *cursor;
+ while( isspace((unsigned char)*p) ) p++;
+
+ if( *p == '\0' ) {
+ if( required ) return 0;
+ dest[0] = '\0';
+ *cursor = p;
+ return 1;
+ }
+
+ char const *start = p;
+ while( *p != '\0' && !isspace((unsigned char)*p) ) p++;
+
+ size_t len = (size_t)(p - start);
+ if( len >= dest_size ) return 0;
+
+ memcpy(dest, start, len);
+ dest[len] = '\0';
+ *cursor = p;
+ return 1;
+}
+
+static int store_hash_call(int ihash, char const *callsign, char *hashtab)
+{
+ if( ihash < 0 || ihash >= WSPRD_HASH_COUNT ) return 0;
+ if( strlen(callsign) >= WSPRD_CALLSIGN_SIZE ) return 0;
+ if( !format_checked(hashtab + ihash * WSPRD_CALLSIGN_SIZE,
+ WSPRD_CALLSIGN_SIZE, "%s", callsign) ) return 0;
+ return 1;
+}
+
+static int store_hash_grid(int ihash, char const *grid, char *loctab)
+{
+ if( ihash < 0 || ihash >= WSPRD_HASH_COUNT ) return 0;
+ if( strlen(grid) >= WSPRD_GRID4_SIZE ) return 0;
+ if( !format_checked(loctab + ihash * WSPRD_GRID4_SIZE,
+ WSPRD_GRID4_SIZE, "%s", grid) ) return 0;
+ return 1;
+}
+
+static int store_hash_entry(int ihash, char const *callsign, char const *grid,
+ char *hashtab, char *loctab)
+{
+ if( !store_hash_call(ihash, callsign, hashtab) ) return 0;
+ if( !store_hash_grid(ihash, grid, loctab) ) return 0;
+ return 1;
+}
+
+int wsprd_load_hash_line(char const *line, char *hashtab, char *loctab)
+{
+ char const *p = line;
+ errno = 0;
+ char *end = NULL;
+ long ihash = strtol(p, &end, 10);
+ if( p == end || errno == ERANGE ||
+ ihash < 0 || ihash >= WSPRD_HASH_COUNT ) return 0;
+ if( !isspace((unsigned char)*end) ) return 0;
+
+ char callsign[WSPRD_CALLSIGN_SIZE];
+ char grid[WSPRD_GRID4_SIZE];
+ p = end;
+ if( !read_bounded_token(&p, callsign, sizeof callsign, 1) ) return 0;
+ if( !read_bounded_token(&p, grid, sizeof grid, 0) ) return 0;
+
+ if( !store_hash_call((int)ihash, callsign, hashtab) ) return 0;
+ /* Legacy loader semantics: missing grid preserves the existing locator. */
+ if( grid[0] != '\0' &&
+ !store_hash_grid((int)ihash, grid, loctab) ) return 0;
+ return 1;
+}
+
void unpack50( signed char *dat, int32_t *n1, int32_t *n2 )
{
int32_t i,i4;
@@ -153,7 +238,7 @@ int unpackpfx( int32_t nprefix, char *call)
int i;
int32_t n;
- strcpy(tmpcall,call);
+ if( !format_checked(tmpcall, sizeof tmpcall, "%s", call) ) return 0;
if( nprefix < 60000 ) {
// add a prefix of 1 to 3 characters
n=nprefix;
@@ -172,31 +257,27 @@ int unpackpfx( int32_t nprefix, char *call)
}
char * p = strrchr(pfx,' ');
- strcpy(call, p ? p + 1 : pfx);
- strncat(call,"/",1);
- strncat(call,tmpcall,strlen(tmpcall));
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%s",
+ p ? p + 1 : pfx, tmpcall) ) return 0;
} else {
// add a suffix of 1 or 2 characters
nc=nprefix-60000;
if( (nc >= 0) & (nc <= 9) ) {
pfx[0]=nc+48;
- strcpy(call,tmpcall);
- strncat(call,"/",1);
- strncat(call,pfx,1);
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%.1s",
+ tmpcall, pfx) ) return 0;
}
else if( (nc >= 10) & (nc <= 35) ) {
pfx[0]=nc+55;
- strcpy(call,tmpcall);
- strncat(call,"/",1);
- strncat(call,pfx,1);
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%.1s",
+ tmpcall, pfx) ) return 0;
}
else if( (nc >= 36) & (nc <= 125) ) {
pfx[0]=(nc-26)/10+48;
pfx[1]=(nc-26)%10+48;
- strcpy(call,tmpcall);
- strncat(call,"/",1);
- strncat(call,pfx,2);
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%.2s",
+ tmpcall, pfx) ) return 0;
}
else {
return 0;
@@ -243,13 +324,13 @@ int floatcomp(const void* elem1, const void* elem2)
int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow, char *callsign)
{
int n1,n2,n3,ndbm,ihash,nadd,noprint=0;
- char grid[5],grid6[7],cdbm[4];
+ char grid[WSPRD_GRID4_SIZE],grid6[WSPRD_GRID6_SIZE];
unpack50(message,&n1,&n2);
if( !unpackcall(n1,callsign) ) return 1;
if( !unpackgrid(n2, grid) ) return 1;
int ntype = (n2&127) - 64;
- callsign[12]=0;
+ callsign[WSPRD_CALLSIGN_SIZE - 1]=0;
grid[4]=0;
/*
@@ -269,17 +350,10 @@ int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow,
int nu=ntype%10;
if( nu == 0 || nu == 3 || nu == 7 ) {
ndbm=ntype;
- memset(call_loc_pow,0,sizeof(char)*23);
- sprintf(cdbm,"%2d",ndbm);
- strncat(call_loc_pow,callsign,strlen(callsign));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,grid,4);
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,cdbm,2);
- strncat(call_loc_pow,"\0",1);
+ if( !format_checked(call_loc_pow, WSPRD_MESSAGE_SIZE, "%s %.4s %2d",
+ callsign, grid, ndbm) ) return 1;
ihash=nhash(callsign,strlen(callsign),(uint32_t)146);
- strcpy(hashtab+ihash*13,callsign);
- strcpy(loctab+ihash*5,grid);
+ if( !store_hash_entry(ihash, callsign, grid, hashtab, loctab) ) return 1;
} else {
nadd=nu;
if( nu > 3 ) nadd=nu-3;
@@ -287,25 +361,21 @@ int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow,
n3=n2/128+32768*(nadd-1);
if( !unpackpfx(n3,callsign) ) return 1;
ndbm=ntype-nadd;
- memset(call_loc_pow,0,sizeof(char)*23);
- sprintf(cdbm,"%2d",ndbm);
- strncat(call_loc_pow,callsign,strlen(callsign));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,cdbm,2);
- strncat(call_loc_pow,"\0",1);
+ if( !format_checked(call_loc_pow, WSPRD_MESSAGE_SIZE, "%s %2d",
+ callsign, ndbm) ) return 1;
int nu=ndbm%10;
if( nu == 0 || nu == 3 || nu == 7 || nu == 10 ) { //make sure power is OK
ihash=nhash(callsign,strlen(callsign),(uint32_t)146);
- strcpy(hashtab+ihash*13,callsign);
+ if( !store_hash_call(ihash, callsign, hashtab) ) return 1;
} else noprint=1;
}
} else if ( ntype < 0 ) {
ndbm=-(ntype+1);
- memset(grid6,0,sizeof(char)*7);
+ memset(grid6,0,sizeof grid6);
// size_t len=strlen(callsign);
size_t len=6;
- strncat(grid6,callsign+len-1,1);
- strncat(grid6,callsign,len-1);
+ if( !format_checked(grid6, sizeof grid6, "%.1s%.*s",
+ callsign+len-1, (int)(len-1), callsign) ) return 1;
int nu=ndbm%10;
if ((nu != 0 && nu != 3 && nu != 7 && nu != 10) ||
!isalpha(grid6[0]) || !isalpha(grid6[1]) ||
@@ -318,19 +388,15 @@ int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow,
ihash=(n2-ntype-64)/128;
if( strncmp(hashtab+ihash*13,"\0",1) != 0 ) {
- sprintf(callsign,"<%s>",hashtab+ihash*13);
+ if( !format_checked(callsign, WSPRD_CALLSIGN_SIZE, "<%s>",
+ hashtab+ihash*13) ) return 1;
} else {
- sprintf(callsign,"%5s","<...>");
+ if( !format_checked(callsign, WSPRD_CALLSIGN_SIZE, "%5s",
+ "<...>") ) return 1;
}
- memset(call_loc_pow,0,sizeof(char)*23);
- sprintf(cdbm,"%2d",ndbm);
- strncat(call_loc_pow,callsign,strlen(callsign));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,grid6,strlen(grid6));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,cdbm,2);
- strncat(call_loc_pow,"\0",1);
+ if( !format_checked(call_loc_pow, WSPRD_MESSAGE_SIZE, "%s %s %2d",
+ callsign, grid6, ndbm) ) return 1;
// I don't know what to do with these... They show up as "A000AA" grids.
diff --git a/lib/wsprd/wsprd_utils.h b/lib/wsprd/wsprd_utils.h
index db6ba946..62c653e8 100644
--- a/lib/wsprd/wsprd_utils.h
+++ b/lib/wsprd/wsprd_utils.h
@@ -10,6 +10,14 @@
#include <time.h>
#include "nhash.h"
+enum {
+ WSPRD_CALLSIGN_SIZE = 13,
+ WSPRD_GRID4_SIZE = 5,
+ WSPRD_GRID6_SIZE = 7,
+ WSPRD_MESSAGE_SIZE = 23,
+ WSPRD_HASH_COUNT = 32768
+};
+
void unpack50( signed char *dat, int32_t *n1, int32_t *n2 );
int unpackcall( int32_t ncall, char *call );
@@ -26,4 +34,6 @@ int floatcomp(const void* elem1, const void* elem2);
int unpk_( signed char *message, char* hashtab, char* loctab, char *call_loc_pow, char *callsign);
+int wsprd_load_hash_line(char const *line, char *hashtab, char *loctab);
+
#endif
diff --git a/lib/wsprd/wsprsimf.f90 b/lib/wsprd/wsprsimf.f90
index d6ee25d4..8fb2a0d7 100644
--- a/lib/wsprd/wsprsimf.f90
+++ b/lib/wsprd/wsprsimf.f90
@@ -89,7 +89,7 @@ program wsprsim
endif
write(fname14,1100) ifile
1100 format('000000_',i4.4,'.c2')
- open(10,file=fname14,status='unknown',access='stream')
+ open(10,file=fname14,status='replace',access='stream')
fMHz=10.1387d0
nmin=2
write(10) fname14,nmin,fMHz,c !Save to *.c2 file
@@ -102,7 +102,7 @@ program wsprsim
hwav=default_header(12000,NMAX)
write(fname15,1102) ifile
1102 format('000000_',i4.4,'.wav')
- open(10,file=fname15,status='unknown',access='stream')
+ open(10,file=fname15,status='replace',access='stream')
write(10) hwav,iwave !Save to *.wav file
close(10)
write(*,1110) ifile,xdt,f0,snrdb,fname15