/contrib/ntp/ntpd/refclock_irig.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 1048 lines · 581 code · 79 blank · 388 comment · 97 complexity · 7b7cb91f7c1c95d671dec2c7c0f373e8 MD5 · raw file

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