xref: /netbsd/external/bsd/ntp/dist/ntpd/refclock_chu.c (revision 6550d01e)
1 /*	$NetBSD: refclock_chu.c,v 1.1.1.1 2009/12/13 16:55:47 kardel 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 #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 MINCHAR		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 #ifdef DEBUG
484 	if (fd_audio > 0 && debug)
485 		audio_show();
486 #endif
487 
488 	/*
489 	 * If audio is unavailable, Open serial port in raw mode.
490 	 */
491 	if (fd_audio > 0) {
492 		fd = fd_audio;
493 	} else {
494 		sprintf(device, DEVICE, unit);
495 		fd = refclock_open(device, SPEED232, LDISC_RAW);
496 	}
497 #else /* HAVE_AUDIO */
498 
499 	/*
500 	 * Open serial port in raw mode.
501 	 */
502 	sprintf(device, DEVICE, unit);
503 	fd = refclock_open(device, SPEED232, LDISC_RAW);
504 #endif /* HAVE_AUDIO */
505 	if (fd < 0)
506 		return (0);
507 
508 	/*
509 	 * Allocate and initialize unit structure
510 	 */
511 	if (!(up = (struct chuunit *)
512 	      emalloc(sizeof(struct chuunit)))) {
513 		close(fd);
514 		return (0);
515 	}
516 	memset((char *)up, 0, sizeof(struct chuunit));
517 	pp = peer->procptr;
518 	pp->unitptr = (caddr_t)up;
519 	pp->io.clock_recv = chu_receive;
520 	pp->io.srcclock = (caddr_t)peer;
521 	pp->io.datalen = 0;
522 	pp->io.fd = fd;
523 	if (!io_addclock(&pp->io)) {
524 		close(fd);
525 		free(up);
526 		return (0);
527 	}
528 
529 	/*
530 	 * Initialize miscellaneous variables
531 	 */
532 	peer->precision = PRECISION;
533 	pp->clockdesc = DESCRIPTION;
534 	strcpy(up->ident, "CHU");
535 	memcpy(&pp->refid, up->ident, 4);
536 	DTOLFP(CHAR, &up->charstamp);
537 #ifdef HAVE_AUDIO
538 
539 	/*
540 	 * The companded samples are encoded sign-magnitude. The table
541 	 * contains all the 256 values in the interest of speed. We do
542 	 * this even if the audio codec is not available. C'est la lazy.
543 	 */
544 	up->fd_audio = fd_audio;
545 	up->gain = 127;
546 	up->comp[0] = up->comp[OFFSET] = 0.;
547 	up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
548 	up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
549 	step = 2.;
550 	for (i = 3; i < OFFSET; i++) {
551 		up->comp[i] = up->comp[i - 1] + step;
552 		up->comp[OFFSET + i] = -up->comp[i];
553                 if (i % 16 == 0)
554                 	step *= 2.;
555 	}
556 	DTOLFP(1. / SECOND, &up->tick);
557 #endif /* HAVE_AUDIO */
558 #ifdef ICOM
559 	temp = 0;
560 #ifdef DEBUG
561 	if (debug > 1)
562 		temp = P_TRACE;
563 #endif
564 	if (peer->ttl > 0) {
565 		if (peer->ttl & 0x80)
566 			up->fd_icom = icom_init("/dev/icom", B1200,
567 			    temp);
568 		else
569 			up->fd_icom = icom_init("/dev/icom", B9600,
570 			    temp);
571 	}
572 	if (up->fd_icom > 0) {
573 		if (chu_newchan(peer, 0) != 0) {
574 			msyslog(LOG_NOTICE, "icom: radio not found");
575 			close(up->fd_icom);
576 			up->fd_icom = 0;
577 		} else {
578 			msyslog(LOG_NOTICE, "icom: autotune enabled");
579 		}
580 	}
581 #endif /* ICOM */
582 	return (1);
583 }
584 
585 
586 /*
587  * chu_shutdown - shut down the clock
588  */
589 static void
590 chu_shutdown(
591 	int	unit,		/* instance number (not used) */
592 	struct peer *peer	/* peer structure pointer */
593 	)
594 {
595 	struct chuunit *up;
596 	struct refclockproc *pp;
597 
598 	pp = peer->procptr;
599 	up = (struct chuunit *)pp->unitptr;
600 	if (up == NULL)
601 		return;
602 
603 	io_closeclock(&pp->io);
604 #ifdef ICOM
605 	if (up->fd_icom > 0)
606 		close(up->fd_icom);
607 #endif /* ICOM */
608 	free(up);
609 }
610 
611 
612 /*
613  * chu_receive - receive data from the audio or serial device
614  */
615 static void
616 chu_receive(
617 	struct recvbuf *rbufp	/* receive buffer structure pointer */
618 	)
619 {
620 #ifdef HAVE_AUDIO
621 	struct chuunit *up;
622 	struct refclockproc *pp;
623 	struct peer *peer;
624 
625 	peer = (struct peer *)rbufp->recv_srcclock;
626 	pp = peer->procptr;
627 	up = (struct chuunit *)pp->unitptr;
628 
629 	/*
630 	 * If the audio codec is warmed up, the buffer contains codec
631 	 * samples which need to be demodulated and decoded into CHU
632 	 * characters using the software UART. Otherwise, the buffer
633 	 * contains CHU characters from the serial port, so the software
634 	 * UART is bypassed. In this case the CPU will probably run a
635 	 * few degrees cooler.
636 	 */
637 	if (up->fd_audio > 0)
638 		chu_audio_receive(rbufp);
639 	else
640 		chu_serial_receive(rbufp);
641 #else
642 	chu_serial_receive(rbufp);
643 #endif /* HAVE_AUDIO */
644 }
645 
646 
647 #ifdef HAVE_AUDIO
648 /*
649  * chu_audio_receive - receive data from the audio device
650  */
651 static void
652 chu_audio_receive(
653 	struct recvbuf *rbufp	/* receive buffer structure pointer */
654 	)
655 {
656 	struct chuunit *up;
657 	struct refclockproc *pp;
658 	struct peer *peer;
659 
660 	double	sample;		/* codec sample */
661 	u_char	*dpt;		/* buffer pointer */
662 	int	bufcnt;		/* buffer counter */
663 	l_fp	ltemp;		/* l_fp temp */
664 
665 	peer = (struct peer *)rbufp->recv_srcclock;
666 	pp = peer->procptr;
667 	up = (struct chuunit *)pp->unitptr;
668 
669 	/*
670 	 * Main loop - read until there ain't no more. Note codec
671 	 * samples are bit-inverted.
672 	 */
673 	DTOLFP((double)rbufp->recv_length / SECOND, &ltemp);
674 	L_SUB(&rbufp->recv_time, &ltemp);
675 	up->timestamp = rbufp->recv_time;
676 	dpt = rbufp->recv_buffer;
677 	for (bufcnt = 0; bufcnt < rbufp->recv_length; bufcnt++) {
678 		sample = up->comp[~*dpt++ & 0xff];
679 
680 		/*
681 		 * Clip noise spikes greater than MAXAMP. If no clips,
682 		 * increase the gain a tad; if the clips are too high,
683 		 * decrease a tad.
684 		 */
685 		if (sample > MAXAMP) {
686 			sample = MAXAMP;
687 			up->clipcnt++;
688 		} else if (sample < -MAXAMP) {
689 			sample = -MAXAMP;
690 			up->clipcnt++;
691 		}
692 		chu_rf(peer, sample);
693 		L_ADD(&up->timestamp, &up->tick);
694 
695 		/*
696 		 * Once each second ride gain.
697 		 */
698 		up->seccnt = (up->seccnt + 1) % SECOND;
699 		if (up->seccnt == 0) {
700 			chu_gain(peer);
701 		}
702 	}
703 
704 	/*
705 	 * Set the input port and monitor gain for the next buffer.
706 	 */
707 	if (pp->sloppyclockflag & CLK_FLAG2)
708 		up->port = 2;
709 	else
710 		up->port = 1;
711 	if (pp->sloppyclockflag & CLK_FLAG3)
712 		up->mongain = MONGAIN;
713 	else
714 		up->mongain = 0;
715 }
716 
717 
718 /*
719  * chu_rf - filter and demodulate the FSK signal
720  *
721  * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz
722  * and space 2025 Hz. It uses a bandpass filter followed by a soft
723  * limiter, FM discriminator and lowpass filter. A maximum-likelihood
724  * decoder samples the baseband signal at eight times the baud rate and
725  * detects the start bit of each character.
726  *
727  * The filters are built for speed, which explains the rather clumsy
728  * code. Hopefully, the compiler will efficiently implement the move-
729  * and-muiltiply-and-add operations.
730  */
731 static void
732 chu_rf(
733 	struct peer *peer,	/* peer structure pointer */
734 	double	sample		/* analog sample */
735 	)
736 {
737 	struct refclockproc *pp;
738 	struct chuunit *up;
739 	struct surv *sp;
740 
741 	/*
742 	 * Local variables
743 	 */
744 	double	signal;		/* bandpass signal */
745 	double	limit;		/* limiter signal */
746 	double	disc;		/* discriminator signal */
747 	double	lpf;		/* lowpass signal */
748 	double	dist;		/* UART signal distance */
749 	int	i, j;
750 
751 	pp = peer->procptr;
752 	up = (struct chuunit *)pp->unitptr;
753 
754 	/*
755 	 * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered
756 	 * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB,
757 	 * phase delay 0.24 ms.
758 	 */
759 	signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01;
760 	signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01;
761 	signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00;
762 	signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00;
763 	signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00;
764 	signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00;
765 	signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00;
766 	signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01;
767 	up->bpf[0] = sample - signal;
768 	signal = up->bpf[0] * 6.176213e-03
769 	    + up->bpf[1] * 3.156599e-03
770 	    + up->bpf[2] * 7.567487e-03
771 	    + up->bpf[3] * 4.344580e-03
772 	    + up->bpf[4] * 1.190128e-02
773 	    + up->bpf[5] * 4.344580e-03
774 	    + up->bpf[6] * 7.567487e-03
775 	    + up->bpf[7] * 3.156599e-03
776 	    + up->bpf[8] * 6.176213e-03;
777 
778 	up->monitor = signal / 4.;	/* note monitor after filter */
779 
780 	/*
781 	 * Soft limiter/discriminator. The 11-sample discriminator lag
782 	 * interval corresponds to three cycles of 2125 Hz, which
783 	 * requires the sample frequency to be 2125 * 11 / 3 = 7791.7
784 	 * Hz. The discriminator output varies +-0.5 interval for input
785 	 * frequency 2025-2225 Hz. However, we don't get to sample at
786 	 * this frequency, so the discriminator output is biased. Life
787 	 * at 8000 Hz sucks.
788 	 */
789 	limit = signal;
790 	if (limit > LIMIT)
791 		limit = LIMIT;
792 	else if (limit < -LIMIT)
793 		limit = -LIMIT;
794 	disc = up->disc[up->discptr] * -limit;
795 	up->disc[up->discptr] = limit;
796 	up->discptr = (up->discptr + 1 ) % LAG;
797 	if (disc >= 0)
798 		disc = SQRT(disc);
799 	else
800 		disc = -SQRT(-disc);
801 
802 	/*
803 	 * Lowpass filter. Raised cosine FIR, Ts = 1 / 300, beta = 0.1.
804 	 */
805 	lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02;
806 	lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01;
807 	lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01;
808 	lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01;
809 	lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01;
810 	lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01;
811 	lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01;
812 	lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01;
813 	lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01;
814 	lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01;
815 	lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01;
816 	lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01;
817 	lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01;
818 	lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00;
819 	lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01;
820 	lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01;
821 	lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01;
822 	lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01;
823 	lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01;
824 	lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01;
825 	lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01;
826 	lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01;
827 	lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01;
828 	lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01;
829 	lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01;
830 	lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01;
831 	lpf += up->lpf[0] = disc * 2.538771e-02;
832 
833 	/*
834 	 * Maximum-likelihood decoder. The UART updates each of the
835 	 * eight survivors and determines the span, slice level and
836 	 * tentative decoded character. Valid 11-bit characters are
837 	 * framed so that bit 10 and bit 11 (stop bits) are mark and bit
838 	 * 1 (start bit) is space. When a valid character is found, the
839 	 * survivor with maximum distance determines the final decoded
840 	 * character.
841 	 */
842 	up->baud += 1. / SECOND;
843 	if (up->baud > 1. / (BAUD * 8.)) {
844 		up->baud -= 1. / (BAUD * 8.);
845 		up->decptr = (up->decptr + 1) % 8;
846 		sp = &up->surv[up->decptr];
847 		sp->cstamp = up->timestamp;
848 		chu_uart(sp, -lpf * AGAIN);
849 		if (up->dbrk > 0) {
850 			up->dbrk--;
851 			if (up->dbrk > 0)
852 				return;
853 
854 			up->decpha = up->decptr;
855 		}
856 		if (up->decptr != up->decpha)
857 			return;
858 
859 		dist = 0;
860 		j = -1;
861 		for (i = 0; i < 8; i++) {
862 
863 			/*
864 			 * The timestamp is taken at the last bit, so
865 			 * for correct decoding we reqire sufficient
866 			 * span and correct start bit and two stop bits.
867 			 */
868 			if ((up->surv[i].uart & 0x601) != 0x600 ||
869 			    up->surv[i].span < SPAN)
870 				continue;
871 
872 			if (up->surv[i].dist > dist) {
873 				dist = up->surv[i].dist;
874 				j = i;
875 			}
876 		}
877 		if (j < 0)
878 			return;
879 
880 		/*
881 		 * Process the character, then blank the decoder until
882 		 * the end of the next character.This sets the decoding
883 		 * phase of the entire burst from the phase of the first
884 		 * character.
885 		 */
886 		up->maxsignal = up->surv[j].span;
887 		chu_decode(peer, (up->surv[j].uart >> 1) & 0xff,
888 		    up->surv[j].cstamp);
889 		up->dbrk = 88;
890 	}
891 }
892 
893 
894 /*
895  * chu_uart - maximum-likelihood UART
896  *
897  * This routine updates a shift register holding the last 11 envelope
898  * samples. It then computes the slice level and span over these samples
899  * and determines the tentative data bits and distance. The calling
900  * program selects over the last eight survivors the one with maximum
901  * distance to determine the decoded character.
902  */
903 static void
904 chu_uart(
905 	struct surv *sp,	/* survivor structure pointer */
906 	double	sample		/* baseband signal */
907 	)
908 {
909 	double	es_max, es_min;	/* max/min envelope */
910 	double	slice;		/* slice level */
911 	double	dist;		/* distance */
912 	double	dtemp;
913 	int	i;
914 
915 	/*
916 	 * Save the sample and shift right. At the same time, measure
917 	 * the maximum and minimum over all eleven samples.
918 	 */
919 	es_max = -1e6;
920 	es_min = 1e6;
921 	sp->shift[0] = sample;
922 	for (i = 11; i > 0; i--) {
923 		sp->shift[i] = sp->shift[i - 1];
924 		if (sp->shift[i] > es_max)
925 			es_max = sp->shift[i];
926 		if (sp->shift[i] < es_min)
927 			es_min = sp->shift[i];
928 	}
929 
930 	/*
931 	 * Determine the span as the maximum less the minimum and the
932 	 * slice level as the minimum plus a fraction of the span. Note
933 	 * the slight bias toward mark to correct for the modem tendency
934 	 * to make more mark than space errors. Compute the distance on
935 	 * the assumption the last two bits must be mark, the first
936 	 * space and the rest either mark or space.
937 	 */
938 	sp->span = es_max - es_min;
939 	slice = es_min + .45 * sp->span;
940 	dist = 0;
941 	sp->uart = 0;
942 	for (i = 1; i < 12; i++) {
943 		sp->uart <<= 1;
944 		dtemp = sp->shift[i];
945 		if (dtemp > slice)
946 			sp->uart |= 0x1;
947 		if (i == 1 || i == 2) {
948 			dist += dtemp - es_min;
949 		} else if (i == 11) {
950 			dist += es_max - dtemp;
951 		} else {
952 			if (dtemp > slice)
953 				dist += dtemp - es_min;
954 			else
955 				dist += es_max - dtemp;
956 		}
957 	}
958 	sp->dist = dist / (11 * sp->span);
959 }
960 #endif /* HAVE_AUDIO */
961 
962 
963 /*
964  * chu_serial_receive - receive data from the serial device
965  */
966 static void
967 chu_serial_receive(
968 	struct recvbuf *rbufp	/* receive buffer structure pointer */
969 	)
970 {
971 	struct chuunit *up;
972 	struct refclockproc *pp;
973 	struct peer *peer;
974 
975 	u_char	*dpt;		/* receive buffer pointer */
976 
977 	peer = (struct peer *)rbufp->recv_srcclock;
978 	pp = peer->procptr;
979 	up = (struct chuunit *)pp->unitptr;
980 
981 	dpt = (u_char *)&rbufp->recv_space;
982 	chu_decode(peer, *dpt, rbufp->recv_time);
983 }
984 
985 
986 /*
987  * chu_decode - decode the character data
988  */
989 static void
990 chu_decode(
991 	struct peer *peer,	/* peer structure pointer */
992 	int	hexhex,		/* data character */
993 	l_fp	cstamp		/* data character timestamp */
994 	)
995 {
996 	struct refclockproc *pp;
997 	struct chuunit *up;
998 
999 	l_fp	tstmp;		/* timestamp temp */
1000 	double	dtemp;
1001 
1002 	pp = peer->procptr;
1003 	up = (struct chuunit *)pp->unitptr;
1004 
1005 	/*
1006 	 * If the interval since the last character is greater than the
1007 	 * longest burst, process the last burst and start a new one. If
1008 	 * the interval is less than this but greater than two
1009 	 * characters, consider this a noise burst and reject it.
1010 	 */
1011 	tstmp = up->timestamp;
1012 	if (L_ISZERO(&up->laststamp))
1013 		up->laststamp = up->timestamp;
1014 	L_SUB(&tstmp, &up->laststamp);
1015 	up->laststamp = up->timestamp;
1016 	LFPTOD(&tstmp, dtemp);
1017 	if (dtemp > BURST * CHAR) {
1018 		chu_burst(peer);
1019 		up->ndx = 0;
1020 	} else if (dtemp > 2.5 * CHAR) {
1021 		up->ndx = 0;
1022 	}
1023 
1024 	/*
1025 	 * Append the character to the current burst and append the
1026 	 * character timestamp to the timestamp list.
1027 	 */
1028 	if (up->ndx < BURST) {
1029 		up->cbuf[up->ndx] = hexhex & 0xff;
1030 		up->cstamp[up->ndx] = cstamp;
1031 		up->ndx++;
1032 
1033 	}
1034 }
1035 
1036 
1037 /*
1038  * chu_burst - search for valid burst format
1039  */
1040 static void
1041 chu_burst(
1042 	struct peer *peer
1043 	)
1044 {
1045 	struct chuunit *up;
1046 	struct refclockproc *pp;
1047 
1048 	int	i;
1049 
1050 	pp = peer->procptr;
1051 	up = (struct chuunit *)pp->unitptr;
1052 
1053 	/*
1054 	 * Correlate a block of five characters with the next block of
1055 	 * five characters. The burst distance is defined as the number
1056 	 * of bits that match in the two blocks for format A and that
1057 	 * match the inverse for format B.
1058 	 */
1059 	if (up->ndx < MINCHAR) {
1060 		up->status |= RUNT;
1061 		return;
1062 	}
1063 	up->burdist = 0;
1064 	for (i = 0; i < 5 && i < up->ndx - 5; i++)
1065 		up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]);
1066 
1067 	/*
1068 	 * If the burst distance is at least MINDIST, this must be a
1069 	 * format A burst; if the value is not greater than -MINDIST, it
1070 	 * must be a format B burst. If the B burst is perfect, we
1071 	 * believe it; otherwise, it is a noise burst and of no use to
1072 	 * anybody.
1073 	 */
1074 	if (up->burdist >= MINDIST) {
1075 		chu_a(peer, up->ndx);
1076 	} else if (up->burdist <= -MINDIST) {
1077 		chu_b(peer, up->ndx);
1078 	} else {
1079 		up->status |= NOISE;
1080 		return;
1081 	}
1082 
1083 	/*
1084 	 * If this is a valid burst, wait a guard time of ten seconds to
1085 	 * allow for more bursts, then arm the poll update routine to
1086 	 * process the minute. Don't do this if this is called from the
1087 	 * timer interrupt routine.
1088 	 */
1089 	if (peer->outdate != current_time)
1090 		peer->nextdate = current_time + 10;
1091 }
1092 
1093 
1094 /*
1095  * chu_b - decode format B burst
1096  */
1097 static void
1098 chu_b(
1099 	struct peer *peer,
1100 	int	nchar
1101 	)
1102 {
1103 	struct	refclockproc *pp;
1104 	struct	chuunit *up;
1105 
1106 	u_char	code[11];	/* decoded timecode */
1107 	char	tbuf[80];	/* trace buffer */
1108 	int	i;
1109 
1110 	pp = peer->procptr;
1111 	up = (struct chuunit *)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 	sprintf(tbuf, "chuB %04x %4.0f %2d %2d ", up->status,
1121 	    up->maxsignal, nchar, -up->burdist);
1122 	for (i = 0; i < nchar; i++)
1123 		sprintf(&tbuf[strlen(tbuf)], "%02x", up->cbuf[i]);
1124 	if (pp->sloppyclockflag & CLK_FLAG4)
1125 		record_clock_stats(&peer->srcadr, tbuf);
1126 #ifdef DEBUG
1127 	if (debug)
1128 		printf("%s\n", tbuf);
1129 #endif
1130 	if (up->burdist > -40) {
1131 		up->status |= BFRAME;
1132 		return;
1133 	}
1134 
1135 	/*
1136 	 * Convert the burst data to internal format. Don't bother with
1137 	 * the timestamps.
1138 	 */
1139 	for (i = 0; i < 5; i++) {
1140 		code[2 * i] = hexchar[up->cbuf[i] & 0xf];
1141 		code[2 * i + 1] = hexchar[(up->cbuf[i] >>
1142 		    4) & 0xf];
1143 	}
1144 	if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &up->leap, &up->dut,
1145 	    &pp->year, &up->tai, &up->dst) != 5) {
1146 		up->status |= BFORMAT;
1147 		return;
1148 	}
1149 	up->status |= BVALID;
1150 	if (up->leap & 0x8)
1151 		up->dut = -up->dut;
1152 }
1153 
1154 
1155 /*
1156  * chu_a - decode format A burst
1157  */
1158 static void
1159 chu_a(
1160 	struct peer *peer,
1161 	int nchar
1162 	)
1163 {
1164 	struct refclockproc *pp;
1165 	struct chuunit *up;
1166 
1167 	char	tbuf[80];	/* trace buffer */
1168 	l_fp	offset;		/* timestamp offset */
1169 	int	val;		/* distance */
1170 	int	temp;
1171 	int	i, j, k;
1172 
1173 	pp = peer->procptr;
1174 	up = (struct chuunit *)pp->unitptr;
1175 
1176 	/*
1177 	 * Determine correct burst phase. There are three cases
1178 	 * corresponding to in-phase, one character early or one
1179 	 * character late. These cases are distinguished by the position
1180 	 * of the framing digits 0x6 at positions 0 and 5 and 0x3 at
1181 	 * positions 4 and 9. The correct phase is when the distance
1182 	 * relative to the framing digits is maximum. The burst is valid
1183 	 * only if the maximum distance is at least MINSYNC.
1184 	 */
1185 	up->syndist = k = 0;
1186 	val = -16;
1187 	for (i = -1; i < 2; i++) {
1188 		temp = up->cbuf[i + 4] & 0xf;
1189 		if (i >= 0)
1190 			temp |= (up->cbuf[i] & 0xf) << 4;
1191 		val = chu_dist(temp, 0x63);
1192 		temp = (up->cbuf[i + 5] & 0xf) << 4;
1193 		if (i + 9 < nchar)
1194 			temp |= up->cbuf[i + 9] & 0xf;
1195 		val += chu_dist(temp, 0x63);
1196 		if (val > up->syndist) {
1197 			up->syndist = val;
1198 			k = i;
1199 		}
1200 	}
1201 
1202 	/*
1203 	 * Extract the second number; it must be in the range 2 through
1204 	 * 9 and the two repititions must be the same.
1205 	 */
1206 	temp = (up->cbuf[k + 4] >> 4) & 0xf;
1207 	if (temp < 2 || temp > 9 || k + 9 >= nchar || temp !=
1208 	    ((up->cbuf[k + 9] >> 4) & 0xf))
1209 		temp = 0;
1210 	sprintf(tbuf, "chuA %04x %4.0f %2d %2d %2d %2d %1d ",
1211 	    up->status, up->maxsignal, nchar, up->burdist, k,
1212 	    up->syndist, temp);
1213 	for (i = 0; i < nchar; i++)
1214 		sprintf(&tbuf[strlen(tbuf)], "%02x",
1215 		    up->cbuf[i]);
1216 	if (pp->sloppyclockflag & CLK_FLAG4)
1217 		record_clock_stats(&peer->srcadr, tbuf);
1218 #ifdef DEBUG
1219 	if (debug)
1220 		printf("%s\n", tbuf);
1221 #endif
1222 	if (up->syndist < MINSYNC) {
1223 		up->status |= AFRAME;
1224 		return;
1225 	}
1226 
1227 	/*
1228 	 * A valid burst requires the first seconds number to match the
1229 	 * last seconds number. If so, the burst timestamps are
1230 	 * corrected to the current minute and saved for later
1231 	 * processing. In addition, the seconds decode is advanced from
1232 	 * the previous burst to the current one.
1233 	 */
1234 	if (temp == 0) {
1235 		up->status |= AFORMAT;
1236 	} else {
1237 		up->status |= AVALID;
1238 		up->second = pp->second = 30 + temp;
1239 		offset.l_ui = 30 + temp;
1240 		offset.l_f = 0;
1241 		i = 0;
1242 		if (k < 0)
1243 			offset = up->charstamp;
1244 		else if (k > 0)
1245 			i = 1;
1246 		for (; i < nchar && i < k + 10; i++) {
1247 			up->tstamp[up->ntstamp] = up->cstamp[i];
1248 			L_SUB(&up->tstamp[up->ntstamp], &offset);
1249 			L_ADD(&offset, &up->charstamp);
1250 			if (up->ntstamp < MAXSTAGE - 1)
1251 				up->ntstamp++;
1252 		}
1253 		while (temp > up->prevsec) {
1254 			for (j = 15; j > 0; j--) {
1255 				up->decode[9][j] = up->decode[9][j - 1];
1256 				up->decode[19][j] =
1257 				    up->decode[19][j - 1];
1258 			}
1259 			up->decode[9][j] = up->decode[19][j] = 0;
1260 			up->prevsec++;
1261 		}
1262 	}
1263 
1264 	/*
1265 	 * Stash the data in the decoding matrix.
1266 	 */
1267 	i = -(2 * k);
1268 	for (j = 0; j < nchar; j++) {
1269 		if (i < 0 || i > 18) {
1270 			i += 2;
1271 			continue;
1272 		}
1273 		up->decode[i][up->cbuf[j] & 0xf]++;
1274 		i++;
1275 		up->decode[i][(up->cbuf[j] >> 4) & 0xf]++;
1276 		i++;
1277 	}
1278 	up->burstcnt++;
1279 }
1280 
1281 
1282 /*
1283  * chu_poll - called by the transmit procedure
1284  */
1285 static void
1286 chu_poll(
1287 	int unit,
1288 	struct peer *peer	/* peer structure pointer */
1289 	)
1290 {
1291 	struct refclockproc *pp;
1292 
1293 	pp = peer->procptr;
1294 	pp->polls++;
1295 }
1296 
1297 
1298 /*
1299  * chu_second - process minute data
1300  */
1301 static void
1302 chu_second(
1303 	int unit,
1304 	struct peer *peer	/* peer structure pointer */
1305 	)
1306 {
1307 	struct refclockproc *pp;
1308 	struct chuunit *up;
1309 	l_fp	offset;
1310 	char	synchar, qual, leapchar;
1311 	int	minset, i;
1312 	double	dtemp;
1313 
1314 	pp = peer->procptr;
1315 	up = (struct chuunit *)pp->unitptr;
1316 
1317 	/*
1318 	 * This routine is called once per minute to process the
1319 	 * accumulated burst data. We do a bit of fancy footwork so that
1320 	 * this doesn't run while burst data are being accumulated.
1321 	 */
1322 	up->second = (up->second + 1) % 60;
1323 	if (up->second != 0)
1324 		return;
1325 
1326 	/*
1327 	 * Process the last burst, if still in the burst buffer.
1328 	 * If the minute contains a valid B frame with sufficient A
1329 	 * frame metric, it is considered valid. However, the timecode
1330 	 * is sent to clockstats even if invalid.
1331 	 */
1332 	chu_burst(peer);
1333 	minset = ((current_time - peer->update) + 30) / 60;
1334 	dtemp = chu_major(peer);
1335 	qual = 0;
1336 	if (up->status & (BFRAME | AFRAME))
1337 		qual |= SYNERR;
1338 	if (up->status & (BFORMAT | AFORMAT))
1339 		qual |= FMTERR;
1340 	if (up->status & DECODE)
1341 		qual |= DECERR;
1342 	if (up->status & STAMP)
1343 		qual |= TSPERR;
1344 	if (up->status & BVALID && dtemp >= MINMETRIC)
1345 		up->status |= INSYNC;
1346 	synchar = leapchar = ' ';
1347 	if (!(up->status & INSYNC)) {
1348 		pp->leap = LEAP_NOTINSYNC;
1349 		synchar = '?';
1350 	} else if (up->leap & 0x2) {
1351 		pp->leap = LEAP_ADDSECOND;
1352 		leapchar = 'L';
1353 	} else if (up->leap & 0x4) {
1354 		pp->leap = LEAP_DELSECOND;
1355 		leapchar = 'l';
1356 	} else {
1357 		pp->leap = LEAP_NOWARNING;
1358 	}
1359 	sprintf(pp->a_lastcode,
1360 	    "%c%1X %04d %03d %02d:%02d:%02d %c%x %+d %d %d %s %.0f %d",
1361 	    synchar, qual, pp->year, pp->day, pp->hour, pp->minute,
1362 	    pp->second, leapchar, up->dst, up->dut, minset, up->gain,
1363 	    up->ident, dtemp, up->ntstamp);
1364 	pp->lencode = strlen(pp->a_lastcode);
1365 
1366 	/*
1367 	 * If in sync and the signal metric is above threshold, the
1368 	 * timecode is ipso fatso valid and can be selected to
1369 	 * discipline the clock.
1370 	 */
1371 	if (up->status & INSYNC && !(up->status & (DECODE | STAMP)) &&
1372 	    dtemp > MINMETRIC) {
1373 		if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT,
1374 		    up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) {
1375 			up->errflg = CEVNT_BADTIME;
1376 		} else {
1377 			offset.l_uf = 0;
1378 			for (i = 0; i < up->ntstamp; i++)
1379 				refclock_process_offset(pp, offset,
1380 				up->tstamp[i], PDELAY +
1381 				    pp->fudgetime1);
1382 			pp->lastref = up->timestamp;
1383 			refclock_receive(peer);
1384 		}
1385 	}
1386 	if (dtemp > 0)
1387 		record_clock_stats(&peer->srcadr, pp->a_lastcode);
1388 #ifdef DEBUG
1389 	if (debug)
1390 		printf("chu: timecode %d %s\n", pp->lencode,
1391 		    pp->a_lastcode);
1392 #endif
1393 #ifdef ICOM
1394 	chu_newchan(peer, dtemp);
1395 #endif /* ICOM */
1396 	chu_clear(peer);
1397 	if (up->errflg)
1398 		refclock_report(peer, up->errflg);
1399 	up->errflg = 0;
1400 }
1401 
1402 
1403 /*
1404  * chu_major - majority decoder
1405  */
1406 static double
1407 chu_major(
1408 	struct peer *peer	/* peer structure pointer */
1409 	)
1410 {
1411 	struct refclockproc *pp;
1412 	struct chuunit *up;
1413 
1414 	u_char	code[11];	/* decoded timecode */
1415 	int	metric;		/* distance metric */
1416 	int	val1;		/* maximum distance */
1417 	int	synchar;	/* stray cat */
1418 	int	temp;
1419 	int	i, j, k;
1420 
1421 	pp = peer->procptr;
1422 	up = (struct chuunit *)pp->unitptr;
1423 
1424 	/*
1425 	 * Majority decoder. Each burst encodes two replications at each
1426 	 * digit position in the timecode. Each row of the decoding
1427 	 * matrix encodes the number of occurences of each digit found
1428 	 * at the corresponding position. The maximum over all
1429 	 * occurrences at each position is the distance for this
1430 	 * position and the corresponding digit is the maximum-
1431 	 * likelihood candidate. If the distance is not more than half
1432 	 * the total number of occurences, a majority has not been found
1433 	 * and the data are discarded. The decoding distance is defined
1434 	 * as the sum of the distances over the first nine digits. The
1435 	 * tenth digit varies over the seconds, so we don't count it.
1436 	 */
1437 	metric = 0;
1438 	for (i = 0; i < 9; i++) {
1439 		val1 = 0;
1440 		k = 0;
1441 		for (j = 0; j < 16; j++) {
1442 			temp = up->decode[i][j] + up->decode[i + 10][j];
1443 			if (temp > val1) {
1444 				val1 = temp;
1445 				k = j;
1446 			}
1447 		}
1448 		if (val1 <= up->burstcnt)
1449 			up->status |= DECODE;
1450 		metric += val1;
1451 		code[i] = hexchar[k];
1452 	}
1453 
1454 	/*
1455 	 * Compute the timecode timestamp from the days, hours and
1456 	 * minutes of the timecode. Use clocktime() for the aggregate
1457 	 * minutes and the minute offset computed from the burst
1458 	 * seconds. Note that this code relies on the filesystem time
1459 	 * for the years and does not use the years of the timecode.
1460 	 */
1461 	if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day,
1462 	    &pp->hour, &pp->minute) != 4)
1463 		up->status |= DECODE;
1464 	if (up->ntstamp < MINSTAMP)
1465 		up->status |= STAMP;
1466 	return (metric);
1467 }
1468 
1469 
1470 /*
1471  * chu_clear - clear decoding matrix
1472  */
1473 static void
1474 chu_clear(
1475 	struct peer *peer	/* peer structure pointer */
1476 	)
1477 {
1478 	struct refclockproc *pp;
1479 	struct chuunit *up;
1480 	int	i, j;
1481 
1482 	pp = peer->procptr;
1483 	up = (struct chuunit *)pp->unitptr;
1484 
1485 	/*
1486 	 * Clear stuff for the minute.
1487 	 */
1488 	up->ndx = up->prevsec = 0;
1489 	up->burstcnt = up->ntstamp = 0;
1490 	up->status &= INSYNC | METRIC;
1491 	for (i = 0; i < 20; i++) {
1492 		for (j = 0; j < 16; j++)
1493 			up->decode[i][j] = 0;
1494 	}
1495 }
1496 
1497 #ifdef ICOM
1498 /*
1499  * chu_newchan - called once per minute to find the best channel;
1500  * returns zero on success, nonzero if ICOM error.
1501  */
1502 static int
1503 chu_newchan(
1504 	struct peer *peer,
1505 	double	met
1506 	)
1507 {
1508 	struct chuunit *up;
1509 	struct refclockproc *pp;
1510 	struct xmtr *sp;
1511 	int	rval;
1512 	double	metric;
1513 	int	i;
1514 
1515 	pp = peer->procptr;
1516 	up = (struct chuunit *)pp->unitptr;
1517 
1518 	/*
1519 	 * The radio can be tuned to three channels: 0 (3330 kHz), 1
1520 	 * (7850 kHz) and 2 (14670 kHz). There are five one-minute
1521 	 * dwells in each cycle. During the first dwell the radio is
1522 	 * tuned to one of the three channels to measure the channel
1523 	 * metric. The channel is selected as the one least recently
1524 	 * measured. During the remaining four dwells the radio is tuned
1525 	 * to the channel with the highest channel metric.
1526 	 */
1527 	if (up->fd_icom <= 0)
1528 		return (0);
1529 
1530 	/*
1531 	 * Update the current channel metric and age of all channels.
1532 	 * Scan all channels for the highest metric.
1533 	 */
1534 	sp = &up->xmtr[up->chan];
1535 	sp->metric -= sp->integ[sp->iptr];
1536 	sp->integ[sp->iptr] = met;
1537 	sp->metric += sp->integ[sp->iptr];
1538 	sp->probe = 0;
1539 	sp->iptr = (sp->iptr + 1) % ISTAGE;
1540 	metric = 0;
1541 	for (i = 0; i < NCHAN; i++) {
1542 		up->xmtr[i].probe++;
1543 		if (up->xmtr[i].metric > metric) {
1544 			up->status |= METRIC;
1545 			metric = up->xmtr[i].metric;
1546 			up->chan = i;
1547 		}
1548 	}
1549 
1550 	/*
1551 	 * Start the next dwell. If the first dwell or no stations have
1552 	 * been heard, continue round-robin scan.
1553 	 */
1554 	up->dwell = (up->dwell + 1) % DWELL;
1555 	if (up->dwell == 0 || metric == 0) {
1556 		rval = 0;
1557 		for (i = 0; i < NCHAN; i++) {
1558 			if (up->xmtr[i].probe > rval) {
1559 				rval = up->xmtr[i].probe;
1560 				up->chan = i;
1561 			}
1562 		}
1563 	}
1564 
1565 	/* Retune the radio at each dwell in case somebody nudges the
1566 	 * tuning knob.
1567 	 */
1568 	rval = icom_freq(up->fd_icom, peer->ttl & 0x7f, qsy[up->chan] +
1569 	    TUNE);
1570 	sprintf(up->ident, "CHU%d", up->chan);
1571 	memcpy(&pp->refid, up->ident, 4);
1572 	memcpy(&peer->refid, up->ident, 4);
1573 	if (metric == 0 && up->status & METRIC) {
1574 		up->status &= ~METRIC;
1575 		refclock_report(peer, CEVNT_PROP);
1576 	}
1577 	return (rval);
1578 }
1579 #endif /* ICOM */
1580 
1581 
1582 /*
1583  * chu_dist - determine the distance of two octet arguments
1584  */
1585 static int
1586 chu_dist(
1587 	int	x,		/* an octet of bits */
1588 	int	y		/* another octet of bits */
1589 	)
1590 {
1591 	int	val;		/* bit count */
1592 	int	temp;
1593 	int	i;
1594 
1595 	/*
1596 	 * The distance is determined as the weight of the exclusive OR
1597 	 * of the two arguments. The weight is determined by the number
1598 	 * of one bits in the result. Each one bit increases the weight,
1599 	 * while each zero bit decreases it.
1600 	 */
1601 	temp = x ^ y;
1602 	val = 0;
1603 	for (i = 0; i < 8; i++) {
1604 		if ((temp & 0x1) == 0)
1605 			val++;
1606 		else
1607 			val--;
1608 		temp >>= 1;
1609 	}
1610 	return (val);
1611 }
1612 
1613 
1614 #ifdef HAVE_AUDIO
1615 /*
1616  * chu_gain - adjust codec gain
1617  *
1618  * This routine is called at the end of each second. During the second
1619  * the number of signal clips above the MAXAMP threshold (6000). If
1620  * there are no clips, the gain is bumped up; if there are more than
1621  * MAXCLP clips (100), it is bumped down. The decoder is relatively
1622  * insensitive to amplitude, so this crudity works just peachy. The
1623  * routine also jiggles the input port and selectively mutes the
1624  */
1625 static void
1626 chu_gain(
1627 	struct peer *peer	/* peer structure pointer */
1628 	)
1629 {
1630 	struct refclockproc *pp;
1631 	struct chuunit *up;
1632 
1633 	pp = peer->procptr;
1634 	up = (struct chuunit *)pp->unitptr;
1635 
1636 	/*
1637 	 * Apparently, the codec uses only the high order bits of the
1638 	 * gain control field. Thus, it may take awhile for changes to
1639 	 * wiggle the hardware bits.
1640 	 */
1641 	if (up->clipcnt == 0) {
1642 		up->gain += 4;
1643 		if (up->gain > MAXGAIN)
1644 			up->gain = MAXGAIN;
1645 	} else if (up->clipcnt > MAXCLP) {
1646 		up->gain -= 4;
1647 		if (up->gain < 0)
1648 			up->gain = 0;
1649 	}
1650 	audio_gain(up->gain, up->mongain, up->port);
1651 	up->clipcnt = 0;
1652 }
1653 #endif /* HAVE_AUDIO */
1654 
1655 
1656 #else
1657 int refclock_chu_bs;
1658 #endif /* REFCLOCK */
1659