Pull morse(6) into the new millenium and teach it to use sound(4).
[dragonfly.git] / games / morse / morse.c
1 /*
2  * Copyright (c) 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1988, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)morse.c  8.1 (Berkeley) 5/31/93
35  * $FreeBSD: src/games/morse/morse.c,v 1.12.2.2 2002/03/12 17:45:15 phantom Exp $
36  * $DragonFly: src/games/morse/morse.c,v 1.4 2007/04/22 10:22:32 corecode Exp $
37  */
38
39 /*
40  * Taught to send *real* morse by Lyndon Nerenberg (VE7TCP/VE6BBM)
41  * <lyndon@orthanc.com>
42  */
43
44 #include <sys/time.h>
45 #include <sys/soundcard.h>
46
47 #include <ctype.h>
48 #include <err.h>
49 #include <fcntl.h>
50 #include <langinfo.h>
51 #include <locale.h>
52 #include <math.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <termios.h>
58 #include <unistd.h>
59
60 struct morsetab {
61         char            inchar;
62         const char      *morse;
63 };
64
65 static const struct morsetab mtab[] = {
66
67         /* letters */
68
69         {'a', ".-"},
70         {'b', "-..."},
71         {'c', "-.-."},
72         {'d', "-.."},
73         {'e', "."},
74         {'f', "..-."},
75         {'g', "--."},
76         {'h', "...."},
77         {'i', ".."},
78         {'j', ".---"},
79         {'k', "-.-"},
80         {'l', ".-.."},
81         {'m', "--"},
82         {'n', "-."},
83         {'o', "---"},
84         {'p', ".--."},
85         {'q', "--.-"},
86         {'r', ".-."},
87         {'s', "..."},
88         {'t', "-"},
89         {'u', "..-"},
90         {'v', "...-"},
91         {'w', ".--"},
92         {'x', "-..-"},
93         {'y', "-.--"},
94         {'z', "--.."},
95
96         /* digits */
97
98         {'0', "-----"},
99         {'1', ".----"},
100         {'2', "..---"},
101         {'3', "...--"},
102         {'4', "....-"},
103         {'5', "....."},
104         {'6', "-...."},
105         {'7', "--..."},
106         {'8', "---.."},
107         {'9', "----."},
108
109         /* punctuation */
110
111         {',', "--..--"},
112         {'.', ".-.-.-"},
113         {'?', "..--.."},
114         {'/', "-..-."},
115         {'-', "-....-"},
116         {'=', "-...-"},         /* BT */
117         {':', "---..."},
118         {';', "-.-.-."},
119         {'(', "-.--."},         /* KN */
120         {')', "-.--.-"},
121         {'$', "...-..-"},
122         {'+', ".-.-."},         /* AR */
123
124         /* prosigns without already assigned values */
125
126         {'#', ".-..."},         /* AS */
127         {'@', "...-.-"},        /* SK */
128         {'*', "...-."},         /* VE */
129         {'%', "-...-.-"},       /* BK */
130
131         {'\0', ""}
132 };
133
134
135 static const struct morsetab iso8859tab[] = {
136         {'á', ".--.-"},
137         {'à', ".--.-"},
138         {'â', ".--.-"},
139         {'ä', ".-.-"},
140         {'ç', "-.-.."},
141         {'é', "..-.."},
142         {'è', "..-.."},
143         {'ê', "-..-."},
144         {'ö', "---."},
145         {'ü', "..--"},
146
147         {'\0', ""}
148 };
149
150 static const struct morsetab koi8rtab[] = {
151         /*
152          * the cyrillic alphabet; you'll need a KOI8R font in order
153          * to see the actual characters
154          */
155         {'Á', ".-"},            /* a */
156         {'Â', "-..."},  /* be */
157         {'×', ".--"},   /* ve */
158         {'Ç', "--."},   /* ge */
159         {'Ä', "-.."},   /* de */
160         {'Å', "."},             /* ye */
161         {'£', "."},             /* yo, the same as ye */
162         {'Ö', "...-"},  /* she */
163         {'Ú', "--.."},  /* ze */
164         {'É', ".."},            /* i */
165         {'Ê', ".---"},  /* i kratkoye */
166         {'Ë', "-.-"},   /* ka */
167         {'Ì', ".-.."},  /* el */
168         {'Í', "--"},            /* em */
169         {'Î', "-."},            /* en */
170         {'Ï', "---"},   /* o */
171         {'Ð', ".--."},  /* pe */
172         {'Ò', ".-."},   /* er */
173         {'Ó', "..."},   /* es */
174         {'Ô', "-"},             /* te */
175         {'Õ', "..-"},   /* u */
176         {'Æ', "..-."},  /* ef */
177         {'È', "...."},  /* kha */
178         {'Ã', "-.-."},  /* ce */
179         {'Þ', "---."},  /* che */
180         {'Û', "----"},  /* sha */
181         {'Ý', "--.-"},  /* shcha */
182         {'Ù', "-.--"},  /* yi */
183         {'Ø', "-..-"},  /* myakhkij znak */
184         {'Ü', "..-.."}, /* ae */
185         {'À', "..--"},  /* yu */
186         {'Ñ', ".-.-"},  /* ya */
187
188         {'\0', ""}
189 };
190
191 struct tone_data {
192         int16_t *data;
193         size_t  len;
194 };
195
196 void            alloc_soundbuf(struct tone_data *, double, int);
197 void            show(const char *), play(const char *), morse(char);
198 void            ttyout(const char *);
199 void            sighandler(int);
200
201 #define GETOPTOPTS "d:ef:pP:sw:"
202 #define USAGE \
203 "usage: morse [-s] [-e] [-p] [-P device] [-d device] [-w speed] [-f frequency] [string ...]\n"
204
205 static int      pflag, sflag, eflag;
206 static int      wpm = 20;       /* words per minute */
207 #define FREQUENCY 600
208 static int      freq = FREQUENCY;
209 static char     *device;        /* for tty-controlled generator */
210
211 static struct tone_data tone_dot, tone_dash, tone_silence;
212 #define DSP_RATE 44100
213 static const char *snddev = "/dev/dsp";
214
215 #define DASH_LEN 3
216 #define CHAR_SPACE 3
217 #define WORD_SPACE (7 - CHAR_SPACE)
218 static float    dot_clock;
219 int             spkr, line;
220 struct termios  otty, ntty;
221 int             olflags;
222
223 static const struct morsetab *hightab;
224
225 int
226 main(int argc, char **argv)
227 {
228         int    ch, lflags;
229         char  *p, *codeset;
230
231         while ((ch = getopt(argc, argv, GETOPTOPTS)) != -1)
232                 switch ((char) ch) {
233                 case 'd':
234                         device = optarg;
235                         break;
236                 case 'e':
237                         eflag = 1;
238                         setvbuf(stdout, 0, _IONBF, 0);
239                         break;
240                 case 'f':
241                         freq = atoi(optarg);
242                         break;
243                 case 'p':
244                         pflag = 1;
245                         break;
246                 case 'P':
247                         snddev = optarg;
248                         break;
249                 case 's':
250                         sflag = 1;
251                         break;
252                 case 'w':
253                         wpm = atoi(optarg);
254                         break;
255                 case '?':
256                 default:
257                         fputs(USAGE, stderr);
258                         exit(1);
259                 }
260         if ((pflag || device) && sflag) {
261                 fputs("morse: only one of -p, -d and -s allowed\n", stderr);
262                 exit(1);
263         }
264         if ((pflag || device) && ((wpm < 1) || (wpm > 60))) {
265                 fputs("morse: insane speed\n", stderr);
266                 exit(1);
267         }
268         if ((pflag || device) && (freq == 0))
269                 freq = FREQUENCY;
270         if (pflag || device) {
271                 dot_clock = wpm / 2.4;          /* dots/sec */
272                 dot_clock = 1 / dot_clock;      /* duration of a dot */
273                 dot_clock = dot_clock / 2;      /* dot_clock runs at twice */
274                                                 /* the dot rate */
275         }
276
277         if (pflag) {
278                 snd_chan_param param;
279
280                 if ((spkr = open(snddev, O_WRONLY, 0)) == -1)
281                         err(1, "%s", snddev);
282                 param.play_rate = DSP_RATE;
283                 param.play_format = AFMT_S16_NE;
284                 param.rec_rate = 0;
285                 param.rec_format = 0;
286                 if (ioctl(spkr, AIOSFMT, &param) != 0)
287                         err(1, "%s: set format", snddev);
288                 alloc_soundbuf(&tone_dot, dot_clock, 1);
289                 alloc_soundbuf(&tone_dash, DASH_LEN * dot_clock, 1);
290                 alloc_soundbuf(&tone_silence, dot_clock, 0);
291         } else
292         if (device) {
293                 if ((line = open(device, O_WRONLY | O_NONBLOCK)) == -1) {
294                         perror("open tty line");
295                         exit(1);
296                 }
297                 if (tcgetattr(line, &otty) == -1) {
298                         perror("tcgetattr() failed");
299                         exit(1);
300                 }
301                 ntty = otty;
302                 ntty.c_cflag |= CLOCAL;
303                 tcsetattr(line, TCSANOW, &ntty);
304                 lflags = fcntl(line, F_GETFL);
305                 lflags &= ~O_NONBLOCK;
306                 fcntl(line, F_SETFL, &lflags);
307                 ioctl(line, TIOCMGET, &lflags);
308                 lflags &= ~TIOCM_RTS;
309                 olflags = lflags;
310                 ioctl(line, TIOCMSET, &lflags);
311                 (void)signal(SIGHUP, sighandler);
312                 (void)signal(SIGINT, sighandler);
313                 (void)signal(SIGQUIT, sighandler);
314                 (void)signal(SIGTERM, sighandler);
315         }
316
317         argc -= optind;
318         argv += optind;
319
320         if (setlocale(LC_CTYPE, "") != NULL &&
321             *(codeset = nl_langinfo(CODESET)) != '\0') {
322                 if (strcmp(codeset, "KOI8-R") == 0)
323                         hightab = koi8rtab;
324                 else if (strcmp(codeset, "ISO8859-1") == 0 ||
325                          strcmp(codeset, "ISO8859-15") == 0)
326                         hightab = iso8859tab;
327         }
328
329         if (*argv) {
330                 do {
331                         for (p = *argv; *p; ++p) {
332                                 if (eflag)
333                                         putchar(*p);
334                                 morse(*p);
335                         }
336                         if (eflag)
337                                 putchar(' ');
338                         morse(' ');
339                 } while (*++argv);
340         } else {
341                 while ((ch = getchar()) != EOF) {
342                         if (eflag)
343                                 putchar(ch);
344                         morse(ch);
345                 }
346         }
347         if (device)
348                 tcsetattr(line, TCSANOW, &otty);
349         exit(0);
350 }
351
352 void
353 alloc_soundbuf(struct tone_data *tone, double len, int on)
354 {
355         int samples, i;
356
357         samples = DSP_RATE * len;
358         tone->len = samples * sizeof(*tone->data);
359         tone->data = malloc(tone->len);
360         if (tone->data == NULL)
361                 err(1, NULL);
362         if (!on) {
363                 bzero(tone->data, tone->len);
364                 return;
365         }
366
367         /*
368          * We create a sinus with the specified frequency and smooth
369          * the edges to reduce key clicks.
370          */
371         for (i = 0; i < samples; i++) {
372                 double filter = 1;
373
374 #define FILTER_SAMPLES 100
375                 if (i < FILTER_SAMPLES || i > samples - FILTER_SAMPLES) {
376                         /*
377                          * Gauss window
378                          */
379 #if 0
380                         int fi = i;
381
382                         if (i > FILTER_SAMPLES)
383                                 fi = samples - i;
384                         filter = exp(-0.5 *
385                                      pow((double)(fi - FILTER_SAMPLES) /
386                                          (0.4 * FILTER_SAMPLES), 2));
387 #else
388                         /*
389                          * Triangle window
390                          */
391                         if (i < FILTER_SAMPLES)
392                                 filter = (double)i / FILTER_SAMPLES;
393                         else
394                                 filter = (double)(samples - i) / FILTER_SAMPLES;
395 #endif
396                 }
397                 tone->data[i] = 32767 * sin((double)i / samples * len * freq * 2 * M_PI) *
398                     filter;
399         }
400 }
401
402 void
403 morse(char c)
404 {
405         const struct morsetab *m;
406
407         if (isalpha((unsigned char)c))
408                 c = tolower((unsigned char)c);
409         if ((c == '\r') || (c == '\n'))
410                 c = ' ';
411         if (c == ' ') {
412                 if (pflag) {
413                         play(" ");
414                         return;
415                 } else if (device) {
416                         ttyout(" ");
417                         return;
418                 } else {
419                         show("");
420                         return;
421                 }
422         }
423         for (m = ((unsigned char)c < 0x80? mtab: hightab);
424              m != NULL && m->inchar != '\0';
425              m++) {
426                 if (m->inchar == c) {
427                         if (pflag) {
428                                 play(m->morse);
429                         } else if (device) {
430                                 ttyout(m->morse);
431                         } else
432                                 show(m->morse);
433                 }
434         }
435 }
436
437 void
438 show(const char *s)
439 {
440         if (sflag)
441                 printf(" %s", s);
442         else
443                 for (; *s; ++s)
444                         printf(" %s", *s == '.' ? "dit" : "dah");
445         printf("\n");
446 }
447
448 void
449 play(const char *s)
450 {
451         const char *c;
452         int duration;
453         struct tone_data *tone;
454
455         /*
456          * We don't need to usleep() here, as the sound device blocks.
457          */
458         for (c = s; *c != '\0'; c++) {
459                 switch (*c) {
460                 case '.':
461                         duration = 1;
462                         tone = &tone_dot;
463                         break;
464                 case '-':
465                         duration = 1;
466                         tone = &tone_dash;
467                         break;
468                 case ' ':
469                         duration = WORD_SPACE;
470                         tone = &tone_silence;
471                         break;
472                 default:
473                         errx(1, "invalid morse digit");
474                 }
475                 while (duration-- > 0)
476                         write(spkr, tone->data, tone->len);
477                 write(spkr, tone_silence.data, tone_silence.len);
478         }
479         duration = CHAR_SPACE - 1;  /* we already waited 1 after the last symbol */
480         while (duration-- > 0)
481                 write(spkr, tone_silence.data, tone_silence.len);
482 }
483
484 void
485 ttyout(const char *s)
486 {
487         const char *c;
488         int duration, on, lflags;
489
490         for (c = s; *c != '\0'; c++) {
491                 switch (*c) {
492                 case '.':
493                         on = 1;
494                         duration = dot_clock;
495                         break;
496                 case '-':
497                         on = 1;
498                         duration = dot_clock * DASH_LEN;
499                         break;
500                 case ' ':
501                         on = 0;
502                         duration = dot_clock * WORD_SPACE;
503                         break;
504                 default:
505                         on = 0;
506                         duration = 0;
507                 }
508                 if (on) {
509                         ioctl(line, TIOCMGET, &lflags);
510                         lflags |= TIOCM_RTS;
511                         ioctl(line, TIOCMSET, &lflags);
512                 }
513                 duration *= 1000000;
514                 if (duration)
515                         usleep(duration);
516                 ioctl(line, TIOCMGET, &lflags);
517                 lflags &= ~TIOCM_RTS;
518                 ioctl(line, TIOCMSET, &lflags);
519                 duration = dot_clock * 1000000;
520                 usleep(duration);
521         }
522         duration = dot_clock * CHAR_SPACE * 1000000;
523         usleep(duration);
524 }
525
526 void
527 sighandler(int signo)
528 {
529
530         ioctl(line, TIOCMSET, &olflags);
531         tcsetattr(line, TCSANOW, &otty);
532
533         signal(signo, SIG_DFL);
534         (void)kill(getpid(), signo);
535 }