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