1/*	$NetBSD: refclock_chu.c,v 1.10 2020/05/25 20:47:25 christos Exp $	*/
2
3/*
4 * refclock_chu - clock driver for Canadian CHU time/frequency station
5 */
6#ifdef HAVE_CONFIG_H
7#include <config.h>
8#endif
9
10#include "ntp_types.h"
11
12#if defined(REFCLOCK) && defined(CLOCK_CHU)
13
14#include "ntpd.h"
15#include "ntp_io.h"
16#include "ntp_refclock.h"
17#include "ntp_calendar.h"
18#include "ntp_stdlib.h"
19
20#include <stdio.h>
21#include <ctype.h>
22#include <math.h>
23
24#ifdef HAVE_AUDIO
25#include "audio.h"
26#endif /* HAVE_AUDIO */
27
28#define ICOM 	1		/* undefine to suppress ICOM code */
29
30#ifdef ICOM
31#include "icom.h"
32#endif /* ICOM */
33/*
34 * Audio CHU demodulator/decoder
35 *
36 * This driver synchronizes the computer time using data encoded in
37 * radio transmissions from Canadian time/frequency station CHU in
38 * Ottawa, Ontario. Transmissions are made continuously on 3330 kHz,
39 * 7850 kHz and 14670 kHz in upper sideband, compatible AM mode. An
40 * ordinary shortwave receiver can be tuned manually to one of these
41 * frequencies or, in the case of ICOM receivers, the receiver can be
42 * tuned automatically as propagation conditions change throughout the
43 * day and season.
44 *
45 * The driver requires an audio codec or sound card with sampling rate 8
46 * kHz and mu-law companding. This is the same standard as used by the
47 * telephone industry and is supported by most hardware and operating
48 * systems, including Solaris, SunOS, FreeBSD, NetBSD and Linux. In this
49 * implementation, only one audio driver and codec can be supported on a
50 * single machine.
51 *
52 * The driver can be compiled to use a Bell 103 compatible modem or
53 * modem chip to receive the radio signal and demodulate the data.
54 * Alternatively, the driver can be compiled to use the audio codec of
55 * the workstation or another with compatible audio drivers. In the
56 * latter case, the driver implements the modem using DSP routines, so
57 * the radio can be connected directly to either the microphone on line
58 * input port. In either case, the driver decodes the data using a
59 * maximum-likelihood technique which exploits the considerable degree
60 * of redundancy available to maximize accuracy and minimize errors.
61 *
62 * The CHU time broadcast includes an audio signal compatible with the
63 * Bell 103 modem standard (mark = 2225 Hz, space = 2025 Hz). The signal
64 * consists of nine, ten-character bursts transmitted at 300 bps between
65 * seconds 31 and 39 of each minute. Each character consists of eight
66 * data bits plus one start bit and two stop bits to encode two hex
67 * digits. The burst data consist of five characters (ten hex digits)
68 * followed by a repeat of these characters. In format A, the characters
69 * are repeated in the same polarity; in format B, the characters are
70 * repeated in the opposite polarity.
71 *
72 * Format A bursts are sent at seconds 32 through 39 of the minute in
73 * hex digits (nibble swapped)
74 *
75 *	6dddhhmmss6dddhhmmss
76 *
77 * The first ten digits encode a frame marker (6) followed by the day
78 * (ddd), hour (hh in UTC), minute (mm) and the second (ss). Since
79 * format A bursts are sent during the third decade of seconds the tens
80 * digit of ss is always 3. The driver uses this to determine correct
81 * burst synchronization. These digits are then repeated with the same
82 * polarity.
83 *
84 * Format B bursts are sent at second 31 of the minute in hex digits
85 *
86 *	xdyyyyttaaxdyyyyttaa
87 *
88 * The first ten digits encode a code (x described below) followed by
89 * the DUT1 (d in deciseconds), Gregorian year (yyyy), difference TAI -
90 * UTC (tt) and daylight time indicator (aa) peculiar to Canada. These
91 * digits are then repeated with inverted polarity.
92 *
93 * The x is coded
94 *
95 * 1 Sign of DUT (0 = +)
96 * 2 Leap second warning. One second will be added.
97 * 4 Leap second warning. One second will be subtracted.
98 * 8 Even parity bit for this nibble.
99 *
100 * By design, the last stop bit of the last character in the burst
101 * coincides with 0.5 second. Since characters have 11 bits and are
102 * transmitted at 300 bps, the last stop bit of the first character
103 * coincides with 0.5 - 9 * 11/300 = 0.170 second. Depending on the
104 * UART, character interrupts can vary somewhere between the end of bit
105 * 9 and end of bit 11. These eccentricities can be corrected along with
106 * the radio propagation delay using fudge time 1.
107 *
108 * Debugging aids
109 *
110 * The timecode format used for debugging and data recording includes
111 * data helpful in diagnosing problems with the radio signal and serial
112 * connections. With debugging enabled (-d on the ntpd command line),
113 * the driver produces one line for each burst in two formats
114 * corresponding to format A and B.Each line begins with the format code
115 * chuA or chuB followed by the status code and signal level (0-9999).
116 * The remainder of the line is as follows.
117 *
118 * Following is format A:
119 *
120 *	n b f s m code
121 *
122 * where n is the number of characters in the burst (0-10), b the burst
123 * distance (0-40), f the field alignment (-1, 0, 1), s the
124 * synchronization distance (0-16), m the burst number (2-9) and code
125 * the burst characters as received. Note that the hex digits in each
126 * character are reversed, so the burst
127 *
128 *	10 38 0 16 9 06851292930685129293
129 *
130 * is interpreted as containing 10 characters with burst distance 38,
131 * field alignment 0, synchronization distance 16 and burst number 9.
132 * The nibble-swapped timecode shows day 58, hour 21, minute 29 and
133 * second 39.
134 *
135 * Following is format B:
136 *
137 *	n b s code
138 *
139 * where n is the number of characters in the burst (0-10), b the burst
140 * distance (0-40), s the synchronization distance (0-40) and code the
141 * burst characters as received. Note that the hex digits in each
142 * character are reversed and the last ten digits inverted, so the burst
143 *
144 *	10 40 1091891300ef6e76ec
145 *
146 * is interpreted as containing 10 characters with burst distance 40.
147 * The nibble-swapped timecode shows DUT1 +0.1 second, year 1998 and TAI
148 * - UTC 31 seconds.
149 *
150 * Each line is preceeded by the code chuA or chuB, as appropriate. If
151 * the audio driver is compiled, the current gain (0-255) and relative
152 * signal level (0-9999) follow the code. The receiver volume control
153 * should be set so that the gain is somewhere near the middle of the
154 * range 0-255, which results in a signal level near 1000.
155 *
156 * In addition to the above, the reference timecode is updated and
157 * written to the clockstats file and debug score after the last burst
158 * received in the minute. The format is
159 *
160 *	sq yyyy ddd hh:mm:ss l s dd t agc ident m b
161 *
162 * s	'?' before first synchronized and ' ' after that
163 * q	status code (see below)
164 * yyyy	year
165 * ddd	day of year
166 * hh:mm:ss time of day
167 * l	leap second indicator (space, L or D)
168 * dst	Canadian daylight code (opaque)
169 * t	number of minutes since last synchronized
170 * agc	audio gain (0 - 255)
171 * ident identifier (CHU0 3330 kHz, CHU1 7850 kHz, CHU2 14670 kHz)
172 * m	signal metric (0 - 100)
173 * b	number of timecodes for the previous minute (0 - 59)
174 *
175 * Fudge factors
176 *
177 * For accuracies better than the low millisceconds, fudge time1 can be
178 * set to the radio propagation delay from CHU to the receiver. This can
179 * be done conviently using the minimuf program.
180 *
181 * Fudge flag4 causes the dubugging output described above to be
182 * recorded in the clockstats file. When the audio driver is compiled,
183 * fudge flag2 selects the audio input port, where 0 is the mike port
184 * (default) and 1 is the line-in port. It does not seem useful to
185 * select the compact disc player port. Fudge flag3 enables audio
186 * monitoring of the input signal. For this purpose, the monitor gain is
187 * set to a default value.
188 *
189 * The audio codec code is normally compiled in the driver if the
190 * architecture supports it (HAVE_AUDIO defined), but is used only if
191 * the link /dev/chu_audio is defined and valid. The serial port code is
192 * always compiled in the driver, but is used only if the autdio codec
193 * is not available and the link /dev/chu%d is defined and valid.
194 *
195 * The ICOM code is normally compiled in the driver if selected (ICOM
196 * defined), but is used only if the link /dev/icom%d is defined and
197 * valid and the mode keyword on the server configuration command
198 * specifies a nonzero mode (ICOM ID select code). The C-IV speed is
199 * 9600 bps if the high order 0x80 bit of the mode is zero and 1200 bps
200 * if one. The C-IV trace is turned on if the debug level is greater
201 * than one.
202 *
203 * Alarm codes
204 *
205 * CEVNT_BADTIME	invalid date or time
206 * CEVNT_PROP		propagation failure - no stations heard
207 */
208/*
209 * Interface definitions
210 */
211#define	SPEED232	B300	/* uart speed (300 baud) */
212#define	PRECISION	(-10)	/* precision assumed (about 1 ms) */
213#define	REFID		"CHU"	/* reference ID */
214#define	DEVICE		"/dev/chu%d" /* device name and unit */
215#define	SPEED232	B300	/* UART speed (300 baud) */
216#ifdef ICOM
217#define TUNE		.001	/* offset for narrow filter (MHz) */
218#define DWELL		5	/* minutes in a dwell */
219#define NCHAN		3	/* number of channels */
220#define ISTAGE		3	/* number of integrator stages */
221#endif /* ICOM */
222
223#ifdef HAVE_AUDIO
224/*
225 * Audio demodulator definitions
226 */
227#define SECOND		8000	/* nominal sample rate (Hz) */
228#define BAUD		300	/* modulation rate (bps) */
229#define OFFSET		128	/* companded sample offset */
230#define SIZE		256	/* decompanding table size */
231#define	MAXAMP		6000.	/* maximum signal level */
232#define	MAXCLP		100	/* max clips above reference per s */
233#define	SPAN		800.	/* min envelope span */
234#define LIMIT		1000.	/* soft limiter threshold */
235#define AGAIN		6.	/* baseband gain */
236#define LAG		10	/* discriminator lag */
237#define	DEVICE_AUDIO	"/dev/audio" /* device name */
238#define	DESCRIPTION	"CHU Audio/Modem Receiver" /* WRU */
239#define	AUDIO_BUFSIZ	240	/* audio buffer size (30 ms) */
240#else
241#define	DESCRIPTION	"CHU Modem Receiver" /* WRU */
242#endif /* HAVE_AUDIO */
243
244/*
245 * Decoder definitions
246 */
247#define CHAR		(11. / 300.) /* character time (s) */
248#define BURST		11	/* max characters per burst */
249#define MINCHARS		9	/* min characters per burst */
250#define MINDIST		28	/* min burst distance (of 40)  */
251#define MINSYNC		8	/* min sync distance (of 16) */
252#define MINSTAMP	20	/* min timestamps (of 60) */
253#define MINMETRIC	50	/* min channel metric (of 160) */
254
255/*
256 * The on-time synchronization point for the driver is the last stop bit
257 * of the first character 170 ms. The modem delay is 0.8 ms, while the
258 * receiver delay is approxmately 4.7 ms at 2125 Hz. The fudge value 1.3
259 * ms due to the codec and other causes was determined by calibrating to
260 * a PPS signal from a GPS receiver. The additional propagation delay
261 * specific to each receiver location can be programmed in the fudge
262 * time1.
263 *
264 * The resulting offsets with a 2.4-GHz P4 running FreeBSD 6.1 are
265 * generally within 0.5 ms short term with 0.3 ms jitter. The long-term
266 * offsets vary up to 0.3 ms due to ionospheric layer height variations.
267 * The processor load due to the driver is 0.4 percent.
268 */
269#define	PDELAY	((170 + .8 + 4.7 + 1.3) / 1000)	/* system delay (s) */
270
271/*
272 * Status bits (status)
273 */
274#define RUNT		0x0001	/* runt burst */
275#define NOISE		0x0002	/* noise burst */
276#define BFRAME		0x0004	/* invalid format B frame sync */
277#define BFORMAT		0x0008	/* invalid format B data */
278#define AFRAME		0x0010	/* invalid format A frame sync */
279#define AFORMAT		0x0020	/* invalid format A data */
280#define DECODE		0x0040	/* invalid data decode */
281#define STAMP		0x0080	/* too few timestamps */
282#define AVALID		0x0100	/* valid A frame */
283#define BVALID		0x0200	/* valid B frame */
284#define INSYNC		0x0400	/* clock synchronized */
285#define	METRIC		0x0800	/* one or more stations heard */
286
287/*
288 * Alarm status bits (alarm)
289 *
290 * These alarms are set at the end of a minute in which at least one
291 * burst was received. SYNERR is raised if the AFRAME or BFRAME status
292 * bits are set during the minute, FMTERR is raised if the AFORMAT or
293 * BFORMAT status bits are set, DECERR is raised if the DECODE status
294 * bit is set and TSPERR is raised if the STAMP status bit is set.
295 */
296#define SYNERR		0x01	/* frame sync error */
297#define FMTERR		0x02	/* data format error */
298#define DECERR		0x04	/* data decoding error */
299#define TSPERR		0x08	/* insufficient data */
300
301#ifdef HAVE_AUDIO
302/*
303 * Maximum-likelihood UART structure. There are eight of these
304 * corresponding to the number of phases.
305 */
306struct surv {
307	l_fp	cstamp;		/* last bit timestamp */
308	double	shift[12];	/* sample shift register */
309	double	span;		/* shift register envelope span */
310	double	dist;		/* sample distance */
311	int	uart;		/* decoded character */
312};
313#endif /* HAVE_AUDIO */
314
315#ifdef ICOM
316/*
317 * CHU station structure. There are three of these corresponding to the
318 * three frequencies.
319 */
320struct xmtr {
321	double	integ[ISTAGE];	/* circular integrator */
322	double	metric;		/* integrator sum */
323	int	iptr;		/* integrator pointer */
324	int	probe;		/* dwells since last probe */
325};
326#endif /* ICOM */
327
328/*
329 * CHU unit control structure
330 */
331struct chuunit {
332	u_char	decode[20][16];	/* maximum-likelihood decoding matrix */
333	l_fp	cstamp[BURST];	/* character timestamps */
334	l_fp	tstamp[MAXSTAGE]; /* timestamp samples */
335	l_fp	timestamp;	/* current buffer timestamp */
336	l_fp	laststamp;	/* last buffer timestamp */
337	l_fp	charstamp;	/* character time as a l_fp */
338	int	second;		/* counts the seconds of the minute */
339	int	errflg;		/* error flags */
340	int	status;		/* status bits */
341	char	ident[5];	/* station ID and channel */
342#ifdef ICOM
343	int	fd_icom;	/* ICOM file descriptor */
344	int	chan;		/* radio channel */
345	int	dwell;		/* dwell cycle */
346	struct xmtr xmtr[NCHAN]; /* station metric */
347#endif /* ICOM */
348
349	/*
350	 * Character burst variables
351	 */
352	int	cbuf[BURST];	/* character buffer */
353	int	ntstamp;	/* number of timestamp samples */
354	int	ndx;		/* buffer start index */
355	int	prevsec;	/* previous burst second */
356	int	burdist;	/* burst distance */
357	int	syndist;	/* sync distance */
358	int	burstcnt;	/* format A bursts this minute */
359	double	maxsignal;	/* signal level (modem only) */
360	int	gain;		/* codec gain (modem only) */
361
362	/*
363	 * Format particulars
364	 */
365	int	leap;		/* leap/dut code */
366	int	dut;		/* UTC1 correction */
367	int	tai;		/* TAI - UTC correction */
368	int	dst;		/* Canadian DST code */
369
370#ifdef HAVE_AUDIO
371	/*
372	 * Audio codec variables
373	 */
374	int	fd_audio;	/* audio port file descriptor */
375	double	comp[SIZE];	/* decompanding table */
376	int	port;		/* codec port */
377	int	mongain;	/* codec monitor gain */
378	int	clipcnt;	/* sample clip count */
379	int	seccnt;		/* second interval counter */
380
381	/*
382	 * Modem variables
383	 */
384	l_fp	tick;		/* audio sample increment */
385	double	bpf[9];		/* IIR bandpass filter */
386	double	disc[LAG];	/* discriminator shift register */
387	double	lpf[27];	/* FIR lowpass filter */
388	double	monitor;	/* audio monitor */
389	int	discptr;	/* discriminator pointer */
390
391	/*
392	 * Maximum-likelihood UART variables
393	 */
394	double	baud;		/* baud interval */
395	struct surv surv[8];	/* UART survivor structures */
396	int	decptr;		/* decode pointer */
397	int	decpha;		/* decode phase */
398	int	dbrk;		/* holdoff counter */
399#endif /* HAVE_AUDIO */
400};
401
402/*
403 * Function prototypes
404 */
405static	int	chu_start	(int, struct peer *);
406static	void	chu_shutdown	(int, struct peer *);
407static	void	chu_receive	(struct recvbuf *);
408static	void	chu_second	(int, struct peer *);
409static	void	chu_poll	(int, struct peer *);
410
411/*
412 * More function prototypes
413 */
414static	void	chu_decode	(struct peer *, int, l_fp);
415static	void	chu_burst	(struct peer *);
416static	void	chu_clear	(struct peer *);
417static	void	chu_a		(struct peer *, int);
418static	void	chu_b		(struct peer *, int);
419static	int	chu_dist	(int, int);
420static	double	chu_major	(struct peer *);
421#ifdef HAVE_AUDIO
422static	void	chu_uart	(struct surv *, double);
423static	void	chu_rf		(struct peer *, double);
424static	void	chu_gain	(struct peer *);
425static	void	chu_audio_receive (struct recvbuf *rbufp);
426#endif /* HAVE_AUDIO */
427#ifdef ICOM
428static	int	chu_newchan	(struct peer *, double);
429#endif /* ICOM */
430static	void	chu_serial_receive (struct recvbuf *rbufp);
431
432/*
433 * Global variables
434 */
435static char hexchar[] = "0123456789abcdef_*=";
436
437#ifdef ICOM
438/*
439 * Note the tuned frequencies are 1 kHz higher than the carrier. CHU
440 * transmits on USB with carrier so we can use AM and the narrow SSB
441 * filter.
442 */
443static double qsy[NCHAN] = {3.330, 7.850, 14.670}; /* freq (MHz) */
444#endif /* ICOM */
445
446/*
447 * Transfer vector
448 */
449struct	refclock refclock_chu = {
450	chu_start,		/* start up driver */
451	chu_shutdown,		/* shut down driver */
452	chu_poll,		/* transmit poll message */
453	noentry,		/* not used (old chu_control) */
454	noentry,		/* initialize driver (not used) */
455	noentry,		/* not used (old chu_buginfo) */
456	chu_second		/* housekeeping timer */
457};
458
459
460/*
461 * chu_start - open the devices and initialize data for processing
462 */
463static int
464chu_start(
465	int	unit,		/* instance number (not used) */
466	struct peer *peer	/* peer structure pointer */
467	)
468{
469	struct chuunit *up;
470	struct refclockproc *pp;
471	char device[20];	/* device name */
472	int	fd;		/* file descriptor */
473#ifdef ICOM
474	int	temp;
475#endif /* ICOM */
476#ifdef HAVE_AUDIO
477	int	fd_audio;	/* audio port file descriptor */
478	int	i;		/* index */
479	double	step;		/* codec adjustment */
480
481	/*
482	 * Open audio device. Don't complain if not there.
483	 */
484	fd_audio = audio_init(DEVICE_AUDIO, AUDIO_BUFSIZ, unit);
485
486#ifdef DEBUG
487	if (fd_audio >= 0 && debug)
488		audio_show();
489#endif
490
491	/*
492	 * If audio is unavailable, Open serial port in raw mode.
493	 */
494	if (fd_audio >= 0) {
495		fd = fd_audio;
496	} else {
497		snprintf(device, sizeof(device), DEVICE, unit);
498		fd = refclock_open(device, SPEED232, LDISC_RAW);
499	}
500#else /* HAVE_AUDIO */
501
502	/*
503	 * Open serial port in raw mode.
504	 */
505	snprintf(device, sizeof(device), DEVICE, unit);
506	fd = refclock_open(device, SPEED232, LDISC_RAW);
507#endif /* HAVE_AUDIO */
508
509	if (fd < 0)
510		return (0);
511
512	/*
513	 * Allocate and initialize unit structure
514	 */
515	up = emalloc_zero(sizeof(*up));
516	pp = peer->procptr;
517	pp->unitptr = up;
518	pp->io.clock_recv = chu_receive;
519	pp->io.srcclock = peer;
520	pp->io.datalen = 0;
521	pp->io.fd = fd;
522	if (!io_addclock(&pp->io)) {
523		close(fd);
524		pp->io.fd = -1;
525		free(up);
526		pp->unitptr = NULL;
527		return (0);
528	}
529
530	/*
531	 * Initialize miscellaneous variables
532	 */
533	peer->precision = PRECISION;
534	pp->clockdesc = DESCRIPTION;
535	strlcpy(up->ident, "CHU", sizeof(up->ident));
536	memcpy(&pp->refid, up->ident, 4);
537	DTOLFP(CHAR, &up->charstamp);
538#ifdef HAVE_AUDIO
539
540	/*
541	 * The companded samples are encoded sign-magnitude. The table
542	 * contains all the 256 values in the interest of speed. We do
543	 * this even if the audio codec is not available. C'est la lazy.
544	 */
545	up->fd_audio = fd_audio;
546	up->gain = 127;
547	up->comp[0] = up->comp[OFFSET] = 0.;
548	up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
549	up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
550	step = 2.;
551	for (i = 3; i < OFFSET; i++) {
552		up->comp[i] = up->comp[i - 1] + step;
553		up->comp[OFFSET + i] = -up->comp[i];
554                if (i % 16 == 0)
555                	step *= 2.;
556	}
557	DTOLFP(1. / SECOND, &up->tick);
558#endif /* HAVE_AUDIO */
559#ifdef ICOM
560	temp = 0;
561#ifdef DEBUG
562	if (debug > 1)
563		temp = P_TRACE;
564#endif
565	if (peer->ttl > 0) {
566		if (peer->ttl & 0x80)
567			up->fd_icom = icom_init("/dev/icom", B1200,
568			    temp);
569		else
570			up->fd_icom = icom_init("/dev/icom", B9600,
571			    temp);
572	}
573	if (up->fd_icom > 0) {
574		if (chu_newchan(peer, 0) != 0) {
575			msyslog(LOG_NOTICE, "icom: radio not found");
576			close(up->fd_icom);
577			up->fd_icom = 0;
578		} else {
579			msyslog(LOG_NOTICE, "icom: autotune enabled");
580		}
581	}
582#endif /* ICOM */
583	return (1);
584}
585
586
587/*
588 * chu_shutdown - shut down the clock
589 */
590static void
591chu_shutdown(
592	int	unit,		/* instance number (not used) */
593	struct peer *peer	/* peer structure pointer */
594	)
595{
596	struct chuunit *up;
597	struct refclockproc *pp;
598
599	pp = peer->procptr;
600	up = pp->unitptr;
601	if (up == NULL)
602		return;
603
604	io_closeclock(&pp->io);
605#ifdef ICOM
606	if (up->fd_icom > 0)
607		close(up->fd_icom);
608#endif /* ICOM */
609	free(up);
610}
611
612
613/*
614 * chu_receive - receive data from the audio or serial device
615 */
616static void
617chu_receive(
618	struct recvbuf *rbufp	/* receive buffer structure pointer */
619	)
620{
621#ifdef HAVE_AUDIO
622	struct chuunit *up;
623	struct refclockproc *pp;
624	struct peer *peer;
625
626	peer = rbufp->recv_peer;
627	pp = peer->procptr;
628	up = pp->unitptr;
629
630	/*
631	 * If the audio codec is warmed up, the buffer contains codec
632	 * samples which need to be demodulated and decoded into CHU
633	 * characters using the software UART. Otherwise, the buffer
634	 * contains CHU characters from the serial port, so the software
635	 * UART is bypassed. In this case the CPU will probably run a
636	 * few degrees cooler.
637	 */
638	if (up->fd_audio > 0)
639		chu_audio_receive(rbufp);
640	else
641		chu_serial_receive(rbufp);
642#else
643	chu_serial_receive(rbufp);
644#endif /* HAVE_AUDIO */
645}
646
647
648#ifdef HAVE_AUDIO
649/*
650 * chu_audio_receive - receive data from the audio device
651 */
652static void
653chu_audio_receive(
654	struct recvbuf *rbufp	/* receive buffer structure pointer */
655	)
656{
657	struct chuunit *up;
658	struct refclockproc *pp;
659	struct peer *peer;
660
661	double	sample;		/* codec sample */
662	u_char	*dpt;		/* buffer pointer */
663	int	bufcnt;		/* buffer counter */
664	l_fp	ltemp;		/* l_fp temp */
665
666	peer = rbufp->recv_peer;
667	pp = peer->procptr;
668	up = pp->unitptr;
669
670	/*
671	 * Main loop - read until there ain't no more. Note codec
672	 * samples are bit-inverted.
673	 */
674	DTOLFP((double)rbufp->recv_length / SECOND, &ltemp);
675	L_SUB(&rbufp->recv_time, &ltemp);
676	up->timestamp = rbufp->recv_time;
677	dpt = rbufp->recv_buffer;
678	for (bufcnt = 0; bufcnt < rbufp->recv_length; bufcnt++) {
679		sample = up->comp[~*dpt++ & 0xff];
680
681		/*
682		 * Clip noise spikes greater than MAXAMP. If no clips,
683		 * increase the gain a tad; if the clips are too high,
684		 * decrease a tad.
685		 */
686		if (sample > MAXAMP) {
687			sample = MAXAMP;
688			up->clipcnt++;
689		} else if (sample < -MAXAMP) {
690			sample = -MAXAMP;
691			up->clipcnt++;
692		}
693		chu_rf(peer, sample);
694		L_ADD(&up->timestamp, &up->tick);
695
696		/*
697		 * Once each second ride gain.
698		 */
699		up->seccnt = (up->seccnt + 1) % SECOND;
700		if (up->seccnt == 0) {
701			chu_gain(peer);
702		}
703	}
704
705	/*
706	 * Set the input port and monitor gain for the next buffer.
707	 */
708	if (pp->sloppyclockflag & CLK_FLAG2)
709		up->port = 2;
710	else
711		up->port = 1;
712	if (pp->sloppyclockflag & CLK_FLAG3)
713		up->mongain = MONGAIN;
714	else
715		up->mongain = 0;
716}
717
718
719/*
720 * chu_rf - filter and demodulate the FSK signal
721 *
722 * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz
723 * and space 2025 Hz. It uses a bandpass filter followed by a soft
724 * limiter, FM discriminator and lowpass filter. A maximum-likelihood
725 * decoder samples the baseband signal at eight times the baud rate and
726 * detects the start bit of each character.
727 *
728 * The filters are built for speed, which explains the rather clumsy
729 * code. Hopefully, the compiler will efficiently implement the move-
730 * and-muiltiply-and-add operations.
731 */
732static void
733chu_rf(
734	struct peer *peer,	/* peer structure pointer */
735	double	sample		/* analog sample */
736	)
737{
738	struct refclockproc *pp;
739	struct chuunit *up;
740	struct surv *sp;
741
742	/*
743	 * Local variables
744	 */
745	double	signal;		/* bandpass signal */
746	double	limit;		/* limiter signal */
747	double	disc;		/* discriminator signal */
748	double	lpf;		/* lowpass signal */
749	double	dist;		/* UART signal distance */
750	int	i, j;
751
752	pp = peer->procptr;
753	up = pp->unitptr;
754
755	/*
756	 * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered
757	 * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB,
758	 * phase delay 0.24 ms.
759	 */
760	signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01;
761	signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01;
762	signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00;
763	signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00;
764	signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00;
765	signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00;
766	signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00;
767	signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01;
768	up->bpf[0] = sample - signal;
769	signal = up->bpf[0] * 6.176213e-03
770	    + up->bpf[1] * 3.156599e-03
771	    + up->bpf[2] * 7.567487e-03
772	    + up->bpf[3] * 4.344580e-03
773	    + up->bpf[4] * 1.190128e-02
774	    + up->bpf[5] * 4.344580e-03
775	    + up->bpf[6] * 7.567487e-03
776	    + up->bpf[7] * 3.156599e-03
777	    + up->bpf[8] * 6.176213e-03;
778
779	up->monitor = signal / 4.;	/* note monitor after filter */
780
781	/*
782	 * Soft limiter/discriminator. The 11-sample discriminator lag
783	 * interval corresponds to three cycles of 2125 Hz, which
784	 * requires the sample frequency to be 2125 * 11 / 3 = 7791.7
785	 * Hz. The discriminator output varies +-0.5 interval for input
786	 * frequency 2025-2225 Hz. However, we don't get to sample at
787	 * this frequency, so the discriminator output is biased. Life
788	 * at 8000 Hz sucks.
789	 */
790	limit = signal;
791	if (limit > LIMIT)
792		limit = LIMIT;
793	else if (limit < -LIMIT)
794		limit = -LIMIT;
795	disc = up->disc[up->discptr] * -limit;
796	up->disc[up->discptr] = limit;
797	up->discptr = (up->discptr + 1 ) % LAG;
798	if (disc >= 0)
799		disc = SQRT(disc);
800	else
801		disc = -SQRT(-disc);
802
803	/*
804	 * Lowpass filter. Raised cosine FIR, Ts = 1 / 300, beta = 0.1.
805	 */
806	lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02;
807	lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01;
808	lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01;
809	lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01;
810	lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01;
811	lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01;
812	lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01;
813	lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01;
814	lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01;
815	lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01;
816	lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01;
817	lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01;
818	lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01;
819	lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00;
820	lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01;
821	lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01;
822	lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01;
823	lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01;
824	lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01;
825	lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01;
826	lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01;
827	lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01;
828	lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01;
829	lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01;
830	lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01;
831	lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01;
832	lpf += up->lpf[0] = disc * 2.538771e-02;
833
834	/*
835	 * Maximum-likelihood decoder. The UART updates each of the
836	 * eight survivors and determines the span, slice level and
837	 * tentative decoded character. Valid 11-bit characters are
838	 * framed so that bit 10 and bit 11 (stop bits) are mark and bit
839	 * 1 (start bit) is space. When a valid character is found, the
840	 * survivor with maximum distance determines the final decoded
841	 * character.
842	 */
843	up->baud += 1. / SECOND;
844	if (up->baud > 1. / (BAUD * 8.)) {
845		up->baud -= 1. / (BAUD * 8.);
846		up->decptr = (up->decptr + 1) % 8;
847		sp = &up->surv[up->decptr];
848		sp->cstamp = up->timestamp;
849		chu_uart(sp, -lpf * AGAIN);
850		if (up->dbrk > 0) {
851			up->dbrk--;
852			if (up->dbrk > 0)
853				return;
854
855			up->decpha = up->decptr;
856		}
857		if (up->decptr != up->decpha)
858			return;
859
860		dist = 0;
861		j = -1;
862		for (i = 0; i < 8; i++) {
863
864			/*
865			 * The timestamp is taken at the last bit, so
866			 * for correct decoding we reqire sufficient
867			 * span and correct start bit and two stop bits.
868			 */
869			if ((up->surv[i].uart & 0x601) != 0x600 ||
870			    up->surv[i].span < SPAN)
871				continue;
872
873			if (up->surv[i].dist > dist) {
874				dist = up->surv[i].dist;
875				j = i;
876			}
877		}
878		if (j < 0)
879			return;
880
881		/*
882		 * Process the character, then blank the decoder until
883		 * the end of the next character.This sets the decoding
884		 * phase of the entire burst from the phase of the first
885		 * character.
886		 */
887		up->maxsignal = up->surv[j].span;
888		chu_decode(peer, (up->surv[j].uart >> 1) & 0xff,
889		    up->surv[j].cstamp);
890		up->dbrk = 88;
891	}
892}
893
894
895/*
896 * chu_uart - maximum-likelihood UART
897 *
898 * This routine updates a shift register holding the last 11 envelope
899 * samples. It then computes the slice level and span over these samples
900 * and determines the tentative data bits and distance. The calling
901 * program selects over the last eight survivors the one with maximum
902 * distance to determine the decoded character.
903 */
904static void
905chu_uart(
906	struct surv *sp,	/* survivor structure pointer */
907	double	sample		/* baseband signal */
908	)
909{
910	double	es_max, es_min;	/* max/min envelope */
911	double	slice;		/* slice level */
912	double	dist;		/* distance */
913	double	dtemp;
914	int	i;
915
916	/*
917	 * Save the sample and shift right. At the same time, measure
918	 * the maximum and minimum over all eleven samples.
919	 */
920	es_max = -1e6;
921	es_min = 1e6;
922	sp->shift[0] = sample;
923	for (i = 11; i > 0; i--) {
924		sp->shift[i] = sp->shift[i - 1];
925		if (sp->shift[i] > es_max)
926			es_max = sp->shift[i];
927		if (sp->shift[i] < es_min)
928			es_min = sp->shift[i];
929	}
930
931	/*
932	 * Determine the span as the maximum less the minimum and the
933	 * slice level as the minimum plus a fraction of the span. Note
934	 * the slight bias toward mark to correct for the modem tendency
935	 * to make more mark than space errors. Compute the distance on
936	 * the assumption the last two bits must be mark, the first
937	 * space and the rest either mark or space.
938	 */
939	sp->span = es_max - es_min;
940	slice = es_min + .45 * sp->span;
941	dist = 0;
942	sp->uart = 0;
943	for (i = 1; i < 12; i++) {
944		sp->uart <<= 1;
945		dtemp = sp->shift[i];
946		if (dtemp > slice)
947			sp->uart |= 0x1;
948		if (i == 1 || i == 2) {
949			dist += dtemp - es_min;
950		} else if (i == 11) {
951			dist += es_max - dtemp;
952		} else {
953			if (dtemp > slice)
954				dist += dtemp - es_min;
955			else
956				dist += es_max - dtemp;
957		}
958	}
959	sp->dist = dist / (11 * sp->span);
960}
961#endif /* HAVE_AUDIO */
962
963
964/*
965 * chu_serial_receive - receive data from the serial device
966 */
967static void
968chu_serial_receive(
969	struct recvbuf *rbufp	/* receive buffer structure pointer */
970	)
971{
972	struct peer *peer;
973
974	u_char	*dpt;		/* receive buffer pointer */
975
976	peer = rbufp->recv_peer;
977
978	dpt = (u_char *)&rbufp->recv_space;
979	chu_decode(peer, *dpt, rbufp->recv_time);
980}
981
982
983/*
984 * chu_decode - decode the character data
985 */
986static void
987chu_decode(
988	struct peer *peer,	/* peer structure pointer */
989	int	hexhex,		/* data character */
990	l_fp	cstamp		/* data character timestamp */
991	)
992{
993	struct refclockproc *pp;
994	struct chuunit *up;
995
996	l_fp	tstmp;		/* timestamp temp */
997	double	dtemp;
998
999	pp = peer->procptr;
1000	up = pp->unitptr;
1001
1002	/*
1003	 * If the interval since the last character is greater than the
1004	 * longest burst, process the last burst and start a new one. If
1005	 * the interval is less than this but greater than two
1006	 * characters, consider this a noise burst and reject it.
1007	 */
1008	tstmp = up->timestamp;
1009	if (L_ISZERO(&up->laststamp))
1010		up->laststamp = up->timestamp;
1011	L_SUB(&tstmp, &up->laststamp);
1012	up->laststamp = up->timestamp;
1013	LFPTOD(&tstmp, dtemp);
1014	if (dtemp > BURST * CHAR) {
1015		chu_burst(peer);
1016		up->ndx = 0;
1017	} else if (dtemp > 2.5 * CHAR) {
1018		up->ndx = 0;
1019	}
1020
1021	/*
1022	 * Append the character to the current burst and append the
1023	 * character timestamp to the timestamp list.
1024	 */
1025	if (up->ndx < BURST) {
1026		up->cbuf[up->ndx] = hexhex & 0xff;
1027		up->cstamp[up->ndx] = cstamp;
1028		up->ndx++;
1029
1030	}
1031}
1032
1033
1034/*
1035 * chu_burst - search for valid burst format
1036 */
1037static void
1038chu_burst(
1039	struct peer *peer
1040	)
1041{
1042	struct chuunit *up;
1043	struct refclockproc *pp;
1044
1045	int	i;
1046
1047	pp = peer->procptr;
1048	up = pp->unitptr;
1049
1050	/*
1051	 * Correlate a block of five characters with the next block of
1052	 * five characters. The burst distance is defined as the number
1053	 * of bits that match in the two blocks for format A and that
1054	 * match the inverse for format B.
1055	 */
1056	if (up->ndx < MINCHARS) {
1057		up->status |= RUNT;
1058		return;
1059	}
1060	up->burdist = 0;
1061	for (i = 0; i < 5 && i < up->ndx - 5; i++)
1062		up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]);
1063
1064	/*
1065	 * If the burst distance is at least MINDIST, this must be a
1066	 * format A burst; if the value is not greater than -MINDIST, it
1067	 * must be a format B burst. If the B burst is perfect, we
1068	 * believe it; otherwise, it is a noise burst and of no use to
1069	 * anybody.
1070	 */
1071	if (up->burdist >= MINDIST) {
1072		chu_a(peer, up->ndx);
1073	} else if (up->burdist <= -MINDIST) {
1074		chu_b(peer, up->ndx);
1075	} else {
1076		up->status |= NOISE;
1077		return;
1078	}
1079
1080	/*
1081	 * If this is a valid burst, wait a guard time of ten seconds to
1082	 * allow for more bursts, then arm the poll update routine to
1083	 * process the minute. Don't do this if this is called from the
1084	 * timer interrupt routine.
1085	 */
1086	if (peer->outdate != current_time)
1087		peer->nextdate = current_time + 10;
1088}
1089
1090
1091/*
1092 * chu_b - decode format B burst
1093 */
1094static void
1095chu_b(
1096	struct peer *peer,
1097	int	nchar
1098	)
1099{
1100	struct	refclockproc *pp;
1101	struct	chuunit *up;
1102
1103	u_char	code[11];	/* decoded timecode */
1104	char	tbuf[80];	/* trace buffer */
1105	char *	p;
1106	size_t	chars;
1107	size_t	cb;
1108	int	i;
1109
1110	pp = peer->procptr;
1111	up = pp->unitptr;
1112
1113	/*
1114	 * In a format B burst, a character is considered valid only if
1115	 * the first occurence matches the last occurence. The burst is
1116	 * considered valid only if all characters are valid; that is,
1117	 * only if the distance is 40. Note that once a valid frame has
1118	 * been found errors are ignored.
1119	 */
1120	snprintf(tbuf, sizeof(tbuf), "chuB %04x %4.0f %2d %2d ",
1121		 up->status, up->maxsignal, nchar, -up->burdist);
1122	cb = sizeof(tbuf);
1123	p = tbuf;
1124	for (i = 0; i < nchar; i++) {
1125		chars = strlen(p);
1126		if (cb < chars + 1) {
1127			msyslog(LOG_ERR, "chu_b() fatal out buffer");
1128			exit(1);
1129		}
1130		cb -= chars;
1131		p += chars;
1132		snprintf(p, cb, "%02x", up->cbuf[i]);
1133	}
1134	if (pp->sloppyclockflag & CLK_FLAG4)
1135		record_clock_stats(&peer->srcadr, tbuf);
1136#ifdef DEBUG
1137	if (debug)
1138		printf("%s\n", tbuf);
1139#endif
1140	if (up->burdist > -40) {
1141		up->status |= BFRAME;
1142		return;
1143	}
1144
1145	/*
1146	 * Convert the burst data to internal format. Don't bother with
1147	 * the timestamps.
1148	 */
1149	for (i = 0; i < 5; i++) {
1150		code[2 * i] = hexchar[up->cbuf[i] & 0xf];
1151		code[2 * i + 1] = hexchar[(up->cbuf[i] >>
1152		    4) & 0xf];
1153	}
1154	if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &up->leap, &up->dut,
1155	    &pp->year, &up->tai, &up->dst) != 5) {
1156		up->status |= BFORMAT;
1157		return;
1158	}
1159	up->status |= BVALID;
1160	if (up->leap & 0x8)
1161		up->dut = -up->dut;
1162}
1163
1164
1165/*
1166 * chu_a - decode format A burst
1167 */
1168static void
1169chu_a(
1170	struct peer *peer,
1171	int nchar
1172	)
1173{
1174	struct refclockproc *pp;
1175	struct chuunit *up;
1176
1177	char	tbuf[80];	/* trace buffer */
1178	char *	p;
1179	size_t	chars;
1180	size_t	cb;
1181	l_fp	offset;		/* timestamp offset */
1182	int	val;		/* distance */
1183	int	temp;
1184	int	i, j, k;
1185
1186	pp = peer->procptr;
1187	up = pp->unitptr;
1188
1189	/*
1190	 * Determine correct burst phase. There are three cases
1191	 * corresponding to in-phase, one character early or one
1192	 * character late. These cases are distinguished by the position
1193	 * of the framing digits 0x6 at positions 0 and 5 and 0x3 at
1194	 * positions 4 and 9. The correct phase is when the distance
1195	 * relative to the framing digits is maximum. The burst is valid
1196	 * only if the maximum distance is at least MINSYNC.
1197	 */
1198	up->syndist = k = 0;
1199	// val = -16;
1200	for (i = -1; i < 2; i++) {
1201		temp = up->cbuf[i + 4] & 0xf;
1202		if (i >= 0)
1203			temp |= (up->cbuf[i] & 0xf) << 4;
1204		val = chu_dist(temp, 0x63);
1205		temp = (up->cbuf[i + 5] & 0xf) << 4;
1206		if (i + 9 < nchar)
1207			temp |= up->cbuf[i + 9] & 0xf;
1208		val += chu_dist(temp, 0x63);
1209		if (val > up->syndist) {
1210			up->syndist = val;
1211			k = i;
1212		}
1213	}
1214
1215	/*
1216	 * Extract the second number; it must be in the range 2 through
1217	 * 9 and the two repititions must be the same.
1218	 */
1219	temp = (up->cbuf[k + 4] >> 4) & 0xf;
1220	if (temp < 2 || temp > 9 || k + 9 >= nchar || temp !=
1221	    ((up->cbuf[k + 9] >> 4) & 0xf))
1222		temp = 0;
1223	snprintf(tbuf, sizeof(tbuf),
1224		 "chuA %04x %4.0f %2d %2d %2d %2d %1d ", up->status,
1225		 up->maxsignal, nchar, up->burdist, k, up->syndist,
1226		 temp);
1227	cb = sizeof(tbuf);
1228	p = tbuf;
1229	for (i = 0; i < nchar; i++) {
1230		chars = strlen(p);
1231		if (cb < chars + 1) {
1232			msyslog(LOG_ERR, "chu_a() fatal out buffer");
1233			exit(1);
1234		}
1235		cb -= chars;
1236		p += chars;
1237		snprintf(p, cb, "%02x", up->cbuf[i]);
1238	}
1239	if (pp->sloppyclockflag & CLK_FLAG4)
1240		record_clock_stats(&peer->srcadr, tbuf);
1241#ifdef DEBUG
1242	if (debug)
1243		printf("%s\n", tbuf);
1244#endif
1245	if (up->syndist < MINSYNC) {
1246		up->status |= AFRAME;
1247		return;
1248	}
1249
1250	/*
1251	 * A valid burst requires the first seconds number to match the
1252	 * last seconds number. If so, the burst timestamps are
1253	 * corrected to the current minute and saved for later
1254	 * processing. In addition, the seconds decode is advanced from
1255	 * the previous burst to the current one.
1256	 */
1257	if (temp == 0) {
1258		up->status |= AFORMAT;
1259	} else {
1260		up->status |= AVALID;
1261		up->second = pp->second = 30 + temp;
1262		offset.l_ui = 30 + temp;
1263		offset.l_uf = 0;
1264		i = 0;
1265		if (k < 0)
1266			offset = up->charstamp;
1267		else if (k > 0)
1268			i = 1;
1269		for (; i < nchar && (i - 10) < k; i++) {
1270			up->tstamp[up->ntstamp] = up->cstamp[i];
1271			L_SUB(&up->tstamp[up->ntstamp], &offset);
1272			L_ADD(&offset, &up->charstamp);
1273			if (up->ntstamp < MAXSTAGE - 1)
1274				up->ntstamp++;
1275		}
1276		while (temp > up->prevsec) {
1277			for (j = 15; j > 0; j--) {
1278				up->decode[9][j] = up->decode[9][j - 1];
1279				up->decode[19][j] =
1280				    up->decode[19][j - 1];
1281			}
1282			up->decode[9][j] = up->decode[19][j] = 0;
1283			up->prevsec++;
1284		}
1285	}
1286
1287	/*
1288	 * Stash the data in the decoding matrix.
1289	 */
1290	i = -(2 * k);
1291	for (j = 0; j < nchar; j++) {
1292		if (i < 0 || i > 18) {
1293			i += 2;
1294			continue;
1295		}
1296		up->decode[i][up->cbuf[j] & 0xf]++;
1297		i++;
1298		up->decode[i][(up->cbuf[j] >> 4) & 0xf]++;
1299		i++;
1300	}
1301	up->burstcnt++;
1302}
1303
1304
1305/*
1306 * chu_poll - called by the transmit procedure
1307 */
1308static void
1309chu_poll(
1310	int unit,
1311	struct peer *peer	/* peer structure pointer */
1312	)
1313{
1314	struct refclockproc *pp;
1315
1316	pp = peer->procptr;
1317	pp->polls++;
1318}
1319
1320
1321/*
1322 * chu_second - process minute data
1323 */
1324static void
1325chu_second(
1326	int unit,
1327	struct peer *peer	/* peer structure pointer */
1328	)
1329{
1330	struct refclockproc *pp;
1331	struct chuunit *up;
1332	l_fp	offset;
1333	char	synchar, qual, leapchar;
1334	int	minset, i;
1335	double	dtemp;
1336
1337	pp = peer->procptr;
1338	up = pp->unitptr;
1339
1340	/*
1341	 * This routine is called once per minute to process the
1342	 * accumulated burst data. We do a bit of fancy footwork so that
1343	 * this doesn't run while burst data are being accumulated.
1344	 */
1345	up->second = (up->second + 1) % 60;
1346	if (up->second != 0)
1347		return;
1348
1349	/*
1350	 * Process the last burst, if still in the burst buffer.
1351	 * If the minute contains a valid B frame with sufficient A
1352	 * frame metric, it is considered valid. However, the timecode
1353	 * is sent to clockstats even if invalid.
1354	 */
1355	chu_burst(peer);
1356	minset = ((current_time - peer->update) + 30) / 60;
1357	dtemp = chu_major(peer);
1358	qual = 0;
1359	if (up->status & (BFRAME | AFRAME))
1360		qual |= SYNERR;
1361	if (up->status & (BFORMAT | AFORMAT))
1362		qual |= FMTERR;
1363	if (up->status & DECODE)
1364		qual |= DECERR;
1365	if (up->status & STAMP)
1366		qual |= TSPERR;
1367	if (up->status & BVALID && dtemp >= MINMETRIC)
1368		up->status |= INSYNC;
1369	synchar = leapchar = ' ';
1370	if (!(up->status & INSYNC)) {
1371		pp->leap = LEAP_NOTINSYNC;
1372		synchar = '?';
1373	} else if (up->leap & 0x2) {
1374		pp->leap = LEAP_ADDSECOND;
1375		leapchar = 'L';
1376	} else if (up->leap & 0x4) {
1377		pp->leap = LEAP_DELSECOND;
1378		leapchar = 'l';
1379	} else {
1380		pp->leap = LEAP_NOWARNING;
1381	}
1382	snprintf(pp->a_lastcode, sizeof(pp->a_lastcode),
1383	    "%c%1X %04d %03d %02d:%02d:%02d %c%x %+d %d %d %s %.0f %d",
1384	    synchar, qual, pp->year, pp->day, pp->hour, pp->minute,
1385	    pp->second, leapchar, up->dst, up->dut, minset, up->gain,
1386	    up->ident, dtemp, up->ntstamp);
1387	pp->lencode = strlen(pp->a_lastcode);
1388
1389	/*
1390	 * If in sync and the signal metric is above threshold, the
1391	 * timecode is ipso fatso valid and can be selected to
1392	 * discipline the clock.
1393	 */
1394	if (up->status & INSYNC && !(up->status & (DECODE | STAMP)) &&
1395	    dtemp > MINMETRIC) {
1396		if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT,
1397		    up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) {
1398			up->errflg = CEVNT_BADTIME;
1399		} else {
1400			offset.l_uf = 0;
1401			for (i = 0; i < up->ntstamp; i++)
1402				refclock_process_offset(pp, offset,
1403				up->tstamp[i], PDELAY +
1404				    pp->fudgetime1);
1405			pp->lastref = up->timestamp;
1406			refclock_receive(peer);
1407		}
1408	}
1409	if (dtemp > 0)
1410		record_clock_stats(&peer->srcadr, pp->a_lastcode);
1411#ifdef DEBUG
1412	if (debug)
1413		printf("chu: timecode %d %s\n", pp->lencode,
1414		    pp->a_lastcode);
1415#endif
1416#ifdef ICOM
1417	chu_newchan(peer, dtemp);
1418#endif /* ICOM */
1419	chu_clear(peer);
1420	if (up->errflg)
1421		refclock_report(peer, up->errflg);
1422	up->errflg = 0;
1423}
1424
1425
1426/*
1427 * chu_major - majority decoder
1428 */
1429static double
1430chu_major(
1431	struct peer *peer	/* peer structure pointer */
1432	)
1433{
1434	struct refclockproc *pp;
1435	struct chuunit *up;
1436
1437	u_char	code[11];	/* decoded timecode */
1438	int	metric;		/* distance metric */
1439	int	val1;		/* maximum distance */
1440	int	synchar;	/* stray cat */
1441	int	temp;
1442	int	i, j, k;
1443
1444	pp = peer->procptr;
1445	up = pp->unitptr;
1446
1447	/*
1448	 * Majority decoder. Each burst encodes two replications at each
1449	 * digit position in the timecode. Each row of the decoding
1450	 * matrix encodes the number of occurences of each digit found
1451	 * at the corresponding position. The maximum over all
1452	 * occurrences at each position is the distance for this
1453	 * position and the corresponding digit is the maximum-
1454	 * likelihood candidate. If the distance is not more than half
1455	 * the total number of occurences, a majority has not been found
1456	 * and the data are discarded. The decoding distance is defined
1457	 * as the sum of the distances over the first nine digits. The
1458	 * tenth digit varies over the seconds, so we don't count it.
1459	 */
1460	metric = 0;
1461	for (i = 0; i < 9; i++) {
1462		val1 = 0;
1463		k = 0;
1464		for (j = 0; j < 16; j++) {
1465			temp = up->decode[i][j] + up->decode[i + 10][j];
1466			if (temp > val1) {
1467				val1 = temp;
1468				k = j;
1469			}
1470		}
1471		if (val1 <= up->burstcnt)
1472			up->status |= DECODE;
1473		metric += val1;
1474		code[i] = hexchar[k];
1475	}
1476
1477	/*
1478	 * Compute the timecode timestamp from the days, hours and
1479	 * minutes of the timecode. Use clocktime() for the aggregate
1480	 * minutes and the minute offset computed from the burst
1481	 * seconds. Note that this code relies on the filesystem time
1482	 * for the years and does not use the years of the timecode.
1483	 */
1484	if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day,
1485	    &pp->hour, &pp->minute) != 4)
1486		up->status |= DECODE;
1487	if (up->ntstamp < MINSTAMP)
1488		up->status |= STAMP;
1489	return (metric);
1490}
1491
1492
1493/*
1494 * chu_clear - clear decoding matrix
1495 */
1496static void
1497chu_clear(
1498	struct peer *peer	/* peer structure pointer */
1499	)
1500{
1501	struct refclockproc *pp;
1502	struct chuunit *up;
1503	int	i, j;
1504
1505	pp = peer->procptr;
1506	up = pp->unitptr;
1507
1508	/*
1509	 * Clear stuff for the minute.
1510	 */
1511	up->ndx = up->prevsec = 0;
1512	up->burstcnt = up->ntstamp = 0;
1513	up->status &= INSYNC | METRIC;
1514	for (i = 0; i < 20; i++) {
1515		for (j = 0; j < 16; j++)
1516			up->decode[i][j] = 0;
1517	}
1518}
1519
1520#ifdef ICOM
1521/*
1522 * chu_newchan - called once per minute to find the best channel;
1523 * returns zero on success, nonzero if ICOM error.
1524 */
1525static int
1526chu_newchan(
1527	struct peer *peer,
1528	double	met
1529	)
1530{
1531	struct chuunit *up;
1532	struct refclockproc *pp;
1533	struct xmtr *sp;
1534	int	rval;
1535	double	metric;
1536	int	i;
1537
1538	pp = peer->procptr;
1539	up = pp->unitptr;
1540
1541	/*
1542	 * The radio can be tuned to three channels: 0 (3330 kHz), 1
1543	 * (7850 kHz) and 2 (14670 kHz). There are five one-minute
1544	 * dwells in each cycle. During the first dwell the radio is
1545	 * tuned to one of the three channels to measure the channel
1546	 * metric. The channel is selected as the one least recently
1547	 * measured. During the remaining four dwells the radio is tuned
1548	 * to the channel with the highest channel metric.
1549	 */
1550	if (up->fd_icom <= 0)
1551		return (0);
1552
1553	/*
1554	 * Update the current channel metric and age of all channels.
1555	 * Scan all channels for the highest metric.
1556	 */
1557	sp = &up->xmtr[up->chan];
1558	sp->metric -= sp->integ[sp->iptr];
1559	sp->integ[sp->iptr] = met;
1560	sp->metric += sp->integ[sp->iptr];
1561	sp->probe = 0;
1562	sp->iptr = (sp->iptr + 1) % ISTAGE;
1563	metric = 0;
1564	for (i = 0; i < NCHAN; i++) {
1565		up->xmtr[i].probe++;
1566		if (up->xmtr[i].metric > metric) {
1567			up->status |= METRIC;
1568			metric = up->xmtr[i].metric;
1569			up->chan = i;
1570		}
1571	}
1572
1573	/*
1574	 * Start the next dwell. If the first dwell or no stations have
1575	 * been heard, continue round-robin scan.
1576	 */
1577	up->dwell = (up->dwell + 1) % DWELL;
1578	if (up->dwell == 0 || metric == 0) {
1579		rval = 0;
1580		for (i = 0; i < NCHAN; i++) {
1581			if (up->xmtr[i].probe > rval) {
1582				rval = up->xmtr[i].probe;
1583				up->chan = i;
1584			}
1585		}
1586	}
1587
1588	/* Retune the radio at each dwell in case somebody nudges the
1589	 * tuning knob.
1590	 */
1591	rval = icom_freq(up->fd_icom, peer->ttl & 0x7f, qsy[up->chan] +
1592	    TUNE);
1593	snprintf(up->ident, sizeof(up->ident), "CHU%d", up->chan);
1594	memcpy(&pp->refid, up->ident, 4);
1595	memcpy(&peer->refid, up->ident, 4);
1596	if (metric == 0 && up->status & METRIC) {
1597		up->status &= ~METRIC;
1598		refclock_report(peer, CEVNT_PROP);
1599	}
1600	return (rval);
1601}
1602#endif /* ICOM */
1603
1604
1605/*
1606 * chu_dist - determine the distance of two octet arguments
1607 */
1608static int
1609chu_dist(
1610	int	x,		/* an octet of bits */
1611	int	y		/* another octet of bits */
1612	)
1613{
1614	int	val;		/* bit count */
1615	int	temp;
1616	int	i;
1617
1618	/*
1619	 * The distance is determined as the weight of the exclusive OR
1620	 * of the two arguments. The weight is determined by the number
1621	 * of one bits in the result. Each one bit increases the weight,
1622	 * while each zero bit decreases it.
1623	 */
1624	temp = x ^ y;
1625	val = 0;
1626	for (i = 0; i < 8; i++) {
1627		if ((temp & 0x1) == 0)
1628			val++;
1629		else
1630			val--;
1631		temp >>= 1;
1632	}
1633	return (val);
1634}
1635
1636
1637#ifdef HAVE_AUDIO
1638/*
1639 * chu_gain - adjust codec gain
1640 *
1641 * This routine is called at the end of each second. During the second
1642 * the number of signal clips above the MAXAMP threshold (6000). If
1643 * there are no clips, the gain is bumped up; if there are more than
1644 * MAXCLP clips (100), it is bumped down. The decoder is relatively
1645 * insensitive to amplitude, so this crudity works just peachy. The
1646 * routine also jiggles the input port and selectively mutes the
1647 */
1648static void
1649chu_gain(
1650	struct peer *peer	/* peer structure pointer */
1651	)
1652{
1653	struct refclockproc *pp;
1654	struct chuunit *up;
1655
1656	pp = peer->procptr;
1657	up = pp->unitptr;
1658
1659	/*
1660	 * Apparently, the codec uses only the high order bits of the
1661	 * gain control field. Thus, it may take awhile for changes to
1662	 * wiggle the hardware bits.
1663	 */
1664	if (up->clipcnt == 0) {
1665		up->gain += 4;
1666		if (up->gain > MAXGAIN)
1667			up->gain = MAXGAIN;
1668	} else if (up->clipcnt > MAXCLP) {
1669		up->gain -= 4;
1670		if (up->gain < 0)
1671			up->gain = 0;
1672	}
1673	audio_gain(up->gain, up->mongain, up->port);
1674	up->clipcnt = 0;
1675}
1676#endif /* HAVE_AUDIO */
1677
1678
1679#else
1680NONEMPTY_TRANSLATION_UNIT
1681#endif /* REFCLOCK */
1682