]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/ntp/ntpd/refclock_chu.c
This commit was generated by cvs2svn to compensate for changes in r54816,
[FreeBSD/FreeBSD.git] / contrib / ntp / ntpd / refclock_chu.c
1 /*
2  * refclock_chu - clock driver for Canadian radio CHU receivers
3  */
4
5 #ifdef HAVE_CONFIG_H
6 #include <config.h>
7 #endif
8
9 #if defined(REFCLOCK) && defined(CLOCK_CHU)
10
11 /* #define AUDIO_CHUa */
12
13 #include <stdio.h>
14 #include <ctype.h>
15 #include <sys/time.h>
16 #include <time.h>
17 #include <math.h>
18
19 #ifdef AUDIO_CHU
20 #ifdef HAVE_SYS_AUDIOIO_H
21 #include <sys/audioio.h>
22 #endif /* HAVE_SYS_AUDIOIO_H */
23 #ifdef HAVE_SUN_AUDIOIO_H
24 #include <sun/audioio.h>
25 #endif /* HAVE_SUN_AUDIOIO_H */
26 #endif /* AUDIO_CHU */
27
28 #include "ntpd.h"
29 #include "ntp_io.h"
30 #include "ntp_refclock.h"
31 #include "ntp_calendar.h"
32 #include "ntp_stdlib.h"
33
34 /*
35  * Clock driver for Canadian radio CHU receivers
36  *
37  * This driver synchronizes the computer time using data encoded in
38  * radio transmissions from Canadian time/frequency station CHU in
39  * Ottawa, Ontario. Transmissions are made continuously on 3330 kHz,
40  * 7335 kHz and 14670 kHz in upper sideband, compatible AM mode. An
41  * ordinary shortwave receiver can be tuned manually to one of these
42  * frequencies or, in the case of ICOM receivers, the receiver can be
43  * tuned automatically using the minimuf and icom programs as
44  * propagation conditions change throughout the day and night.
45  *
46  * The driver can be compiled to use a Bell 103 compatible modem or
47  * modem chip to receive the radio signal and demodulate the data.
48  * Alternatively, the driver can be compiled to use the audio codec of
49  * the Sun workstation or another with compatible audio drivers. In the
50  * latter case, the driver implements the modem using DSP routines, so
51  * the radio can be connected directly to either the microphone on line
52  * input port. In either case, the driver decodes the data using a
53  * maximum likelihood technique which exploits the considerable degree
54  * of redundancy available to maximize accuracy and minimize errors.
55  *
56  * The CHU time broadcast includes an audio signal compatible with the
57  * Bell 103 modem standard (mark = 2225 Hz, space = 2025 Hz). It consist
58  * of nine, ten-character bursts transmitted at 300 bps and beginning
59  * each second from second 31 to second 39 of the minute. Each character
60  * consists of eight data bits plus one start bit and two stop bits to
61  * encode two hex digits. The burst data consist of five characters (ten
62  * hex digits) followed by a repeat of these characters. In format A,
63  * the characters are repeated in the same polarity; in format B, the
64  * characters are repeated in the opposite polarity.
65  *
66  * Format A bursts are sent at seconds 32 through 39 of the minute in
67  * hex digits
68  *
69  *      6dddhhmmss6dddhhmmss
70  *
71  * The first ten digits encode a frame marker (6) followed by the day
72  * (ddd), hour (hh in UTC), minute (mm) and the second (ss). Since
73  * format A bursts are sent during the third decade of seconds the tens
74  * digit of ss is always 3. The driver uses this to determine correct
75  * burst synchronization. These digits are then repeated with the same
76  * polarity.
77  *
78  * Format B bursts are sent at second 31 of the minute in hex digits
79  *
80  *      xdyyyyttaaxdyyyyttaa
81  *
82  * The first ten digits encode a code (x described below) followed by
83  * the DUT1 (d in deciseconds), Gregorian year (yyyy), difference TAI -
84  * UTC (tt) and daylight time indicator (aa) peculiar to Canada. These
85  * digits are then repeated with inverted polarity.
86  *
87  * The x is coded
88  *
89  * 1 Sign of DUT (0 = +)
90  * 2 Leap second warning. One second will be added.
91  * 4 Leap second warning. One second will be subtracted.
92  * 8 Even parity bit for this nibble.
93  *
94  * By design, the last stop bit of the last character in the burst
95  * coincides with 0.5 second. Since characters have 11 bits and are
96  * transmitted at 300 bps, the last stop bit of the first character
97  * coincides with 0.5 - 10 * 11/300 = 0.133 second. Depending on the
98  * UART, character interrupts can vary somewhere between the beginning
99  * of bit 9 and end of bit 11. These eccentricities can be corrected
100  * along with the radio propagation delay using fudge time 1.
101  *
102  * Debugging aids
103  *
104  * The timecode format used for debugging and data recording includes
105  * data helpful in diagnosing problems with the radio signal and serial
106  * connections. With debugging enabled (-d -d -d on the ntpd command
107  * line), the driver produces one line for each burst in two formats
108  * corresponding to format A and B. Following is format A:
109  *
110  *      n b f s m code
111  *
112  * where n is the number of characters in the burst (0-11), b the burst
113  * distance (0-40), f the field alignment (-1, 0, 1), s the
114  * synchronization distance (0-16), m the burst number (2-9) and code
115  * the burst characters as received. Note that the hex digits in each
116  * character are reversed, so the burst
117  *
118  *      10 38 0 16 9 06851292930685129293
119  *
120  * is interpreted as containing 11 characters with burst distance 38,
121  * field alignment 0, synchronization distance 16 and burst number 9.
122  * The nibble-swapped timecode shows day 58, hour 21, minute 29 and
123  * second 39.
124  *
125  * When the audio driver is compiled, format A is preceded by
126  * the current gain (0-255) and relative signal level (0-9999). The
127  * receiver folume control should be set so that the gain is somewhere
128  * near the middle of the range 0-255, which results in a signal level
129  * near 1000.
130  *
131  * Following is format B:
132  * 
133  *      n b s code
134  *
135  * where n is the number of characters in the burst (0-11), b the burst
136  * distance (0-40), s the synchronization distance (0-40) and code the
137  * burst characters as received. Note that the hex digits in each
138  * character are reversed and the last ten digits inverted, so the burst
139  *
140  *      11 40 1091891300ef6e76ecff
141  *
142  * is interpreted as containing 11 characters with burst distance 40.
143  * The nibble-swapped timecode shows DUT1 +0.1 second, year 1998 and TAI
144  * - UTC 31 seconds.
145  *
146  * In addition to the above, the reference timecode is updated and
147  * written to the clockstats file and debug score after the last burst
148  * received in the minute. The format is
149  *
150  *      qq yyyy ddd hh:mm:ss nn dd tt
151  *
152  * where qq are the error flags, as described below, yyyy is the year,
153  * ddd the day, hh:mm:ss the time of day, nn the number of format A
154  * bursts received during the previous minute, dd the decoding distance
155  * and tt the number of timestamps. The error flags are cleared after
156  * every update.
157  *
158  * Fudge factors
159  *
160  * For accuracies better than the low millisceconds, fudge time1 can be
161  * set to the radio propagation delay from CHU to the receiver. This can
162  * be done conviently using the minimuf program. When the modem driver
163  * is compiled, fudge flag3 enables the ppsclock line discipline. Fudge
164  * flag4 causes the dubugging output described above to be recorded in
165  * the clockstats file.
166  *
167  * When the audio driver is compiled, fudge flag2 selects the audio
168  * input port, where 0 is the mike port (default) and 1 is the line-in
169  * port. It does not seem useful to select the compact disc player port.
170  * Fudge flag3 enables audio monitoring of the input signal. For this
171  * purpose, the speaker volume must be set before the driver is started. 
172  */
173
174 /*
175  * Interface definitions
176  */
177 #define SPEED232        B300    /* uart speed (300 baud) */
178 #define PRECISION       (-10)   /* precision assumed (about 1 ms) */
179 #define REFID           "CHU"   /* reference ID */
180 #ifdef AUDIO_CHU
181 #define DESCRIPTION     "CHU Modem Receiver" /* WRU */
182
183 /*
184  * Audio demodulator definitions
185  */
186 #define AUDIO_BUFSIZ    160     /* codec buffer size (Solaris only) */
187 #define SAMPLE          8000    /* nominal sample rate (Hz) */
188 #define BAUD            300     /* modulation rate (bps) */
189 #define OFFSET          128     /* companded sample offset */
190 #define SIZE            256     /* decompanding table size */
191 #define MAXSIG          6000.   /* maximum signal level */
192 #define DRPOUT          100.    /* dropout signal level */
193 #define LIMIT           1000.   /* soft limiter threshold */
194 #define AGAIN           6.      /* baseband gain */
195 #define LAG             10      /* discriminator lag */
196 #else
197 #define DEVICE          "/dev/chu%d" /* device name and unit */
198 #define SPEED232        B300    /* UART speed (300 baud) */
199 #define DESCRIPTION     "CHU Audio Receiver" /* WRU */
200 #endif /* AUDIO_CHU */
201
202 /*
203  * Decoder definitions
204  */
205 #define CHAR            (11. / 300.) /* character time (s) */
206 #define FUDGE           .185    /* offset to first stop bit (s) */
207 #define BURST           11      /* max characters per burst */
208 #define MINCHAR         9       /* min characters per burst */
209 #define MINDIST         28      /* min burst distance (of 40)  */
210 #define MINSYNC         8       /* min sync distance (of 16) */
211 #define MINDEC          .5      /* decoder majority rule (of 1.) */
212 #define MINSTAMP        20      /* min timestamps (of 60) */
213
214 /*
215  * Hex extension codes (>= 16)
216  */
217 #define HEX_MISS        16      /* miss */
218 #define HEX_SOFT        17      /* soft error */
219 #define HEX_HARD        18      /* hard error */
220
221 /*
222  * Error flags (up->errflg)
223  */
224 #define CHU_ERR_RUNT    0x001   /* runt burst */
225 #define CHU_ERR_NOISE   0x002   /* noise burst */
226 #define CHU_ERR_BFRAME  0x004   /* invalid format B frame sync */
227 #define CHU_ERR_BFORMAT 0x008   /* invalid format B data */
228 #define CHU_ERR_AFRAME  0x010   /* invalid format A frame sync */
229 #define CHU_ERR_DECODE  0x020   /* invalid data decode */
230 #define CHU_ERR_STAMP   0x040   /* too few timestamps */
231 #define CHU_ERR_AFORMAT 0x080   /* invalid format A data */
232 #ifdef AUDIO_CHU
233 #define CHU_ERR_ERROR   0x100   /* codec error (overrun) */
234 #endif /* AUDIO_CHU */
235
236 #ifdef AUDIO_CHU
237 struct surv {
238         double  shift[12];      /* mark register */
239         double  max, min;       /* max/min envelope signals */
240         double  dist;           /* sample distance */
241         int     uart;           /* decoded character */
242 };
243 #endif /* AUDIO_CHU */
244
245 /*
246  * CHU unit control structure
247  */
248 struct chuunit {
249         u_char  decode[20][16]; /* maximum likelihood decoding matrix */
250         l_fp    cstamp[BURST];  /* character timestamps */
251         l_fp    tstamp[MAXSTAGE]; /* timestamp samples */
252         l_fp    timestamp;      /* current buffer timestamp */
253         l_fp    laststamp;      /* last buffer timestamp */
254         l_fp    charstamp;      /* character time as a l_fp */
255         int     errflg;         /* error flags */
256         int     bufptr;         /* buffer index pointer */
257         int     pollcnt;        /* poll message counter */
258
259         /*
260          * Character burst variables
261          */
262         int     cbuf[BURST];    /* character buffer */
263         int     ntstamp;        /* number of timestamp samples */
264         int     ndx;            /* buffer start index */
265         int     prevsec;        /* previous burst second */
266         int     burdist;        /* burst distance */
267         int     syndist;        /* sync distance */
268         int     burstcnt;       /* format A bursts this minute */
269
270 #ifdef AUDIO_CHU
271         /*
272          * Audio codec variables
273          */
274         double  comp[SIZE];     /* decompanding table */
275         int     port;           /* codec port */
276         int     gain;           /* codec gain */
277         int     bufcnt;         /* samples in buffer */
278         int     clipcnt;        /* sample clip count */
279         int     seccnt;         /* second interval counter */
280
281         /*
282          * Modem variables
283          */
284         l_fp    tick;           /* audio sample increment */
285         double  bpf[9];         /* IIR bandpass filter */
286         double  disc[LAG];      /* discriminator shift register */
287         double  lpf[27];        /* FIR lowpass filter */
288         double  monitor;        /* audio monitor */
289         double  maxsignal;      /* signal level */
290         int     discptr;        /* discriminator pointer */
291
292         /*
293          * Maximum likelihood UART variables
294          */
295         double  baud;           /* baud interval */
296         struct surv surv[8];    /* UART survivor structures */
297         int     decptr;         /* decode pointer */
298         int     dbrk;           /* holdoff counter */
299 #endif /* AUDIO_CHU */
300 };
301
302 /*
303  * Function prototypes
304  */
305 static  int     chu_start       P((int, struct peer *));
306 static  void    chu_shutdown    P((int, struct peer *));
307 static  void    chu_receive     P((struct recvbuf *));
308 static  void    chu_poll        P((int, struct peer *));
309
310 /*
311  * More function prototypes
312  */
313 static  void    chu_decode      P((struct peer *, int));
314 static  void    chu_burst       P((struct peer *));
315 static  void    chu_clear       P((struct peer *));
316 static  void    chu_update      P((struct peer *, int));
317 static  void    chu_year        P((struct peer *, int));
318 static  int     chu_dist        P((int, int));
319 #ifdef AUDIO_CHU
320 static  void    chu_uart        P((struct surv *, double));
321 static  void    chu_rf          P((struct peer *, double));
322 static  void    chu_gain        P((struct peer *));
323 static  int     chu_audio       P((void));
324 static  void    chu_debug       P((void));
325 #endif /* AUDIO_CHU */
326
327 /*
328  * Global variables
329  */
330 static char hexchar[] = "0123456789abcdef_-=";
331 #ifdef AUDIO_CHU
332 #ifdef HAVE_SYS_AUDIOIO_H
333 struct  audio_device device;    /* audio device ident */
334 #endif /* HAVE_SYS_AUDIOIO_H */
335 static struct audio_info info;  /* audio device info */
336 static int      chu_ctl_fd;     /* audio control file descriptor */
337 #endif /* AUDIO_CHU */
338
339 /*
340  * Transfer vector
341  */
342 struct  refclock refclock_chu = {
343         chu_start,              /* start up driver */
344         chu_shutdown,           /* shut down driver */
345         chu_poll,               /* transmit poll message */
346         noentry,                /* not used (old chu_control) */
347         noentry,                /* initialize driver (not used) */
348         noentry,                /* not used (old chu_buginfo) */
349         NOFLAGS                 /* not used */
350 };
351
352
353 /*
354  * chu_start - open the devices and initialize data for processing
355  */
356 static int
357 chu_start(
358         int     unit,           /* instance number (not used) */
359         struct peer *peer       /* peer structure pointer */
360         )
361 {
362         struct chuunit *up;
363         struct refclockproc *pp;
364
365         /*
366          * Local variables
367          */
368         int     fd;             /* file descriptor */
369 #ifdef AUDIO_CHU
370         int     i;              /* index */
371         double  step;           /* codec adjustment */
372
373         /*
374          * Open audio device
375          */
376         fd = open("/dev/audio", O_RDWR | O_NONBLOCK, 0777);
377         if (fd == -1) {
378                 perror("chu: audio");
379                 return (0);
380         }
381 #else
382         char device[20];        /* device name */
383
384         /*
385          * Open serial port. Use RAW line discipline (required).
386          */
387         (void)sprintf(device, DEVICE, unit);
388         if (!(fd = refclock_open(device, SPEED232, LDISC_RAW))) {
389                 return (0);
390         }
391 #endif /* AUDIO_CHU */
392
393         /*
394          * Allocate and initialize unit structure
395          */
396         if (!(up = (struct chuunit *)
397               emalloc(sizeof(struct chuunit)))) {
398                 (void) close(fd);
399                 return (0);
400         }
401         memset((char *)up, 0, sizeof(struct chuunit));
402         pp = peer->procptr;
403         pp->unitptr = (caddr_t)up;
404         pp->io.clock_recv = chu_receive;
405         pp->io.srcclock = (caddr_t)peer;
406         pp->io.datalen = 0;
407         pp->io.fd = fd;
408         if (!io_addclock(&pp->io)) {
409                 (void)close(fd);
410                 free(up);
411                 return (0);
412         }
413
414         /*
415          * Initialize miscellaneous variables
416          */
417         peer->precision = PRECISION;
418         pp->clockdesc = DESCRIPTION;
419         memcpy((char *)&pp->refid, REFID, 4);
420         DTOLFP(CHAR, &up->charstamp);
421         up->pollcnt = 2;
422 #ifdef AUDIO_CHU
423         up->gain = (AUDIO_MAX_GAIN - AUDIO_MIN_GAIN) / 2;
424         if (chu_audio() < 0) {
425                 io_closeclock(&pp->io);
426                 free(up);
427                 return (0);
428         }
429
430         /*
431          * The companded samples are encoded sign-magnitude. The table
432          * contains all the 256 values in the interest of speed.
433          */
434         up->comp[0] = up->comp[OFFSET] = 0.;
435         up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
436         up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
437         step = 2.;
438         for (i = 3; i < OFFSET; i++) {
439                 up->comp[i] = up->comp[i - 1] + step;
440                 up->comp[OFFSET + i] = -up->comp[i];
441                 if (i % 16 == 0)
442                         step *= 2.;
443         }
444         DTOLFP(1. / SAMPLE, &up->tick);
445 #endif /* AUDIO_CHU */
446         return (1);
447 }
448
449
450 /*
451  * chu_shutdown - shut down the clock
452  */
453 static void
454 chu_shutdown(
455         int     unit,           /* instance number (not used) */
456         struct peer *peer       /* peer structure pointer */
457         )
458 {
459         struct chuunit *up;
460         struct refclockproc *pp;
461
462         pp = peer->procptr;
463         up = (struct chuunit *)pp->unitptr;
464         io_closeclock(&pp->io);
465         free(up);
466 }
467
468 #ifdef AUDIO_CHU
469
470 /*
471  * chu_receive - receive data from the audio device
472  */
473 static void
474 chu_receive(
475         struct recvbuf *rbufp   /* receive buffer structure pointer */
476         )
477 {
478         struct chuunit *up;
479         struct refclockproc *pp;
480         struct peer *peer;
481
482         /*
483          * Local variables
484          */
485         double  sample;         /* codec sample */
486         u_char  *dpt;           /* buffer pointer */
487         l_fp    ltemp;          /* l_fp temp */
488         double  dtemp;          /* double temp */
489         int     isneg;          /* parity flag */
490         int     i, j;           /* index temps */
491
492         peer = (struct peer *)rbufp->recv_srcclock;
493         pp = peer->procptr;
494         up = (struct chuunit *)pp->unitptr;
495
496         /*
497          * Main loop - read until there ain't no more. Note codec
498          * samples are bit-inverted.
499          */
500         up->timestamp = rbufp->recv_time;
501         up->bufcnt = rbufp->recv_length;
502         DTOLFP(up->bufcnt * 1. / SAMPLE, &ltemp);
503         L_SUB(&up->timestamp, &ltemp);
504         dpt = (u_char *)&rbufp->recv_space;
505         for (up->bufptr = 0; up->bufptr < up->bufcnt; up->bufptr++) {
506                 sample = up->comp[~*dpt & 0xff];
507
508                 /*
509                  * Clip noise spikes greater than MAXSIG. If no clips,
510                  * increase the gain a tad; if the clips are too high, 
511                  * decrease a tad.
512                  */
513                 if (sample > MAXSIG) {
514                         sample = MAXSIG;
515                         up->clipcnt++;
516                 } else if (sample < -MAXSIG) {
517                         sample = -MAXSIG;
518                         up->clipcnt++;
519                 }
520                 up->seccnt = (up->seccnt + 1) % SAMPLE;
521                 if (up->seccnt == 0) {
522                         if (pp->sloppyclockflag & CLK_FLAG2)
523                                 up->port = AUDIO_LINE_IN;
524                         else
525                                 up->port = AUDIO_MICROPHONE;
526                         chu_gain(peer);
527                         up->clipcnt = 0;
528                 }
529                 chu_rf(peer, sample);
530
531                 /*
532                  * During development, it is handy to have an audio
533                  * monitor that can be switched to various signals. This
534                  * code converts the linear signal left in up->monitor
535                  * to codec format. If we can get the grass out of this
536                  * thing and improve modem performance, this expensive
537                  * code will be permanently nixed.
538                  */
539                 isneg = 0;
540                 dtemp = up->monitor;
541                 if (sample < 0) {
542                         isneg = 1;
543                         dtemp-= dtemp;
544                 }
545                 i = 0;
546                 j = OFFSET >> 1;
547                 while (j != 0) {
548                         if (dtemp > up->comp[i])
549                                 i += j;
550                         else if (dtemp < up->comp[i])
551                                 i -= j;
552                         else
553                                 break;
554                         j >>= 1;
555                 }
556                 if (isneg)
557                         *dpt = ~(i + OFFSET);
558                 else
559                         *dpt = ~i;
560                 dpt++;
561                 L_ADD(&up->timestamp, &up->tick);
562         }
563         
564         /*
565          * Squawk to the monitor speaker if enabled.
566          */
567         if (pp->sloppyclockflag & CLK_FLAG3)
568                 if (write(pp->io.fd, (u_char *)&rbufp->recv_space,
569                     (u_int)up->bufcnt) < 0)
570                         perror("chu:");
571 }
572
573
574 /*
575  * chu_rf - filter and demodulate the FSK signal
576  *
577  * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz
578  * and space 2025 Hz. It uses a bandpass filter followed by a soft
579  * limiter, FM discriminator and lowpass filter. A maximum likelihood
580  * decoder samples the baseband signal at eight times the baud rate and
581  * detects the start bit of each character.
582  *
583  * The filters are built for speed, which explains the rather clumsy
584  * code. Hopefully, the compiler will efficiently implement the move-
585  * and-muiltiply-and-add operations.
586  */
587 void
588 chu_rf(
589         struct peer *peer,      /* peer structure pointer */
590         double  sample          /* analog sample */
591         )
592 {
593         struct refclockproc *pp;
594         struct chuunit *up;
595         struct surv *sp;
596
597         /*
598          * Local variables
599          */
600         double  signal;         /* bandpass signal */
601         double  limit;          /* limiter signal */
602         double  disc;           /* discriminator signal */
603         double  lpf;            /* lowpass signal */
604         double  span;           /* UART signal span */
605         double  dist;           /* UART signal distance */
606         int     i, j;           /* index temps */
607
608         pp = peer->procptr;
609         up = (struct chuunit *)pp->unitptr;
610         /*
611          * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered
612          * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB.
613          */
614         signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01;
615         signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01;
616         signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00;
617         signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00;
618         signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00;
619         signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00;
620         signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00;
621         signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01;
622         up->bpf[0] = sample - signal;
623         signal = up->bpf[0] * 6.176213e-03
624             + up->bpf[1] * 3.156599e-03
625             + up->bpf[2] * 7.567487e-03
626             + up->bpf[3] * 4.344580e-03
627             + up->bpf[4] * 1.190128e-02
628             + up->bpf[5] * 4.344580e-03
629             + up->bpf[6] * 7.567487e-03
630             + up->bpf[7] * 3.156599e-03
631             + up->bpf[8] * 6.176213e-03;
632
633         up->monitor = signal / 4.;      /* note monitor after filter */
634
635         /*
636          * Soft limiter/discriminator. The 11-sample discriminator lag
637          * interval corresponds to three cycles of 2125 Hz, which
638          * requires the sample frequency to be 2125 * 11 / 3 = 7791.7
639          * Hz. The discriminator output varies +-0.5 interval for input
640          * frequency 2025-2225 Hz. However, we don't get to sample at
641          * this frequency, so the discriminator output is biased. Life
642          * at 8000 Hz sucks.
643          */
644         limit = signal;
645         if (limit > LIMIT)
646                 limit = LIMIT;
647         else if (limit < -LIMIT)
648                 limit = -LIMIT;
649         disc = up->disc[up->discptr] * -limit;
650         up->disc[up->discptr] = limit;
651         up->discptr = (up->discptr + 1 ) % LAG;
652         if (disc >= 0)
653                 disc = sqrt(disc);
654         else
655                 disc = -sqrt(-disc);
656
657         /*
658          * Lowpass filter. Raised cosine, Ts = 1 / 300, beta = 0.1.
659          */
660         lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02;
661         lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01;
662         lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01;
663         lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01;
664         lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01;
665         lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01;
666         lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01;
667         lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01;
668         lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01;
669         lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01;
670         lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01;
671         lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01;
672         lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01;
673         lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00;
674         lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01;
675         lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01;
676         lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01;
677         lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01;
678         lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01;
679         lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01;
680         lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01;
681         lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01;
682         lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01;
683         lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01;
684         lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01;
685         lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01;
686         lpf += up->lpf[0] = disc * 2.538771e-02;
687 /*
688 printf("%8.3f %8.3f\n", disc, lpf);
689 return;
690 */
691         /*
692          * Maximum likelihood decoder. The UART updates each of the
693          * eight survivors and determines the span, slice level and
694          * tentative decoded character. Valid 11-bit characters are
695          * framed so that bit 1 and bit 11 (stop bits) are mark and bit
696          * 2 (start bit) is space. When a valid character is found, the
697          * survivor with maximum distance determines the final decoded
698          * character.
699          */
700         up->baud += 1. / SAMPLE;
701         if (up->baud > 1. / (BAUD * 8.)) {
702                 up->baud -= 1. / (BAUD * 8.);
703                 sp = &up->surv[up->decptr];
704                 span = sp->max - sp->min;
705                 up->maxsignal += (span - up->maxsignal) / 80.;
706                 if (up->dbrk > 0) {
707                         up->dbrk--;
708                 } else if ((sp->uart & 0x403) == 0x401 && span > 1000.)
709                     {
710                         dist = 0;
711                         j = 0;
712                         for (i = 0; i < 8; i++) {
713                                 if (up->surv[i].dist > dist) {
714                                         dist = up->surv[i].dist;
715                                         j = i;
716                                 }
717                         }
718                         chu_decode(peer, (up->surv[j].uart >> 2) &
719                             0xff);
720                         up->dbrk = 80;
721                 }
722                 up->decptr = (up->decptr + 1) % 8;
723                 chu_uart(sp, -lpf * AGAIN);
724         }
725 }
726
727
728 /*
729  * chu_uart - maximum likelihood UART
730  *
731  * This routine updates a shift register holding the last 11 envelope
732  * samples. It then computes the slice level and span over these samples
733  * and determines the tentative data bits and distance. The calling
734  * program selects over the last eight survivors the one with maximum
735  * distance to determine the decoded character.
736  */
737 void
738 chu_uart(
739         struct surv *sp,        /* survivor structure pointer */
740         double  sample          /* baseband signal */
741         )
742 {
743         /*
744          * Local variables
745          */
746         double  max, min;       /* max/min envelope */
747         double  slice;          /* slice level */
748         double  dist;           /* distance */
749         double  dtemp;          /* double temp */
750         int     i;              /* index temp */
751
752         /*
753          * Save the sample and shift right. At the same time, measure
754          * the maximum and minimum over all eleven samples.
755          */
756         max = -1e6;
757         min = 1e6;
758         sp->shift[0] = sample;
759         for (i = 11; i > 0; i--) {
760                 sp->shift[i] = sp->shift[i - 1];
761                 if (sp->shift[i] > max)
762                         max = sp->shift[i];
763                 if (sp->shift[i] < min)
764                         min = sp->shift[i];
765         }
766
767         /*
768          * Determine the slice level midway beteen the maximum and
769          * minimum and the span as the maximum less the minimum. Compute
770          * the distance on the assumption the first and last bits must
771          * be mark, the second space and the rest either mark or space.
772          */ 
773         slice = (max + min) / 2.;
774         dist = 0;
775         sp->uart = 0;
776         for (i = 1; i < 12; i++) {
777                 sp->uart <<= 1;
778                 dtemp = sp->shift[i];
779                 if (dtemp > slice)
780                         sp->uart |= 0x1;
781                 if (i == 1 || i == 11) {
782                         dist += dtemp - min;
783                 } else if (i == 10) {
784                         dist += max - dtemp;
785                 } else {
786                         if (dtemp > slice)
787                                 dist += dtemp - min;
788                         else
789                                 dist += max - dtemp;
790                 }
791         }
792         sp->max = max;
793         sp->min = min;
794         sp->dist = dist / (11 * (max - min));
795 }
796
797
798 #else /* AUDIO_CHU */
799 /*
800  * chu_receive - receive data from the serial interface
801  */
802 static void
803 chu_receive(
804         struct recvbuf *rbufp   /* receive buffer structure pointer */
805         )
806 {
807         struct chuunit *up;
808         struct refclockproc *pp;
809         struct peer *peer;
810
811         u_char  *dpt;           /* receive buffer pointer */
812
813         peer = (struct peer *)rbufp->recv_srcclock;
814         pp = peer->procptr;
815         up = (struct chuunit *)pp->unitptr;
816
817         /*
818          * Initialize pointers and read the timecode and timestamp.
819          */
820         up->timestamp = rbufp->recv_time;
821         dpt = (u_char *)&rbufp->recv_space;
822         chu_decode(peer, *dpt);
823 }
824 #endif /* AUDIO_CHU */
825
826
827 /*
828  * chu_decode - decode the data
829  */
830 static void
831 chu_decode(
832         struct peer *peer,      /* peer structure pointer */
833         int     hexhex          /* data character */
834         )
835 {
836         struct refclockproc *pp;
837         struct chuunit *up;
838
839         /*
840          * Local variables
841          */
842         l_fp    tstmp;          /* timestamp temp */
843         double  dtemp;          /* double temp */
844
845         pp = peer->procptr;
846         up = (struct chuunit *)pp->unitptr;
847
848         /*
849          * If the interval since the last character is greater than the
850          * longest burst, process the last burst and start a new one. If
851          * the interval is less than this but greater than two
852          * characters, consider this a noise burst and reject it.
853          */
854         tstmp = up->timestamp;
855         if (L_ISZERO(&up->laststamp))
856                 up->laststamp = up->timestamp;
857         L_SUB(&tstmp, &up->laststamp);
858         up->laststamp = up->timestamp;
859         LFPTOD(&tstmp, dtemp);
860         if (dtemp > BURST * CHAR) {
861                 chu_burst(peer);
862                 up->ndx = 0;
863         } else if (dtemp > 2.5 * CHAR) {
864                 up->ndx = 0;
865         }
866
867         /*
868          * Append the character to the current burst and append the
869          * timestamp to the timestamp list.
870          */
871         if (up->ndx < BURST) {
872                 up->cbuf[up->ndx] = hexhex & 0xff;
873                 up->cstamp[up->ndx] = up->timestamp;
874                 up->ndx++;
875
876         }
877 }
878
879
880 /*
881  * chu_burst - search for valid burst format
882  */
883 static void
884 chu_burst(
885         struct peer *peer
886         )
887 {
888         struct chuunit *up;
889         struct refclockproc *pp;
890
891         /*
892          * Local variables
893          */
894         int     i;              /* index temp */
895
896         pp = peer->procptr;
897         up = (struct chuunit *)pp->unitptr;
898
899         /*
900          * Correlate a block of five characters with the next block of
901          * five characters. The burst distance is defined as the number
902          * of bits that match in the two blocks for format A and that
903          * match the inverse for format B.
904          */
905         if (up->ndx < MINCHAR) {
906                 up->errflg |= CHU_ERR_RUNT;
907                 return;
908         }
909         up->burdist = 0;
910         for (i = 0; i < 5 && i < up->ndx - 5; i++)
911                 up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]);
912
913         /*
914          * If the burst distance is at least MINDIST, this must be a
915          * format A burst; if the value is not greater than -MINDIST, it
916          * must be a format B burst; otherwise, it is a noise burst and
917          * of no use to anybody.
918          */
919         if (up->burdist >= MINDIST) {
920                 chu_update(peer, up->ndx);
921         } else if (up->burdist <= -MINDIST) {
922                 chu_year(peer, up->ndx);
923         } else {
924                 up->errflg |= CHU_ERR_NOISE;
925                 return;
926         }
927
928         /*
929          * If this is a valid burst, wait a guard time of ten seconds to
930          * allow for more bursts, then arm the poll update routine to
931          * process the minute. Don't do this if this is called from the
932          * timer interrupt routine.
933          */
934         if (peer->outdate == current_time)
935                 up->pollcnt = 2;
936         else
937                 peer->nextdate = current_time + 10;
938 }
939
940
941 /*
942  * chu_year - decode format B burst
943  */
944 static void
945 chu_year(
946         struct peer *peer,
947         int     nchar
948         )
949 {
950         struct  refclockproc *pp;
951         struct  chuunit *up;
952
953         /*
954          * Local variables
955          */
956         u_char  code[11];       /* decoded timecode */
957         l_fp    offset;         /* timestamp offset */
958         int     leap;           /* leap/dut code */
959         int     dut;            /* UTC1 correction */
960         int     tai;            /* TAI - UTC correction */
961         int     dst;            /* Canadian DST code */
962         int     i;              /* index temp */
963
964         pp = peer->procptr;
965         up = (struct chuunit *)pp->unitptr;
966
967         /*
968          * In a format B burst, a character is considered valid only if
969          * the first occurrence matches the last occurrence. The burst
970          * is considered valid only if all characters are valid; that
971          * is, only if the distance is 40. 
972          */
973         sprintf(pp->a_lastcode, "%2d %2d ", nchar, -up->burdist);
974         for (i = 0; i < nchar; i++)
975                 sprintf(&pp->a_lastcode[strlen(pp->a_lastcode)], "%02x",
976                     up->cbuf[i]);
977         pp->lencode = strlen(pp->a_lastcode);
978         if (pp->sloppyclockflag & CLK_FLAG4)
979                 record_clock_stats(&peer->srcadr, pp->a_lastcode);
980 #ifdef DEBUG
981         if (debug > 2)
982                 printf("chu: %s\n", pp->a_lastcode);
983 #endif
984         if (-up->burdist < 40) {
985                 up->errflg |= CHU_ERR_BFRAME;
986                 return;
987         }
988
989         /*
990          * Convert the burst data to internal format. If this succeeds,
991          * save the timestamps for later. The leap, dut, tai and dst are
992          * presently unused.
993          */
994         for (i = 0; i < 5; i++) {
995                 code[2 * i] = hexchar[up->cbuf[i] & 0xf];
996                 code[2 * i + 1] = hexchar[(up->cbuf[i] >>
997                     4) & 0xf];
998         }
999         if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &leap, &dut,
1000             &pp->year, &tai, &dst) != 5) {
1001                 up->errflg |= CHU_ERR_BFORMAT;
1002                 return;
1003         }
1004         offset.l_ui = 31;
1005         offset.l_f = 0;
1006         for (i = 0; i < nchar && i < 10; i++) {
1007                 up->tstamp[up->ntstamp] = up->cstamp[i];
1008                 L_SUB(&up->tstamp[up->ntstamp], &offset);
1009                 L_ADD(&offset, &up->charstamp);
1010                 if (up->ntstamp < MAXSTAGE) 
1011                         up->ntstamp++;
1012         }
1013 }
1014
1015
1016 /*
1017  * chu_update - decode format A burst
1018  */
1019 static void
1020 chu_update(
1021         struct peer *peer,
1022         int nchar
1023         )
1024 {
1025         struct refclockproc *pp;
1026         struct chuunit *up;
1027
1028         /*
1029          * Local variables
1030          */
1031         l_fp    offset;         /* timestamp offset */
1032         int     val;            /* distance */
1033         int     temp;           /* common temp */
1034         int     i, j, k;        /* index temps */
1035
1036         pp = peer->procptr;
1037         up = (struct chuunit *)pp->unitptr;
1038
1039         /*
1040          * Determine correct burst phase. There are three cases
1041          * corresponding to in-phase, one character early or one
1042          * character late. These cases are distinguished by the position
1043          * of the framing digits x6 at positions 0 and 5 and x3 at
1044          * positions 4 and 9. The correct phase is when the distance
1045          * relative to the framing digits is maximum. The burst is valid
1046          * only if the maximum distance is at least MINSYNC.
1047          */
1048         up->syndist = k = 0;
1049         val = -16;
1050         for (i = -1; i < 2; i++) {
1051                 temp = up->cbuf[i + 4] & 0xf;
1052                 if (i >= 0)
1053                         temp |= (up->cbuf[i] & 0xf) << 4;
1054                 val = chu_dist(temp, 0x63);
1055                 temp = (up->cbuf[i + 5] & 0xf) << 4;
1056                 if (i + 9 < nchar)
1057                         temp |= up->cbuf[i + 9] & 0xf;
1058                 val += chu_dist(temp, 0x63);
1059                 if (val > up->syndist) {
1060                         up->syndist = val;
1061                         k = i;
1062                 }
1063         }
1064
1065         temp = (up->cbuf[k + 4] >> 4) & 0xf;
1066         if (temp > 9 || k + 9 >= nchar || temp != ((up->cbuf[k + 9] >>
1067             4) & 0xf))
1068                 temp = 0;
1069 #ifdef AUDIO_CHU
1070         sprintf(pp->a_lastcode, "%3d %4.0f %2d %2d %2d %2d %1d ",
1071             up->gain, up->maxsignal, nchar, up->burdist, k, up->syndist,
1072             temp);
1073 #else
1074         sprintf(pp->a_lastcode, "%2d %2d %2d %2d %1d ", nchar,
1075             up->burdist, k, up->syndist, temp);
1076 #endif /* AUDIO_CHU */
1077         for (i = 0; i < nchar; i++)
1078                 sprintf(&pp->a_lastcode[strlen(pp->a_lastcode)], "%02x",
1079                     up->cbuf[i]);
1080         pp->lencode = strlen(pp->a_lastcode);
1081         if (pp->sloppyclockflag & CLK_FLAG4)
1082                 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1083 #ifdef DEBUG
1084         if (debug > 2)
1085                 printf("chu: %s\n", pp->a_lastcode);
1086 #endif
1087         if (up->syndist < MINSYNC) {
1088                 up->errflg |= CHU_ERR_AFRAME;
1089                 return;
1090         }
1091
1092         /*
1093          * A valid burst requires the first seconds number to match the
1094          * last seconds number. If so, the burst timestamps are
1095          * corrected to the current minute and saved for later
1096          * processing. In addition, the seconds decode is advanced from
1097          * the previous burst to the current one.
1098          */
1099         if (temp != 0) {
1100                 offset.l_ui = 30 + temp;
1101                 offset.l_f = 0;
1102                 i = 0;
1103                 if (k < 0)
1104                         offset = up->charstamp;
1105                 else if (k > 0)
1106                         i = 1;
1107                 for (; i < nchar && i < k + 10; i++) {
1108                         up->tstamp[up->ntstamp] = up->cstamp[i];
1109                         L_SUB(&up->tstamp[up->ntstamp], &offset);
1110                         L_ADD(&offset, &up->charstamp);
1111                         if (up->ntstamp < MAXSTAGE) 
1112                                 up->ntstamp++;
1113                 }
1114                 while (temp > up->prevsec) {
1115                         for (j = 15; j > 0; j--) {
1116                                 up->decode[9][j] = up->decode[9][j - 1];
1117                                 up->decode[19][j] =
1118                                     up->decode[19][j - 1];
1119                         }
1120                         up->decode[9][j] = up->decode[19][j] = 0;
1121                         up->prevsec++;
1122                 }
1123         }
1124         i = -(2 * k);
1125         for (j = 0; j < nchar; j++) {
1126                 if (i < 0 || i > 19) {
1127                         i += 2;
1128                         continue;
1129                 }
1130                 up->decode[i++][up->cbuf[j] & 0xf]++;
1131                 up->decode[i++][(up->cbuf[j] >> 4) & 0xf]++;
1132         }
1133         up->burstcnt++;
1134 }
1135
1136
1137 /*
1138  * chu_poll - called by the transmit procedure
1139  */
1140 static void
1141 chu_poll(
1142         int unit,
1143         struct peer *peer
1144         )
1145 {
1146         struct refclockproc *pp;
1147         struct chuunit *up;
1148
1149         /*
1150          * Local variables
1151          */
1152         u_char  code[11];       /* decoded timecode */
1153         l_fp    toffset, offset; /* l_fp temps */
1154         int     mindist;        /* minimum distance */
1155         int     val1, val2;     /* maximum distance */
1156         int     synchar;        /* should be a 6 in traffic */
1157         double  dtemp;          /* double temp */
1158         int     temp;           /* common temp */
1159         int     i, j, k;        /* index temps */
1160
1161         pp = peer->procptr;
1162         up = (struct chuunit *)pp->unitptr;
1163
1164         /*
1165          * Process the last burst, if still in the burst buffer.
1166          * Don't mess with anything if nothing has been heard.
1167          */
1168         chu_burst(peer);
1169         if (up->pollcnt == 0)
1170                 refclock_report(peer, CEVNT_TIMEOUT);
1171         else
1172                 up->pollcnt--;
1173         if (up->burstcnt == 0) {
1174                 chu_clear(peer);
1175                 return;
1176         }
1177
1178         /*
1179          * Majority decoder. Select the character with the most
1180          * occurrences for each burst position. The distance for the
1181          * character is this number of occurrences. If no occurrences
1182          * are found, assume a miss '_'; if only a single occurrence is
1183          * found, assume a soft error '-'; if two different characters
1184          * with the same distance are found, assume a hard error '='.
1185          * The decoding distance is defined as the minimum of the
1186          * character distances.
1187          */
1188         mindist = 16;
1189         for (i = 0; i < 10; i++) {
1190                 val1 = val2 = 0;
1191                 k = 0;
1192                 for (j = 0; j < 16; j++) {
1193                         temp = up->decode[i][j] + up->decode[i + 10][j];
1194                         if (temp > val1) {
1195                                 val2 = val1;
1196                                 val1 = temp;
1197                                 k = j;
1198                         }
1199                 }
1200                 if (val1 > 0 && val1 == val2)
1201                         code[i] = HEX_HARD;
1202                 else if (val1 < 2)
1203                         code[i] = HEX_SOFT;
1204                 else
1205                         code[i] = k;
1206                 if (val1 < mindist)
1207                         mindist = val1;
1208                 code[i] = hexchar[code[i]];
1209         }
1210         code[i] = 0;
1211         if (mindist < up->burstcnt * 2 * MINDEC)
1212                 up->errflg |= CHU_ERR_DECODE;
1213         if (up->ntstamp < MINSTAMP)
1214                 up->errflg |= CHU_ERR_STAMP;
1215
1216         /*
1217          * Compute the timecode timestamp from the days, hours and
1218          * minutes of the timecode. Use clocktime() for the aggregate
1219          * minutes and the minute offset computed from the burst
1220          * seconds. Note that this code relies on the filesystem time
1221          * for the years and does not use the years of the timecode.
1222          */
1223         if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day, &pp->hour,
1224             &pp->minute) != 4)
1225                 up->errflg |= CHU_ERR_AFORMAT;
1226         sprintf(pp->a_lastcode,
1227             "%02x %4d %3d %02d:%02d:%02d %2d %2d %2d",
1228             up->errflg, pp->year, pp->day, pp->hour, pp->minute,
1229             pp->second, up->burstcnt, mindist, up->ntstamp);
1230         pp->lencode = strlen(pp->a_lastcode);
1231         record_clock_stats(&peer->srcadr, pp->a_lastcode);
1232 #ifdef DEBUG
1233         if (debug > 2)
1234                 printf("chu: %s\n", pp->a_lastcode);
1235 #endif
1236         if (up->errflg & (CHU_ERR_DECODE | CHU_ERR_STAMP |
1237             CHU_ERR_AFORMAT)) {
1238                 refclock_report(peer, CEVNT_BADREPLY);
1239                 chu_clear(peer);
1240                 return;
1241         }
1242         L_CLR(&offset);
1243         if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT,
1244             up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) {
1245                 refclock_report(peer, CEVNT_BADTIME);
1246                 chu_clear(peer);
1247                 return;
1248         }
1249         pp->polls++;
1250         pp->leap = LEAP_NOWARNING;
1251         pp->lastref = offset;
1252         pp->variance = 0;
1253         for (i = 0; i < up->ntstamp; i++) {
1254                 toffset = offset;
1255                 L_SUB(&toffset, &up->tstamp[i]);
1256                 LFPTOD(&toffset, dtemp);
1257                 SAMPLE(dtemp + FUDGE + pp->fudgetime1);
1258         }
1259         if (i > 0)
1260                 refclock_receive(peer);
1261         chu_clear(peer);
1262 }
1263
1264
1265 /*
1266  * chu_clear - clear decoding matrix
1267  */
1268 static void
1269 chu_clear(
1270         struct peer *peer
1271         )
1272 {
1273         struct refclockproc *pp;
1274         struct chuunit *up;
1275
1276         /*
1277          * Local variables
1278          */
1279         int     i, j;           /* index temps */
1280
1281         pp = peer->procptr;
1282         up = (struct chuunit *)pp->unitptr;
1283
1284         /*
1285          * Clear stuff for following minute.
1286          */
1287         up->ndx = up->ntstamp = up->prevsec = 0;
1288         up->errflg = 0;
1289         up->burstcnt = 0;
1290         for (i = 0; i < 20; i++) {
1291                 for (j = 0; j < 16; j++)
1292                         up->decode[i][j] = 0;
1293         }
1294 }
1295
1296
1297 /*
1298  * chu_dist - determine the distance of two octet arguments
1299  */
1300 static int
1301 chu_dist(
1302         int     x,              /* an octet of bits */
1303         int     y               /* another octet of bits */
1304         )
1305 {
1306         /*
1307          * Local variables
1308          */
1309         int     val;            /* bit count */ 
1310         int     temp;           /* misc temporary */
1311         int     i;              /* index temporary */
1312
1313         /*
1314          * The distance is determined as the weight of the exclusive OR
1315          * of the two arguments. The weight is determined by the number
1316          * of one bits in the result. Each one bit increases the weight,
1317          * while each zero bit decreases it.
1318          */
1319         temp = x ^ y;
1320         val = 0;
1321         for (i = 0; i < 8; i++) {
1322                 if ((temp & 0x1) == 0)
1323                         val++;
1324                 else
1325                         val--;
1326                 temp >>= 1;
1327         }
1328         return (val);
1329 }
1330
1331
1332 #ifdef AUDIO_CHU
1333 /*
1334  * chu_gain - adjust codec gain
1335  *
1336  * This routine is called once each second. If the signal envelope
1337  * amplitude is too low, the codec gain is bumped up by four units; if
1338  * too high, it is bumped down. The decoder is relatively insensitive to
1339  * amplitude, so this crudity works just fine. The input port is set and
1340  * the error flag is cleared, mostly to be ornery.
1341  */
1342 static void
1343 chu_gain(
1344         struct peer *peer       /* peer structure pointer */
1345         )
1346 {
1347         struct refclockproc *pp;
1348         struct chuunit *up;
1349
1350         pp = peer->procptr;
1351         up = (struct chuunit *)pp->unitptr;
1352
1353         /*
1354          * Apparently, the codec uses only the high order bits of the
1355          * gain control field. Thus, it may take awhile for changes to
1356          * wiggle the hardware bits. Set the new bits in the structure
1357          * and call AUDIO_SETINFO. Upon return, the old bits are in the
1358          * structure.
1359          */
1360         if (up->clipcnt == 0) {
1361                 up->gain += 4;
1362                 if (up->gain > AUDIO_MAX_GAIN)
1363                         up->gain = AUDIO_MAX_GAIN;
1364         } else if (up->clipcnt > SAMPLE / 100) {
1365                 up->gain -= 4;
1366                 if (up->gain < AUDIO_MIN_GAIN)
1367                         up->gain = AUDIO_MIN_GAIN;
1368         }
1369         AUDIO_INITINFO(&info);
1370         info.record.port = up->port;
1371         info.record.gain = up->gain;
1372         info.record.error = 0;
1373         ioctl(chu_ctl_fd, (int)AUDIO_SETINFO, &info);
1374         if (info.record.error)
1375                 up->errflg |= CHU_ERR_ERROR;
1376 }
1377
1378
1379 /*
1380  * chu_audio - initialize audio device
1381  *
1382  * This code works with SunOS 4.1.3 and Solaris 2.6; however, it is
1383  * believed generic and applicable to other systems with a minor twid
1384  * or two. All it does is open the device, set the buffer size (Solaris
1385  * only), preset the gain and set the input port. It assumes that the
1386  * codec sample rate (8000 Hz), precision (8 bits), number of channels
1387  * (1) and encoding (ITU-T G.711 mu-law companded) have been set by
1388  * default.
1389  */
1390 static int
1391 chu_audio(
1392         )
1393 {
1394         /*
1395          * Open audio control device
1396          */
1397         if ((chu_ctl_fd = open("/dev/audioctl", O_RDWR)) < 0) {
1398                 perror("audioctl");
1399                 return(-1);
1400         }
1401 #ifdef HAVE_SYS_AUDIOIO_H
1402         /*
1403          * Set audio device parameters.
1404          */
1405         AUDIO_INITINFO(&info);
1406         info.record.buffer_size = AUDIO_BUFSIZ;
1407         if (ioctl(chu_ctl_fd, (int)AUDIO_SETINFO, &info) < 0) {
1408                 perror("AUDIO_SETINFO");
1409                 close(chu_ctl_fd);
1410                 return(-1);
1411         }
1412 #endif /* HAVE_SYS_AUDIOIO_H */
1413 #ifdef DEBUG
1414         chu_debug();
1415 #endif /* DEBUG */
1416         return(0);
1417 }
1418
1419
1420 #ifdef DEBUG
1421 /*
1422  * chu_debug - display audio parameters
1423  *
1424  * This code doesn't really do anything, except satisfy curiousity and
1425  * verify the ioctl's work.
1426  */
1427 static void
1428 chu_debug(
1429         )
1430 {
1431         if (debug == 0)
1432                 return;
1433 #ifdef HAVE_SYS_AUDIOIO_H
1434         ioctl(chu_ctl_fd, (int)AUDIO_GETDEV, &device);
1435         printf("chu: name %s, version %s, config %s\n",
1436             device.name, device.version, device.config);
1437 #endif /* HAVE_SYS_AUDIOIO_H */
1438         ioctl(chu_ctl_fd, (int)AUDIO_GETINFO, &info);
1439         printf(
1440             "chu: samples %d, channels %d, precision %d, encoding %d\n",
1441             info.record.sample_rate, info.record.channels,
1442             info.record.precision, info.record.encoding);
1443 #ifdef HAVE_SYS_AUDIOIO_H
1444         printf("chu: gain %d, port %d, buffer %d\n",
1445             info.record.gain, info.record.port,
1446             info.record.buffer_size);
1447 #else /* HAVE_SYS_AUDIOIO_H */
1448         printf("chu: gain %d, port %d\n",
1449             info.record.gain, info.record.port);
1450 #endif /* HAVE_SYS_AUDIOIO_H */
1451         printf(
1452             "chu: samples %d, eof %d, pause %d, error %d, waiting %d, balance %d\n",
1453             info.record.samples, info.record.eof,
1454             info.record.pause, info.record.error,
1455             info.record.waiting, info.record.balance);
1456         printf("chu: monitor %d, muted %d\n",
1457             info.monitor_gain, info.output_muted);
1458 }
1459 #endif /* DEBUG */
1460 #endif /* AUDIO_CHU */
1461
1462 #else
1463 int refclock_chu_bs;
1464 #endif /* REFCLOCK */