]> git.deb.at Git - pkg/beep.git/blob - beep.c
Imported Debian patch 1.2.2-16
[pkg/beep.git] / beep.c
1 /*  beep - just what it sounds like, makes the console beep - but with
2  * precision control.  See the man page for details.
3  *
4  * Try beep -h for command line args
5  *
6  * This code is copyright (C) Johnathan Nightingale, 2000.
7  *
8  * This code may distributed only under the terms of the GNU Public License 
9  * which can be found at http://www.gnu.org/copyleft or in the file COPYING 
10  * supplied with this code.
11  *
12  * This code is not distributed with warranties of any kind, including implied
13  * warranties of merchantability or fitness for a particular use or ability to 
14  * breed pandas in captivity, it just can't be done.
15  *
16  * Bug me, I like it:  http://johnath.com/  or johnath@johnath.com
17  */
18
19 #include <fcntl.h>
20 #include <getopt.h>
21 #include <signal.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/ioctl.h>
27 #include <sys/types.h>
28 #include <linux/kd.h>
29
30 /* I don't know where this number comes from, I admit that freely.  A 
31    wonderful human named Raine M. Ekman used it in a program that played
32    a tune at the console, and apparently, it's how the kernel likes its
33    sound requests to be phrased.  If you see Raine, thank him for me.  
34    
35    June 28, email from Peter Tirsek (peter at tirsek dot com):
36    
37    This number represents the fixed frequency of the original PC XT's
38    timer chip (the 8254 AFAIR), which is approximately 1.193 MHz. This
39    number is divided with the desired frequency to obtain a counter value,
40    that is subsequently fed into the timer chip, tied to the PC speaker.
41    The chip decreases this counter at every tick (1.193 MHz) and when it
42    reaches zero, it toggles the state of the speaker (on/off, or in/out),
43    resets the counter to the original value, and starts over. The end
44    result of this is a tone at approximately the desired frequency. :)
45 */
46 #ifndef CLOCK_TICK_RATE
47 #define CLOCK_TICK_RATE 1193180
48 #endif
49
50 #define VERSION_STRING "beep-1.2.2"
51 char *copyright = 
52 "Copyright (C) Johnathan Nightingale, 2002.  "
53 "Use and Distribution subject to GPL.  "
54 "For information: http://www.gnu.org/copyleft/.";
55
56 /* Meaningful Defaults */
57 #define DEFAULT_FREQ       440.0 /* Middle A */
58 #define DEFAULT_LENGTH     200   /* milliseconds */
59 #define DEFAULT_REPS       1
60 #define DEFAULT_DELAY      100   /* milliseconds */
61 #define DEFAULT_END_DELAY  NO_END_DELAY
62 #define DEFAULT_STDIN_BEEP NO_STDIN_BEEP
63
64 /* Other Constants */
65 #define NO_END_DELAY    0
66 #define YES_END_DELAY   1
67
68 #define NO_STDIN_BEEP   0
69 #define LINE_STDIN_BEEP 1
70 #define CHAR_STDIN_BEEP 2
71
72 typedef struct beep_parms_t {
73   float freq;     /* tone frequency (Hz)      */
74   int length;     /* tone length    (ms)      */
75   int reps;       /* # of repetitions         */
76   int delay;      /* delay between reps  (ms) */
77   int end_delay;  /* do we delay after last rep? */
78   int stdin_beep; /* are we using stdin triggers?  We have three options:
79                      - just beep and terminate (default)
80                      - beep after a line of input
81                      - beep after a character of input
82                      In the latter two cases, pass the text back out again,
83                      so that beep can be tucked appropriately into a text-
84                      processing pipe.
85                   */
86   int verbose;    /* verbose output?          */
87   struct beep_parms_t *next;  /* in case -n/--new is used. */
88 } beep_parms_t;
89
90 /* Momma taught me never to use globals, but we need something the signal 
91    handlers can get at.*/
92 int console_fd = -1;
93
94 /* If we get interrupted, it would be nice to not leave the speaker beeping in
95    perpetuity. */
96 void handle_signal(int signum) {
97   switch(signum) {
98   case SIGINT:
99     if(console_fd >= 0) {
100       /* Kill the sound, quit gracefully */
101       ioctl(console_fd, KIOCSOUND, 0);
102       close(console_fd);
103       exit(signum);
104     } else {
105       /* Just quit gracefully */
106       exit(signum);
107     }
108   }
109 }
110
111 /* print usage and exit */
112 void usage_bail(const char *executable_name) {
113   printf("Usage:\n%s [-f freq] [-l length] [-r reps] [-d delay] "
114          "[-D delay] [-s] [-c]\n",
115          executable_name);
116   printf("%s [Options...] [-n] [--new] [Options...] ... \n", executable_name);
117   printf("%s [-h] [--help]\n", executable_name);
118   printf("%s [-v] [-V] [--version]\n", executable_name);
119   exit(1);
120 }
121
122
123 /* Parse the command line.  argv should be untampered, as passed to main.
124  * Beep parameters returned in result, subsequent parameters in argv will over-
125  * ride previous ones.
126  * 
127  * Currently valid parameters:
128  *  "-f <frequency in Hz>"
129  *  "-l <tone length in ms>"
130  *  "-r <repetitions>"
131  *  "-d <delay in ms>"
132  *  "-D <delay in ms>" (similar to -d, but delay after last repetition as well)
133  *  "-s" (beep after each line of input from stdin, echo line to stdout)
134  *  "-c" (beep after each char of input from stdin, echo char to stdout)
135  *  "--verbose/--debug"
136  *  "-h/--help"
137  *  "-v/-V/--version"
138  *  "-n/--new"
139  *
140  * March 29, 2002 - Daniel Eisenbud points out that c should be int, not char,
141  * for correctness on platforms with unsigned chars.
142  */
143 void parse_command_line(int argc, char **argv, beep_parms_t *result) {
144   int c;
145
146   struct option opt_list[6] = {{"help", 0, NULL, 'h'},
147                                {"version", 0, NULL, 'V'},
148                                {"new", 0, NULL, 'n'},
149                                {"verbose", 0, NULL, 'X'},
150                                {"debug", 0, NULL, 'X'},
151                                {0,0,0,0}};
152   while((c = getopt_long(argc, argv, "f:l:r:d:D:schvVn", opt_list, NULL))
153         != EOF) {
154     int argval = -1;    /* handle parsed numbers for various arguments */
155     float argfreq = -1; 
156     switch(c) {      
157     case 'f':  /* freq */
158       if(!sscanf(optarg, "%f", &argfreq) || (argfreq >= 20000 /* ack! */) || 
159          (argfreq <= 0))
160         usage_bail(argv[0]);
161       else
162         if (result->freq != 0)
163           fprintf(stderr, "WARNING: multiple -f values given, only last "
164             "one is used.\n");
165         result->freq = argfreq;    
166       break;
167     case 'l' : /* length */
168       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
169         usage_bail(argv[0]);
170       else
171         result->length = argval;
172       break;
173     case 'r' : /* repetitions */
174       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
175         usage_bail(argv[0]);
176       else
177         result->reps = argval;
178       break;
179     case 'd' : /* delay between reps - WITHOUT delay after last beep*/
180       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
181         usage_bail(argv[0]);
182       else {
183         result->delay = argval;
184         result->end_delay = NO_END_DELAY;
185       }
186       break;
187     case 'D' : /* delay between reps - WITH delay after last beep */
188       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
189         usage_bail(argv[0]);
190       else {
191         result->delay = argval;
192         result->end_delay = YES_END_DELAY;
193       }
194       break;
195     case 's' :
196       result->stdin_beep = LINE_STDIN_BEEP;
197       break;
198     case 'c' :
199       result->stdin_beep = CHAR_STDIN_BEEP;
200       break;
201     case 'v' :
202     case 'V' : /* also --version */
203       printf("%s\n",VERSION_STRING);
204       exit(0);
205       break;
206     case 'n' : /* also --new - create another beep */
207       if (result->freq == 0)
208         result->freq = DEFAULT_FREQ;
209       result->next = (beep_parms_t *)malloc(sizeof(beep_parms_t));
210       result->next->freq       = 0;
211       result->next->length     = DEFAULT_LENGTH;
212       result->next->reps       = DEFAULT_REPS;
213       result->next->delay      = DEFAULT_DELAY;
214       result->next->end_delay  = DEFAULT_END_DELAY;
215       result->next->stdin_beep = DEFAULT_STDIN_BEEP;
216       result->next->verbose    = result->verbose;
217       result->next->next       = NULL;
218       result = result->next; /* yes, I meant to do that. */
219       break;
220     case 'X' : /* --debug / --verbose */
221       result->verbose = 1;
222       break;
223     case 'h' : /* notice that this is also --help */
224     default :
225       usage_bail(argv[0]);
226     }
227   }
228 }  
229
230 void play_beep(beep_parms_t parms) {
231   int i; /* loop counter */
232
233   if(parms.verbose == 1)
234       fprintf(stderr, "[DEBUG] %d times %d ms beeps (%d delay between, "
235         "%d delay after) @ %.2f Hz\n",
236         parms.reps, parms.length, parms.delay, parms.end_delay, parms.freq);
237
238   /* try to snag the console */
239   if((console_fd = open("/dev/tty0", O_WRONLY)) == -1) {
240     if((console_fd = open("/dev/vc/0", O_WRONLY)) == -1) {
241       fprintf(stderr, "Could not open /dev/tty0 or /dev/vc/0 for writing.\n");
242       printf("\a");  /* Output the only beep we can, in an effort to fall back on usefulness */
243       perror("open");
244       exit(1);
245     }
246   }
247   
248   /* Beep */
249   for (i = 0; i < parms.reps; i++) {                    /* start beep */
250     if(ioctl(console_fd, KIOCSOUND, (int)(CLOCK_TICK_RATE/parms.freq)) < 0) {
251       printf("\a");  /* Output the only beep we can, in an effort to fall back on usefulness */
252       perror("ioctl");
253     }
254     /* Look ma, I'm not ansi C compatible! */
255     usleep(1000*parms.length);                          /* wait...    */
256     ioctl(console_fd, KIOCSOUND, 0);                    /* stop beep  */
257     if(parms.end_delay || (i+1 < parms.reps))
258        usleep(1000*parms.delay);                        /* wait...    */
259   }                                                     /* repeat.    */
260
261   close(console_fd);
262 }
263
264
265
266 int main(int argc, char **argv) {
267   char sin[4096], *ptr;
268   
269   beep_parms_t *parms = (beep_parms_t *)malloc(sizeof(beep_parms_t));
270   parms->freq       = 0;
271   parms->length     = DEFAULT_LENGTH;
272   parms->reps       = DEFAULT_REPS;
273   parms->delay      = DEFAULT_DELAY;
274   parms->end_delay  = DEFAULT_END_DELAY;
275   parms->stdin_beep = DEFAULT_STDIN_BEEP;
276   parms->verbose    = 0;
277   parms->next       = NULL;
278
279   signal(SIGINT, handle_signal);
280   parse_command_line(argc, argv, parms);
281
282   /* this outermost while loop handles the possibility that -n/--new has been
283      used, i.e. that we have multiple beeps specified. Each iteration will
284      play, then free() one parms instance. */
285   while(parms) {
286     beep_parms_t *next = parms->next;
287
288     if(parms->stdin_beep) {
289       /* in this case, beep is probably part of a pipe, in which case POSIX 
290          says stdin and out should be fuly buffered.  This however means very 
291          laggy performance with beep just twiddling it's thumbs until a buffer
292          fills. Thus, kill the buffering.  In some situations, this too won't 
293          be enough, namely if we're in the middle of a long pipe, and the 
294          processes feeding us stdin are buffered, we'll have to wait for them,
295          not much to  be done about that. */
296       setvbuf(stdin, NULL, _IONBF, 0);
297       setvbuf(stdout, NULL, _IONBF, 0);
298       while(fgets(sin, 4096, stdin)) {
299         if(parms->stdin_beep==CHAR_STDIN_BEEP) {
300           for(ptr=sin;*ptr;ptr++) {
301             putchar(*ptr);
302             fflush(stdout);
303             play_beep(*parms);
304           }
305         } else {
306           fputs(sin, stdout);
307           play_beep(*parms);
308         }
309       }
310     } else {
311       play_beep(*parms);
312     }
313
314     /* Junk each parms struct after playing it */
315     free(parms);
316     parms = next;
317   }
318
319   return EXIT_SUCCESS;
320 }