xref: /freebsd/contrib/ntp/ntpd/refclock_irig.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
1 /*
2  * refclock_irig - audio IRIG-B/E demodulator/decoder
3  */
4 #ifdef HAVE_CONFIG_H
5 #include <config.h>
6 #endif
7 
8 #if defined(REFCLOCK) && defined(CLOCK_IRIG)
9 
10 #include <stdio.h>
11 #include <ctype.h>
12 #include <sys/time.h>
13 #include <math.h>
14 #ifdef HAVE_SYS_IOCTL_H
15 #include <sys/ioctl.h>
16 #endif /* HAVE_SYS_IOCTL_H */
17 
18 #include "ntpd.h"
19 #include "ntp_io.h"
20 #include "ntp_refclock.h"
21 #include "ntp_calendar.h"
22 #include "ntp_stdlib.h"
23 #include "audio.h"
24 
25 /*
26  * Audio IRIG-B/E demodulator/decoder
27  *
28  * This driver receives, demodulates and decodes IRIG-B/E signals when
29  * connected to the audio codec /dev/audio. The IRIG signal format is an
30  * amplitude-modulated carrier with pulse-width modulated data bits. For
31  * IRIG-B, the carrier frequency is 1000 Hz and bit rate 100 b/s; for
32  * IRIG-E, the carrier frequenchy is 100 Hz and bit rate 10 b/s. The
33  * driver automatically recognizes which format is in use.
34  *
35  * The program processes 8000-Hz mu-law companded samples using separate
36  * signal filters for IRIG-B and IRIG-E, a comb filter, envelope
37  * detector and automatic threshold corrector. Cycle crossings relative
38  * to the corrected slice level determine the width of each pulse and
39  * its value - zero, one or position identifier. The data encode 20 BCD
40  * digits which determine the second, minute, hour and day of the year
41  * and sometimes the year and synchronization condition. The comb filter
42  * exponentially averages the corresponding samples of successive baud
43  * intervals in order to reliably identify the reference carrier cycle.
44  * A type-II phase-lock loop (PLL) performs additional integration and
45  * interpolation to accurately determine the zero crossing of that
46  * cycle, which determines the reference timestamp. A pulse-width
47  * discriminator demodulates the data pulses, which are then encoded as
48  * the BCD digits of the timecode.
49  *
50  * The timecode and reference timestamp are updated once each second
51  * with IRIG-B (ten seconds with IRIG-E) and local clock offset samples
52  * saved for later processing. At poll intervals of 64 s, the saved
53  * samples are processed by a trimmed-mean filter and used to update the
54  * system clock.
55  *
56  * An automatic gain control feature provides protection against
57  * overdriven or underdriven input signal amplitudes. It is designed to
58  * maintain adequate demodulator signal amplitude while avoiding
59  * occasional noise spikes. In order to assure reliable capture, the
60  * decompanded input signal amplitude must be greater than 100 units and
61  * the codec sample frequency error less than 250 PPM (.025 percent).
62  *
63  * The program performs a number of error checks to protect against
64  * overdriven or underdriven input signal levels, incorrect signal
65  * format or improper hardware configuration. Specifically, if any of
66  * the following errors occur for a time measurement, the data are
67  * rejected.
68  *
69  * o The peak carrier amplitude is less than DRPOUT (100). This usually
70  *   means dead IRIG signal source, broken cable or wrong input port.
71  *
72  * o The frequency error is greater than MAXFREQ +-250 PPM (.025%). This
73  *   usually means broken codec hardware or wrong codec configuration.
74  *
75  * o The modulation index is less than MODMIN (0.5). This usually means
76  *   overdriven IRIG signal or wrong IRIG format.
77  *
78  * o A frame synchronization error has occurred. This usually means wrong
79  *   IRIG signal format or the IRIG signal source has lost
80  *   synchronization (signature control).
81  *
82  * o A data decoding error has occurred. This usually means wrong IRIG
83  *   signal format.
84  *
85  * o The current second of the day is not exactly one greater than the
86  *   previous one. This usually means a very noisy IRIG signal or
87  *   insufficient CPU resources.
88  *
89  * o An audio codec error (overrun) occurred. This usually means
90  *   insufficient CPU resources, as sometimes happens with Sun SPARC
91  *   IPCs when doing something useful.
92  *
93  * Note that additional checks are done elsewhere in the reference clock
94  * interface routines.
95  *
96  * Debugging aids
97  *
98  * The timecode format used for debugging and data recording includes
99  * data helpful in diagnosing problems with the IRIG signal and codec
100  * connections. With debugging enabled (-d -d -d on the ntpd command
101  * line), the driver produces one line for each timecode in the
102  * following format:
103  *
104  * 00 1 98 23 19:26:52 721 143 0.694 47 20 0.083 66.5 3094572411.00027
105  *
106  * The most recent line is also written to the clockstats file at 64-s
107  * intervals.
108  *
109  * The first field contains the error flags in hex, where the hex bits
110  * are interpreted as below. This is followed by the IRIG status
111  * indicator, year of century, day of year and time of day. The status
112  * indicator and year are not produced by some IRIG devices. Following
113  * these fields are the signal amplitude (0-8100), codec gain (0-255),
114  * field phase (0-79), time constant (2-20), modulation index (0-1),
115  * carrier phase error (0+-0.5) and carrier frequency error (PPM). The
116  * last field is the on-time timestamp in NTP format.
117  *
118  * The fraction part of the on-time timestamp is a good indicator of how
119  * well the driver is doing. With an UltrSPARC 30, this thing can keep
120  * the clock within a few tens of microseconds relative to the IRIG-B
121  * signal. Accuracy with IRIG-E is about ten times worse.
122  *
123  * Unlike other drivers, which can have multiple instantiations, this
124  * one supports only one. It does not seem likely that more than one
125  * audio codec would be useful in a single machine. More than one would
126  * probably chew up too much CPU time anyway.
127  *
128  * Fudge factors
129  *
130  * Fudge flag2 selects the audio input port, where 0 is the mike port
131  * (default) and 1 is the line-in port. It does not seem useful to
132  * select the compact disc player port. Fudge flag3 enables audio
133  * monitoring of the input signal. For this purpose, the speaker volume
134  * must be set before the driver is started. Fudge flag4 causes the
135  * debugging output described above to be recorded in the clockstats
136  * file. Any of these flags can be changed during operation with the
137  * ntpdc program.
138  */
139 
140 /*
141  * Interface definitions
142  */
143 #define	PRECISION	(-17)	/* precision assumed (about 10 us) */
144 #define	REFID		"IRIG"	/* reference ID */
145 #define	DESCRIPTION	"Generic IRIG Audio Driver" /* WRU */
146 
147 #define SECOND		8000	/* nominal sample rate (Hz) */
148 #define BAUD		80	/* samples per baud interval */
149 #define OFFSET		128	/* companded sample offset */
150 #define SIZE		256	/* decompanding table size */
151 #define CYCLE		8	/* samples per carrier cycle */
152 #define SUBFLD		10	/* bits per subfield */
153 #define FIELD		10	/* subfields per field */
154 #define MINTC		2	/* min PLL time constant */
155 #define MAXTC		20	/* max PLL time constant max */
156 #define	MAXSIG		6000.	/* maximum signal level */
157 #define DRPOUT		100.	/* dropout signal level */
158 #define MODMIN		0.5	/* minimum modulation index */
159 #define MAXFREQ		(250e-6 * SECOND) /* freq tolerance (.025%) */
160 #define PI		3.1415926535 /* the real thing */
161 
162 /*
163  * Experimentally determined fudge factors
164  */
165 #define IRIG_B		.0019		/* IRIG-B phase delay */
166 #define IRIG_E		.0019		/* IRIG-E phase delay */
167 
168 /*
169  * Data bit definitions
170  */
171 #define BIT0		0	/* zero */
172 #define BIT1		1	/* one */
173 #define BITP		2	/* position identifier */
174 
175 /*
176  * Error flags (up->errflg)
177  */
178 #define IRIG_ERR_AMP	0x01	/* low carrier amplitude */
179 #define IRIG_ERR_FREQ	0x02	/* frequency tolerance exceeded */
180 #define IRIG_ERR_MOD	0x04	/* low modulation index */
181 #define IRIG_ERR_SYNCH	0x08	/* frame synch error */
182 #define IRIG_ERR_DECODE	0x10	/* frame decoding error */
183 #define IRIG_ERR_CHECK	0x20	/* second numbering discrepancy */
184 #define IRIG_ERR_ERROR	0x40	/* codec error (overrun) */
185 
186 /*
187  * IRIG unit control structure
188  */
189 struct irigunit {
190 	u_char	timecode[21];	/* timecode string */
191 	l_fp	timestamp;	/* audio sample timestamp */
192 	l_fp	tick;		/* audio sample increment */
193 	double	comp[SIZE];	/* decompanding table */
194 	double	integ[BAUD];	/* baud integrator */
195 	double	phase, freq;	/* logical clock phase and frequency */
196 	double	zxing;		/* phase detector integrator */
197 	double	yxing;		/* phase detector display */
198 	double	modndx;		/* modulation index */
199 	double	irig_b;		/* IRIG-B signal amplitude */
200 	double	irig_e;		/* IRIG-E signal amplitude */
201 	int	errflg;		/* error flags */
202 	int	bufcnt;		/* samples in buffer */
203 	int	bufptr;		/* buffer index pointer */
204 	int	pollcnt;	/* poll counter */
205 	int	port;		/* codec port */
206 	int	gain;		/* codec gain */
207 	int	clipcnt;	/* sample clipped count */
208 	int	seccnt;		/* second interval counter */
209 	int	decim;		/* sample decimation factor */
210 
211 	/*
212 	 * RF variables
213 	 */
214 	double	hpf[5];		/* IRIG-B filter shift register */
215 	double	lpf[5];		/* IRIG-E filter shift register */
216 	double	intmin, intmax;	/* integrated envelope min and max */
217 	double	envmax;		/* peak amplitude */
218 	double	envmin;		/* noise amplitude */
219 	double	maxsignal;	/* integrated peak amplitude */
220 	double	noise;		/* integrated noise amplitude */
221 	double	lastenv[CYCLE];	/* last cycle amplitudes */
222 	double	lastint[CYCLE];	/* last integrated cycle amplitudes */
223 	double	lastsig;	/* last carrier sample */
224 	double	xxing;		/* phase detector interpolated output */
225 	double	fdelay;		/* filter delay */
226 	int	envphase;	/* envelope phase */
227 	int	envptr;		/* envelope phase pointer */
228 	int	carphase;	/* carrier phase */
229 	int	envsw;		/* envelope state */
230 	int	envxing;	/* envelope slice crossing */
231 	int	tc;		/* time constant */
232 	int	tcount;		/* time constant counter */
233 	int	badcnt;		/* decimation interval counter */
234 
235 	/*
236 	 * Decoder variables
237 	 */
238 	l_fp	montime;	/* reference timestamp for eyeball */
239 	int	timecnt;	/* timecode counter */
240 	int	pulse;		/* cycle counter */
241 	int	cycles;		/* carrier cycles */
242 	int	dcycles;	/* data cycles */
243 	int	xptr;		/* translate table pointer */
244 	int	lastbit;	/* last code element length */
245 	int	second;		/* previous second */
246 	int	fieldcnt;	/* subfield count in field */
247 	int	bits;		/* demodulated bits */
248 	int	bitcnt;		/* bit count in subfield */
249 };
250 
251 /*
252  * Function prototypes
253  */
254 static	int	irig_start	P((int, struct peer *));
255 static	void	irig_shutdown	P((int, struct peer *));
256 static	void	irig_receive	P((struct recvbuf *));
257 static	void	irig_poll	P((int, struct peer *));
258 
259 /*
260  * More function prototypes
261  */
262 static	void	irig_base	P((struct peer *, double));
263 static	void	irig_rf		P((struct peer *, double));
264 static	void	irig_decode	P((struct peer *, int));
265 static	void	irig_gain	P((struct peer *));
266 
267 /*
268  * Transfer vector
269  */
270 struct	refclock refclock_irig = {
271 	irig_start,		/* start up driver */
272 	irig_shutdown,		/* shut down driver */
273 	irig_poll,		/* transmit poll message */
274 	noentry,		/* not used (old irig_control) */
275 	noentry,		/* initialize driver (not used) */
276 	noentry,		/* not used (old irig_buginfo) */
277 	NOFLAGS			/* not used */
278 };
279 
280 /*
281  * Global variables
282  */
283 static char	hexchar[] = {	/* really quick decoding table */
284 	'0', '8', '4', 'c',		/* 0000 0001 0010 0011 */
285 	'2', 'a', '6', 'e',		/* 0100 0101 0110 0111 */
286 	'1', '9', '5', 'd',		/* 1000 1001 1010 1011 */
287 	'3', 'b', '7', 'f'		/* 1100 1101 1110 1111 */
288 };
289 
290 
291 /*
292  * irig_start - open the devices and initialize data for processing
293  */
294 static int
295 irig_start(
296 	int	unit,		/* instance number (not used) */
297 	struct peer *peer	/* peer structure pointer */
298 	)
299 {
300 	struct refclockproc *pp;
301 	struct irigunit *up;
302 
303 	/*
304 	 * Local variables
305 	 */
306 	int	fd;		/* file descriptor */
307 	int	i;		/* index */
308 	double	step;		/* codec adjustment */
309 
310 	/*
311 	 * Open audio device
312 	 */
313 	fd = audio_init();
314 	if (fd < 0)
315 		return (0);
316 #ifdef DEBUG
317 	if (debug)
318 		audio_show();
319 #endif
320 
321 	/*
322 	 * Allocate and initialize unit structure
323 	 */
324 	if (!(up = (struct irigunit *)
325 	      emalloc(sizeof(struct irigunit)))) {
326 		(void) close(fd);
327 		return (0);
328 	}
329 	memset((char *)up, 0, sizeof(struct irigunit));
330 	pp = peer->procptr;
331 	pp->unitptr = (caddr_t)up;
332 	pp->io.clock_recv = irig_receive;
333 	pp->io.srcclock = (caddr_t)peer;
334 	pp->io.datalen = 0;
335 	pp->io.fd = fd;
336 	if (!io_addclock(&pp->io)) {
337 		(void)close(fd);
338 		free(up);
339 		return (0);
340 	}
341 
342 	/*
343 	 * Initialize miscellaneous variables
344 	 */
345 	peer->precision = PRECISION;
346 	pp->clockdesc = DESCRIPTION;
347 	memcpy((char *)&pp->refid, REFID, 4);
348 	up->tc = MINTC;
349 	up->decim = 1;
350 	up->fdelay = IRIG_B;
351 	up->gain = 127;
352 	up->pollcnt = 2;
353 
354 	/*
355 	 * The companded samples are encoded sign-magnitude. The table
356 	 * contains all the 256 values in the interest of speed.
357 	 */
358 	up->comp[0] = up->comp[OFFSET] = 0.;
359 	up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
360 	up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
361 	step = 2.;
362 	for (i = 3; i < OFFSET; i++) {
363 		up->comp[i] = up->comp[i - 1] + step;
364 		up->comp[OFFSET + i] = -up->comp[i];
365                 if (i % 16 == 0)
366 		    step *= 2.;
367 	}
368 	DTOLFP(1. / SECOND, &up->tick);
369 	return (1);
370 }
371 
372 
373 /*
374  * irig_shutdown - shut down the clock
375  */
376 static void
377 irig_shutdown(
378 	int	unit,		/* instance number (not used) */
379 	struct peer *peer	/* peer structure pointer */
380 	)
381 {
382 	struct refclockproc *pp;
383 	struct irigunit *up;
384 
385 	pp = peer->procptr;
386 	up = (struct irigunit *)pp->unitptr;
387 	io_closeclock(&pp->io);
388 	free(up);
389 }
390 
391 
392 /*
393  * irig_receive - receive data from the audio device
394  *
395  * This routine reads input samples and adjusts the logical clock to
396  * track the irig clock by dropping or duplicating codec samples.
397  */
398 static void
399 irig_receive(
400 	struct recvbuf *rbufp	/* receive buffer structure pointer */
401 	)
402 {
403 	struct peer *peer;
404 	struct refclockproc *pp;
405 	struct irigunit *up;
406 
407 	/*
408 	 * Local variables
409 	 */
410 	double	sample;		/* codec sample */
411 	u_char	*dpt;		/* buffer pointer */
412 	l_fp	ltemp;		/* l_fp temp */
413 
414 	peer = (struct peer *)rbufp->recv_srcclock;
415 	pp = peer->procptr;
416 	up = (struct irigunit *)pp->unitptr;
417 
418 	/*
419 	 * Main loop - read until there ain't no more. Note codec
420 	 * samples are bit-inverted.
421 	 */
422 	up->timestamp = rbufp->recv_time;
423 	up->bufcnt = rbufp->recv_length;
424 	DTOLFP((double)up->bufcnt / SECOND, &ltemp);
425 	L_SUB(&up->timestamp, &ltemp);
426 	dpt = rbufp->recv_buffer;
427 	for (up->bufptr = 0; up->bufptr < up->bufcnt; up->bufptr++) {
428 		sample = up->comp[~*dpt++ & 0xff];
429 
430 		/*
431 		 * Clip noise spikes greater than MAXSIG. If no clips,
432 		 * increase the gain a tad; if the clips are too high,
433 		 * decrease a tad. Choose either IRIG-B or IRIG-E
434 		 * according to the energy at the respective filter
435 		 * output.
436 		 */
437 		if (sample > MAXSIG) {
438 			sample = MAXSIG;
439 			up->clipcnt++;
440 		} else if (sample < -MAXSIG) {
441 			sample = -MAXSIG;
442 			up->clipcnt++;
443 		}
444 
445 		/*
446 		 * Variable frequency oscillator. A phase change of one
447 		 * unit produces a change of 360 degrees; a frequency
448 		 * change of one unit produces a change of 1 Hz.
449 		 */
450 		up->phase += up->freq / SECOND;
451 		if (up->phase >= .5) {
452 			up->phase -= 1.;
453 		} else if (up->phase < -.5) {
454 			up->phase += 1.;
455 			irig_rf(peer, sample);
456 			irig_rf(peer, sample);
457 		} else {
458 			irig_rf(peer, sample);
459 		}
460 		L_ADD(&up->timestamp, &up->tick);
461 
462 		/*
463 		 * Once each second, determine the IRIG format, codec
464 		 * port and gain.
465 		 */
466 		up->seccnt = (up->seccnt + 1) % SECOND;
467 		if (up->seccnt == 0) {
468 			if (up->irig_b > up->irig_e) {
469 				up->decim = 1;
470 				up->fdelay = IRIG_B;
471 			} else {
472 				up->decim = 10;
473 				up->fdelay = IRIG_E;
474 			}
475 			if (pp->sloppyclockflag & CLK_FLAG2)
476 			    up->port = 2;
477 			else
478 			    up->port = 1;
479 			irig_gain(peer);
480 			up->irig_b = up->irig_e = 0;
481 		}
482 	}
483 
484 	/*
485 	 * Squawk to the monitor speaker if enabled.
486 	 */
487 	if (pp->sloppyclockflag & CLK_FLAG3)
488 	    if (write(pp->io.fd, (u_char *)&rbufp->recv_space,
489 		      (u_int)up->bufcnt) < 0)
490 		perror("irig:");
491 }
492 
493 /*
494  * irig_rf - RF processing
495  *
496  * This routine filters the RF signal using a highpass filter for IRIG-B
497  * and a lowpass filter for IRIG-E. In case of IRIG-E, the samples are
498  * decimated by a factor of ten. The lowpass filter functions also as a
499  * decimation filter in this case. Note that the codec filters function
500  * as roofing filters to attenuate both the high and low ends of the
501  * passband. IIR filter coefficients were determined using Matlab Signal
502  * Processing Toolkit.
503  */
504 static void
505 irig_rf(
506 	struct peer *peer,	/* peer structure pointer */
507 	double	sample		/* current signal sample */
508 	)
509 {
510 	struct refclockproc *pp;
511 	struct irigunit *up;
512 
513 	/*
514 	 * Local variables
515 	 */
516 	double	irig_b, irig_e;	/* irig filter outputs */
517 
518 	pp = peer->procptr;
519 	up = (struct irigunit *)pp->unitptr;
520 
521 	/*
522 	 * IRIG-B filter. 4th-order elliptic, 800-Hz highpass, 0.3 dB
523 	 * passband ripple, -50 dB stopband ripple, phase delay -.0022
524 	 * s)
525 	 */
526 	irig_b = (up->hpf[4] = up->hpf[3]) * 2.322484e-01;
527 	irig_b += (up->hpf[3] = up->hpf[2]) * -1.103929e+00;
528 	irig_b += (up->hpf[2] = up->hpf[1]) * 2.351081e+00;
529 	irig_b += (up->hpf[1] = up->hpf[0]) * -2.335036e+00;
530 	up->hpf[0] = sample - irig_b;
531 	irig_b = up->hpf[0] * 4.335855e-01
532 	    + up->hpf[1] * -1.695859e+00
533 	    + up->hpf[2] * 2.525004e+00
534 	    + up->hpf[3] * -1.695859e+00
535 	    + up->hpf[4] * 4.335855e-01;
536 	up->irig_b += irig_b * irig_b;
537 
538 	/*
539 	 * IRIG-E filter. 4th-order elliptic, 130-Hz lowpass, 0.3 dB
540 	 * passband ripple, -50 dB stopband ripple, phase delay .0219 s.
541 	 */
542 	irig_e = (up->lpf[4] = up->lpf[3]) * 8.694604e-01;
543 	irig_e += (up->lpf[3] = up->lpf[2]) * -3.589893e+00;
544 	irig_e += (up->lpf[2] = up->lpf[1]) * 5.570154e+00;
545 	irig_e += (up->lpf[1] = up->lpf[0]) * -3.849667e+00;
546 	up->lpf[0] = sample - irig_e;
547 	irig_e = up->lpf[0] * 3.215696e-03
548 	    + up->lpf[1] * -1.174951e-02
549 	    + up->lpf[2] * 1.712074e-02
550 	    + up->lpf[3] * -1.174951e-02
551 	    + up->lpf[4] * 3.215696e-03;
552 	up->irig_e += irig_e * irig_e;
553 
554 	/*
555 	 * Decimate by a factor of either 1 (IRIG-B) or 10 (IRIG-E).
556 	 */
557 	up->badcnt = (up->badcnt + 1) % up->decim;
558 	if (up->badcnt == 0) {
559 		if (up->decim == 1)
560 		    irig_base(peer, irig_b);
561 		else
562 		    irig_base(peer, irig_e);
563 	}
564 }
565 
566 /*
567  * irig_base - baseband processing
568  *
569  * This routine processes the baseband signal and demodulates the AM
570  * carrier using a synchronous detector. It then synchronizes to the
571  * data frame at the baud rate and decodes the data pulses.
572  */
573 static void
574 irig_base(
575 	struct peer *peer,	/* peer structure pointer */
576 	double	sample		/* current signal sample */
577 	)
578 {
579 	struct refclockproc *pp;
580 	struct irigunit *up;
581 
582 	/*
583 	 * Local variables
584 	 */
585 	double	lope;		/* integrator output */
586 	double	env;		/* envelope detector output */
587 	double	dtemp;		/* double temp */
588 	int	i;		/* index temp */
589 
590 	pp = peer->procptr;
591 	up = (struct irigunit *)pp->unitptr;
592 
593 	/*
594 	 * Synchronous baud integrator. Corresponding samples of current
595 	 * and past baud intervals are integrated to refine the envelope
596 	 * amplitude and phase estimate. We keep one cycle of both the
597 	 * raw and integrated data for later use.
598 	 */
599 	up->envphase = (up->envphase + 1) % BAUD;
600 	up->carphase = (up->carphase + 1) % CYCLE;
601 	up->integ[up->envphase] += (sample - up->integ[up->envphase]) /
602 	    (5 * up->tc);
603 	lope = up->integ[up->envphase];
604 	up->lastenv[up->carphase] = sample;
605 	up->lastint[up->carphase] = lope;
606 
607 	/*
608 	 * Phase detector. Sample amplitudes are integrated over the
609 	 * baud interval. Cycle phase is determined from these
610 	 * amplitudes using an eight-sample cyclic buffer. A phase
611 	 * change of 360 degrees produces an output change of one unit.
612 	 */
613 	if (up->lastsig > 0 && lope <= 0) {
614 		up->xxing = lope / (up->lastsig - lope);
615 		up->zxing += (up->carphase - 4 + up->xxing) / 8.;
616 	}
617 	up->lastsig = lope;
618 
619 	/*
620 	 * Update signal/noise estimates and PLL phase/frequency.
621 	 */
622 	if (up->envphase == 0) {
623 
624 		/*
625 		 * Update envelope signal and noise estimates and mess
626 		 * with error bits.
627 		 */
628 		up->maxsignal = up->intmax;
629 		up->noise = up->intmin;
630 		if (up->maxsignal < DRPOUT)
631 		    up->errflg |= IRIG_ERR_AMP;
632 		if (up->intmax > 0)
633 		    up->modndx = (up->intmax - up->intmin) / up->intmax;
634  		else
635 		    up->modndx = 0;
636 		if (up->modndx < MODMIN)
637 		    up->errflg |= IRIG_ERR_MOD;
638 		up->intmin = 1e6; up->intmax = 0;
639 		if (up->errflg & (IRIG_ERR_AMP | IRIG_ERR_FREQ |
640 				  IRIG_ERR_MOD | IRIG_ERR_SYNCH)) {
641 			up->tc = MINTC;
642 			up->tcount = 0;
643 		}
644 
645 		/*
646 		 * Update PLL phase and frequency. The PLL time constant
647 		 * is set initially to stabilize the frequency within a
648 		 * minute or two, then increases to the maximum. The
649 		 * frequency is clamped so that the PLL capture range
650 		 * cannot be exceeded.
651 		 */
652 		dtemp = up->zxing * up->decim / BAUD;
653 		up->yxing = dtemp;
654 		up->zxing = 0.;
655 		up->phase += dtemp / up->tc;
656 		up->freq += dtemp / (4. * up->tc * up->tc);
657 		if (up->freq > MAXFREQ) {
658 			up->freq = MAXFREQ;
659 			up->errflg |= IRIG_ERR_FREQ;
660 		} else if (up->freq < -MAXFREQ) {
661 			up->freq = -MAXFREQ;
662 			up->errflg |= IRIG_ERR_FREQ;
663 		}
664 	}
665 
666 	/*
667 	 * Synchronous demodulator. There are eight samples in the cycle
668 	 * and ten cycles in the baud interval. The amplitude of each
669 	 * cycle is determined at the last sample in the cycle. The
670 	 * beginning of the data pulse is determined from the integrated
671 	 * samples, while the end of the pulse is determined from the
672 	 * raw samples. The raw data bits are demodulated relative to
673 	 * the slice level and left-shifted in the decoding register.
674 	 */
675 	if (up->carphase != 7)
676 	    return;
677 	env = (up->lastenv[2] - up->lastenv[6]) / 2.;
678 	lope = (up->lastint[2] - up->lastint[6]) / 2.;
679 	if (lope > up->intmax)
680 	    up->intmax = lope;
681 	if (lope < up->intmin)
682 	    up->intmin = lope;
683 
684 	/*
685 	 * Pulse code demodulator and reference timestamp. The decoder
686 	 * looks for a sequence of ten bits; the first two bits must be
687 	 * one, the last two bits must be zero. Frame synch is asserted
688 	 * when three correct frames have been found.
689 	 */
690 	up->pulse = (up->pulse + 1) % 10;
691 	if (up->pulse == 1)
692 	    up->envmax = env;
693 	else if (up->pulse == 9)
694 	    up->envmin = env;
695 	up->dcycles <<= 1;
696 	if (env >= (up->envmax + up->envmin) / 2.)
697 	    up->dcycles |= 1;
698 	up->cycles <<= 1;
699 	if (lope >= (up->maxsignal + up->noise) / 2.)
700 	    up->cycles |= 1;
701 	if ((up->cycles & 0x303c0f03) == 0x300c0300) {
702 		l_fp ltemp;
703 		int bitz;
704 
705 		/*
706 		 * The PLL time constant starts out small, in order to
707 		 * sustain a frequency tolerance of 250 PPM. It
708 		 * gradually increases as the loop settles down. Note
709 		 * that small wiggles are not believed, unless they
710 		 * persist for lots of samples.
711 		 */
712 		if (up->pulse != 9)
713 		    up->errflg |= IRIG_ERR_SYNCH;
714 		up->pulse = 9;
715 		dtemp = BAUD - up->zxing;
716 		i = up->envxing - up->envphase;
717 		if (i < 0)
718 		    i -= i;
719 		if (i <= 1) {
720 			up->tcount++;
721 			if (up->tcount > 50 * up->tc) {
722 				up->tc++;
723 				if (up->tc > MAXTC)
724 				    up->tc = MAXTC;
725 				up->tcount = 0;
726 				up->envxing = up->envphase;
727 			} else {
728 				dtemp -= up->envxing - up->envphase;
729 			}
730 		} else {
731 			up->tcount = 0;
732 			up->envxing = up->envphase;
733 		}
734 
735 		/*
736 		 * Determine a reference timestamp, accounting for the
737 		 * codec delay and filter delay. Note the timestamp is
738 		 * for the previous frame, so we have to backtrack for
739 		 * this plus the delay since the last carrier positive
740 		 * zero crossing.
741 		 */
742 		DTOLFP(up->decim * (dtemp / SECOND + 1.) + up->fdelay,
743 		       &ltemp);
744 		pp->lastrec = up->timestamp;
745 		L_SUB(&pp->lastrec, &ltemp);
746 
747 		/*
748 		 * The data bits are collected in ten-bit frames. The
749 		 * first two and last two bits are determined by frame
750 		 * sync and ignored here; the resulting patterns
751 		 * represent zero (0-1 bits), one (2-4 bits) and
752 		 * position identifier (5-6 bits). The remaining
753 		 * patterns represent errors and are treated as zeros.
754 		 */
755 		bitz = up->dcycles & 0xfc;
756 		switch(bitz) {
757 
758 		    case 0x00:
759 		    case 0x80:
760 			irig_decode(peer, BIT0);
761 			break;
762 
763 		    case 0xc0:
764 		    case 0xe0:
765 		    case 0xf0:
766 			irig_decode(peer, BIT1);
767 			break;
768 
769 		    case 0xf8:
770 		    case 0xfc:
771 			irig_decode(peer, BITP);
772 			break;
773 
774 		    default:
775 			irig_decode(peer, 0);
776 			up->errflg |= IRIG_ERR_DECODE;
777 		}
778 	}
779 }
780 
781 
782 /*
783  * irig_decode - decode the data
784  *
785  * This routine assembles bits into digits, digits into subfields and
786  * subfields into the timecode field. Bits can have values of zero, one
787  * or position identifier. There are four bits per digit, two digits per
788  * subfield and ten subfields per field. The last bit in every subfield
789  * and the first bit in the first subfield are position identifiers.
790  */
791 static void
792 irig_decode(
793 	struct	peer *peer,	/* peer structure pointer */
794 	int	bit		/* data bit (0, 1 or 2) */
795 	)
796 {
797 	struct refclockproc *pp;
798 	struct irigunit *up;
799 
800 	/*
801 	 * Local variables
802 	 */
803 	char	syncchar;	/* sync character (Spectracom only) */
804 	char	sbs[6];		/* binary seconds since 0h */
805 	char	spare[2];	/* mulligan digits */
806 
807         pp = peer->procptr;
808 	up = (struct irigunit *)pp->unitptr;
809 
810 	/*
811 	 * Assemble subfield bits.
812 	 */
813 	up->bits <<= 1;
814 	if (bit == BIT1) {
815 		up->bits |= 1;
816 	} else if (bit == BITP && up->lastbit == BITP) {
817 
818 		/*
819 		 * Frame sync - two adjacent position identifiers.
820 		 * Monitor the reference timestamp and wiggle the
821 		 * clock, but only if no errors have occurred.
822 		 */
823 		up->bitcnt = 1;
824 		up->fieldcnt = 0;
825 		up->lastbit = 0;
826 		up->montime = pp->lastrec;
827 		if (up->errflg == 0) {
828 			up->timecnt++;
829 			refclock_process(pp);
830 		}
831 		if (up->timecnt >= MAXSTAGE) {
832 			refclock_receive(peer);
833 			up->timecnt = 0;
834 			up->pollcnt = 2;
835 		}
836 		up->errflg = 0;
837 	}
838 	up->bitcnt = (up->bitcnt + 1) % SUBFLD;
839 	if (up->bitcnt == 0) {
840 
841 		/*
842 		 * End of subfield. Encode two hexadecimal digits in
843 		 * little-endian timecode field.
844 		 */
845 		if (up->fieldcnt == 0)
846 		    up->bits <<= 1;
847 		if (up->xptr < 2)
848 		    up->xptr = 2 * FIELD;
849 		up->timecode[--up->xptr] = hexchar[(up->bits >> 5) &
850 						  0xf];
851 		up->timecode[--up->xptr] = hexchar[up->bits & 0xf];
852 		up->fieldcnt = (up->fieldcnt + 1) % FIELD;
853 		if (up->fieldcnt == 0) {
854 
855 			/*
856 			 * End of field. Decode the timecode, adjust the
857 			 * gain and set the input port. Set the port
858 			 * here on the assumption somebody might even
859 			 * change it on-wing.
860 			 */
861 			up->xptr = 2 * FIELD;
862 			if (sscanf((char *)up->timecode,
863 				   "%6s%2d%c%2s%3d%2d%2d%2d",
864 				   sbs, &pp->year, &syncchar, spare, &pp->day,
865 				   &pp->hour, &pp->minute, &pp->second) != 8)
866 			    pp->leap = LEAP_NOTINSYNC;
867 			else
868 			    pp->leap = LEAP_NOWARNING;
869 			up->second = (up->second + up->decim) % 60;
870 			if (pp->second != up->second)
871 			    up->errflg |= IRIG_ERR_CHECK;
872 			up->second = pp->second;
873 			sprintf(pp->a_lastcode,
874 				"%02x %c %2d %3d %02d:%02d:%02d %4.0f %3d %6.3f %2d %2d %6.3f %6.1f %s",
875 				up->errflg, syncchar, pp->year, pp->day,
876 				pp->hour, pp->minute, pp->second,
877 				up->maxsignal, up->gain, up->modndx,
878 				up->envxing, up->tc, up->yxing, up->freq *
879 				1e6 / SECOND, ulfptoa(&up->montime, 6));
880 			pp->lencode = strlen(pp->a_lastcode);
881 			if (up->timecnt == 0 || pp->sloppyclockflag &
882 			    CLK_FLAG4)
883 			    record_clock_stats(&peer->srcadr,
884 					       pp->a_lastcode);
885 #ifdef DEBUG
886 			if (debug > 2)
887 			    printf("irig: %s\n", pp->a_lastcode);
888 #endif /* DEBUG */
889 		}
890 	}
891 	up->lastbit = bit;
892 }
893 
894 
895 /*
896  * irig_poll - called by the transmit procedure
897  *
898  * This routine keeps track of status. If nothing is heard for two
899  * successive poll intervals, a timeout event is declared and any
900  * orphaned timecode updates are sent to foster care.
901  */
902 static void
903 irig_poll(
904 	int	unit,		/* instance number (not used) */
905 	struct peer *peer	/* peer structure pointer */
906 	)
907 {
908 	struct refclockproc *pp;
909 	struct irigunit *up;
910 
911 	pp = peer->procptr;
912 	up = (struct irigunit *)pp->unitptr;
913 
914 	/*
915 	 * Keep book for tattletales
916 	 */
917 	if (up->pollcnt == 0) {
918 		refclock_report(peer, CEVNT_TIMEOUT);
919 		up->timecnt = 0;
920 		return;
921 	}
922 	up->pollcnt--;
923 	pp->polls++;
924 
925 }
926 
927 
928 /*
929  * irig_gain - adjust codec gain
930  *
931  * This routine is called once each second. If the signal envelope
932  * amplitude is too low, the codec gain is bumped up by four units; if
933  * too high, it is bumped down. The decoder is relatively insensitive to
934  * amplitude, so this crudity works just fine. The input port is set and
935  * the error flag is cleared, mostly to be ornery.
936  */
937 static void
938 irig_gain(
939 	struct peer *peer	/* peer structure pointer */
940 	)
941 {
942 	struct refclockproc *pp;
943 	struct irigunit *up;
944 
945 	pp = peer->procptr;
946 	up = (struct irigunit *)pp->unitptr;
947 
948 	/*
949 	 * Apparently, the codec uses only the high order bits of the
950 	 * gain control field. Thus, it may take awhile for changes to
951 	 * wiggle the hardware bits.
952 	 */
953 	if (up->clipcnt == 0) {
954 		up->gain += 4;
955 		if (up->gain > 255)
956 			up->gain = 255;
957 	} else if (up->clipcnt > SECOND / 100) {
958 		up->gain -= 4;
959 		if (up->gain < 0)
960 			up->gain = 0;
961 	}
962 	audio_gain(up->gain, up->port);
963 	up->clipcnt = 0;
964 }
965 
966 
967 #else
968 int refclock_irig_bs;
969 #endif /* REFCLOCK */
970