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