]> git.deb.at Git - pkg/beep.git/blob - beep.c
Gerfried's debug/verbose support
[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] [--verbose | --debug]\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         result->freq = argfreq;    
163       break;
164     case 'l' : /* length */
165       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
166         usage_bail(argv[0]);
167       else
168         result->length = argval;
169       break;
170     case 'r' : /* repetitions */
171       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
172         usage_bail(argv[0]);
173       else
174         result->reps = argval;
175       break;
176     case 'd' : /* delay between reps - WITHOUT delay after last beep*/
177       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
178         usage_bail(argv[0]);
179       else {
180         result->delay = argval;
181         result->end_delay = NO_END_DELAY;
182       }
183       break;
184     case 'D' : /* delay between reps - WITH delay after last beep */
185       if(!sscanf(optarg, "%d", &argval) || (argval < 0))
186         usage_bail(argv[0]);
187       else {
188         result->delay = argval;
189         result->end_delay = YES_END_DELAY;
190       }
191       break;
192     case 's' :
193       result->stdin_beep = LINE_STDIN_BEEP;
194       break;
195     case 'c' :
196       result->stdin_beep = CHAR_STDIN_BEEP;
197       break;
198     case 'v' :
199     case 'V' : /* also --version */
200       printf("%s\n",VERSION_STRING);
201       exit(0);
202       break;
203     case 'n' : /* also --new - create another beep */
204       result->next = (beep_parms_t *)malloc(sizeof(beep_parms_t));
205       result->next->freq       = DEFAULT_FREQ;
206       result->next->length     = DEFAULT_LENGTH;
207       result->next->reps       = DEFAULT_REPS;
208       result->next->delay      = DEFAULT_DELAY;
209       result->next->end_delay  = DEFAULT_END_DELAY;
210       result->next->stdin_beep = DEFAULT_STDIN_BEEP;
211       result->next->verbose    = result->verbose;
212       result->next->next       = NULL;
213       result = result->next; /* yes, I meant to do that. */
214       break;
215     case 'X' : /* --debug / --verbose */
216       result->verbose = 1;
217       break;
218     case 'h' : /* notice that this is also --help */
219     default :
220       usage_bail(argv[0]);
221     }
222   }
223 }  
224
225 void play_beep(beep_parms_t parms) {
226   int i; /* loop counter */
227
228   if(parms.verbose == 1)
229       fprintf(stderr, "[DEBUG] %d times %d ms beeps (%d delay between, "
230         "%d delay after) @ %.2f Hz\n",
231         parms.reps, parms.length, parms.delay, parms.end_delay, parms.freq);
232
233   /* try to snag the console */
234   if((console_fd = open("/dev/console", O_WRONLY)) == -1) {
235     fprintf(stderr, "Could not open /dev/console for writing.\n");
236     printf("\a");  /* Output the only beep we can, in an effort to fall back on usefulness */
237     perror("open");
238     exit(1);
239   }
240   
241   /* Beep */
242   for (i = 0; i < parms.reps; i++) {                    /* start beep */
243     if(ioctl(console_fd, KIOCSOUND, (int)(CLOCK_TICK_RATE/parms.freq)) < 0) {
244       printf("\a");  /* Output the only beep we can, in an effort to fall back on usefulness */
245       perror("ioctl");
246     }
247     /* Look ma, I'm not ansi C compatible! */
248     usleep(1000*parms.length);                          /* wait...    */
249     ioctl(console_fd, KIOCSOUND, 0);                    /* stop beep  */
250     if(parms.end_delay || (i+1 < parms.reps))
251        usleep(1000*parms.delay);                        /* wait...    */
252   }                                                     /* repeat.    */
253
254   close(console_fd);
255 }
256
257
258
259 int main(int argc, char **argv) {
260   char sin[4096], *ptr;
261   
262   beep_parms_t *parms = (beep_parms_t *)malloc(sizeof(beep_parms_t));
263   parms->freq       = DEFAULT_FREQ;
264   parms->length     = DEFAULT_LENGTH;
265   parms->reps       = DEFAULT_REPS;
266   parms->delay      = DEFAULT_DELAY;
267   parms->end_delay  = DEFAULT_END_DELAY;
268   parms->stdin_beep = DEFAULT_STDIN_BEEP;
269   parms->verbose    = 0;
270   parms->next       = NULL;
271
272   signal(SIGINT, handle_signal);
273   parse_command_line(argc, argv, parms);
274
275   /* this outermost while loop handles the possibility that -n/--new has been
276      used, i.e. that we have multiple beeps specified. Each iteration will
277      play, then free() one parms instance. */
278   while(parms) {
279     beep_parms_t *next = parms->next;
280
281     if(parms->stdin_beep) {
282       /* in this case, beep is probably part of a pipe, in which case POSIX 
283          says stdin and out should be fuly buffered.  This however means very 
284          laggy performance with beep just twiddling it's thumbs until a buffer
285          fills. Thus, kill the buffering.  In some situations, this too won't 
286          be enough, namely if we're in the middle of a long pipe, and the 
287          processes feeding us stdin are buffered, we'll have to wait for them,
288          not much to  be done about that. */
289       setvbuf(stdin, NULL, _IONBF, 0);
290       setvbuf(stdout, NULL, _IONBF, 0);
291       while(fgets(sin, 4096, stdin)) {
292         if(parms->stdin_beep==CHAR_STDIN_BEEP) {
293           for(ptr=sin;*ptr;ptr++) {
294             putchar(*ptr);
295             fflush(stdout);
296             play_beep(*parms);
297           }
298         } else {
299           fputs(sin, stdout);
300           play_beep(*parms);
301         }
302       }
303     } else {
304       play_beep(*parms);
305     }
306
307     /* Junk each parms struct after playing it */
308     free(parms);
309     parms = next;
310   }
311
312   return EXIT_SUCCESS;
313 }