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