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