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