Update muted for operation on OSX. :)
[asterisk/asterisk.git] / muted.c
1 /*
2  * Mute Daemon
3  *
4  * Specially written for Malcolm Davenport, but I think I'll use it too
5  *
6  * Copyright (C)  2004 - 2005, Digium Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  * 
10  * Updated for Mac OSX CoreAudio 
11  * by Josh Roberson <josh@asteraisgi.com>
12  *
13  * Distributed under the terms of the GNU General Public License version 2.0 
14  *
15  */
16
17 #ifndef __Darwin__
18 #include <linux/soundcard.h>
19 #else
20 #include <CoreAudio/AudioHardware.h> 
21 #endif
22 #include <stdio.h>
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <string.h>
28 #include <netdb.h>
29 #include <sys/socket.h>
30 #include <sys/ioctl.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33
34 static char *config = "/etc/muted.conf";
35
36 static char host[256] = "";
37 static char user[256] = "";
38 static char pass[256] = "";
39 static int smoothfade = 0;
40 static int mutelevel = 20;
41 static int muted = 0;
42 static int needfork = 1;
43 static int debug = 0;
44 static int stepsize = 3;
45 #ifndef __Darwin__
46 static int mixchan = SOUND_MIXER_VOLUME;
47 #endif
48
49 struct subchannel {
50         char *name;
51         struct subchannel *next;
52 };
53
54 static struct channel {
55         char *tech;
56         char *location;
57         struct channel *next;
58         struct subchannel *subs;
59 } *channels;
60
61 static void add_channel(char *tech, char *location)
62 {
63         struct channel *chan;
64         chan = malloc(sizeof(struct channel));
65         if (chan) {
66                 memset(chan, 0, sizeof(struct channel));
67                 chan->tech = strdup(tech);
68                 chan->location = strdup(location);
69                 chan->next = channels;
70                 channels = chan;
71         }
72         
73 }
74
75 static int load_config(void)
76 {
77         FILE *f;
78         char buf[1024];
79         char *val;
80         char *val2;
81         int lineno=0;
82         int x;
83         f = fopen(config, "r");
84         if (!f) {
85                 fprintf(stderr, "Unable to open config file '%s': %s\n", config, strerror(errno));
86                 return -1;
87         }
88         while(!feof(f)) {
89                 fgets(buf, sizeof(buf), f);
90                 if (!feof(f)) {
91                         lineno++;
92                         val = strchr(buf, '#');
93                         if (val) *val = '\0';
94                         while(strlen(buf) && (buf[strlen(buf) - 1] < 33))
95                                 buf[strlen(buf) - 1] = '\0';
96                         if (!strlen(buf))
97                                 continue;
98                         val = buf;
99                         while(*val) {
100                                 if (*val < 33)
101                                         break;
102                                 val++;
103                         }
104                         if (*val) {
105                                 *val = '\0';
106                                 val++;
107                                 while(*val && (*val < 33)) val++;
108                         }
109                         if (!strcasecmp(buf, "host")) {
110                                 if (val && strlen(val))
111                                         strncpy(host, val, sizeof(host) - 1);
112                                 else
113                                         fprintf(stderr, "host needs an argument (the host) at line %d\n", lineno);
114                         } else if (!strcasecmp(buf, "user")) {
115                                 if (val && strlen(val))
116                                         strncpy(user, val, sizeof(user) - 1);
117                                 else
118                                         fprintf(stderr, "user needs an argument (the user) at line %d\n", lineno);
119                         } else if (!strcasecmp(buf, "pass")) {
120                                 if (val && strlen(val))
121                                         strncpy(pass, val, sizeof(pass) - 1);
122                                 else
123                                         fprintf(stderr, "pass needs an argument (the password) at line %d\n", lineno);
124                         } else if (!strcasecmp(buf, "smoothfade")) {
125                                 smoothfade = 1;
126                         } else if (!strcasecmp(buf, "mutelevel")) {
127                                 if (val && (sscanf(val, "%d", &x) == 1) && (x > -1) && (x < 101)) {
128                                         mutelevel = x;
129                                 } else 
130                                         fprintf(stderr, "mutelevel must be a number from 0 (most muted) to 100 (no mute) at line %d\n", lineno);
131                         } else if (!strcasecmp(buf, "channel")) {
132                                 if (val && strlen(val)) {
133                                         val2 = strchr(val, '/');
134                                         if (val2) {
135                                                 *val2 = '\0';
136                                                 val2++;
137                                                 add_channel(val, val2);
138                                         } else
139                                                 fprintf(stderr, "channel needs to be of the format Tech/Location at line %d\n", lineno);
140                                 } else
141                                         fprintf(stderr, "channel needs an argument (the channel) at line %d\n", lineno);
142                         } else {
143                                 fprintf(stderr, "ignoring unknown keyword '%s'\n", buf);
144                         }
145                 }
146         }
147         fclose(f);
148         if (!strlen(host))
149                 fprintf(stderr, "no 'host' specification in config file\n");
150         else if (!strlen(user))
151                 fprintf(stderr, "no 'user' specification in config file\n");
152         else if (!channels) 
153                 fprintf(stderr, "no 'channel' specifications in config file\n");
154         else
155                 return 0;
156         return -1;
157 }
158
159 static FILE *astf;
160 #ifndef __Darwin__
161 static int mixfd;
162
163 static int open_mixer(void)
164 {
165         mixfd = open("/dev/mixer", O_RDWR);
166         if (mixfd < 0) {
167                 fprintf(stderr, "Unable to open /dev/mixer: %s\n", strerror(errno));
168                 return -1;
169         }
170         return 0;
171 }
172 #endif /* !__Darwin */
173
174 static int connect_asterisk(void)
175 {
176         int sock;
177         struct hostent *hp;
178         char *ports;
179         int port = 5038;
180         struct sockaddr_in sin;
181         ports = strchr(host, ':');
182         if (ports) {
183                 *ports = '\0';
184                 ports++;
185                 if ((sscanf(ports, "%d", &port) != 1) || (port < 1) || (port > 65535)) {
186                         fprintf(stderr, "'%s' is not a valid port number in the hostname\n", ports);
187                         return -1;
188                 }
189         }
190         hp = gethostbyname(host);
191         if (!hp) {
192                 fprintf(stderr, "Can't find host '%s'\n", host);
193                 return -1;
194         }
195         sock = socket(AF_INET, SOCK_STREAM, 0);
196         if (sock < 0) {
197                 fprintf(stderr, "Failed to create socket: %s\n", strerror(errno));
198                 return -1;
199         }
200         sin.sin_family = AF_INET;
201         sin.sin_port = htons(port);
202         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
203         if (connect(sock, &sin, sizeof(sin))) {
204                 fprintf(stderr, "Failed to connect to '%s' port '%d': %s\n", host, port, strerror(errno));
205                 close(sock);
206                 return -1;
207         }
208         astf = fdopen(sock, "r+");
209         if (!astf) {
210                 fprintf(stderr, "fdopen failed: %s\n", strerror(errno));
211                 close(sock);
212                 return -1;
213         }
214         return 0;
215 }
216
217 static char *get_line(void)
218 {
219         static char buf[1024];
220         if (fgets(buf, sizeof(buf), astf)) {
221                 while(strlen(buf) && (buf[strlen(buf) - 1] < 33))
222                         buf[strlen(buf) - 1] = '\0';
223                 return buf;
224         } else
225                 return NULL;
226 }
227
228 static int login_asterisk(void)
229 {
230         char *welcome;
231         char *resp;
232         if (!(welcome = get_line())) {
233                 fprintf(stderr, "disconnected (1)\n");
234                 return -1;
235         }
236         fprintf(astf, 
237                 "Action: Login\r\n"
238                 "Username: %s\r\n"
239                 "Secret: %s\r\n\r\n", user, pass);
240         if (!(welcome = get_line())) {
241                 fprintf(stderr, "disconnected (2)\n");
242                 return -1;
243         }
244         if (strcasecmp(welcome, "Response: Success")) {
245                 fprintf(stderr, "login failed ('%s')\n", welcome);
246                 return -1;
247         }
248         /* Eat the rest of the event */
249         while((resp = get_line()) && strlen(resp));
250         if (!resp) {
251                 fprintf(stderr, "disconnected (3)\n");
252                 return -1;
253         }
254         fprintf(astf, 
255                 "Action: Status\r\n\r\n");
256         if (!(welcome = get_line())) {
257                 fprintf(stderr, "disconnected (4)\n");
258                 return -1;
259         }
260         if (strcasecmp(welcome, "Response: Success")) {
261                 fprintf(stderr, "status failed ('%s')\n", welcome);
262                 return -1;
263         }
264         /* Eat the rest of the event */
265         while((resp = get_line()) && strlen(resp));
266         if (!resp) {
267                 fprintf(stderr, "disconnected (5)\n");
268                 return -1;
269         }
270         return 0;
271 }
272
273 static struct channel *find_channel(char *channel)
274 {
275         char tmp[256] = "";
276         char *s, *t;
277         struct channel *chan;
278         strncpy(tmp, channel, sizeof(tmp) - 1);
279         s = strchr(tmp, '/');
280         if (s) {
281                 *s = '\0';
282                 s++;
283                 t = strrchr(s, '-');
284                 if (t) {
285                         *t = '\0';
286                 }
287                 if (debug)
288                         printf("Searching for '%s' tech, '%s' location\n", tmp, s);
289                 chan = channels;
290                 while(chan) {
291                         if (!strcasecmp(chan->tech, tmp) && !strcasecmp(chan->location, s)) {
292                                 if (debug)
293                                         printf("Found '%s'/'%s'\n", chan->tech, chan->location);
294                                 break;
295                         }
296                         chan = chan->next;
297                 }
298         } else
299                 chan = NULL;
300         return chan;
301 }
302
303 #ifndef __Darwin__
304 static int getvol(void)
305 {
306         int vol;
307
308         if (ioctl(mixfd, MIXER_READ(mixchan), &vol)) {
309 #else
310 static float getvol(void)
311 {
312         float volumeL, volumeR, vol;
313         OSStatus err;
314         AudioDeviceID device;
315         UInt32 size;
316         UInt32 channels[2];
317
318         size = sizeof(device);
319         err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &size, &device);
320         size = sizeof(channels);
321         if (!err) 
322                 err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyPreferredChannelsForStereo, &size, &channels);
323         size = sizeof(vol);
324         if (!err)
325                 err = AudioDeviceGetProperty(device, channels[0], false, kAudioDevicePropertyVolumeScalar, &size, &volumeL);
326         if (!err)
327                 err = AudioDeviceGetProperty(device, channels[1], false, kAudioDevicePropertyVolumeScalar, &size, &volumeR);
328         printf("volumeL = %f - volumeR = %f\n", volumeL, volumeR);
329         if (!err)
330                 vol = (volumeL < volumeR) ? volumeR : volumeL;
331         else {
332 #endif
333                 fprintf(stderr, "Unable to read mixer volume: %s\n", strerror(errno));
334                 return -1;
335         }
336         return vol;
337 }
338
339 #ifndef __Darwin__
340 static int setvol(int vol)
341 #else
342 static int setvol(float vol)
343 #endif
344 {
345 #ifndef __Darwin__
346         if (ioctl(mixfd, MIXER_WRITE(mixchan), &vol)) {
347 #else   
348         float volumeL = vol;
349         float volumeR = vol;
350         OSStatus err;
351         AudioDeviceID device;
352         UInt32 size;
353         UInt32 channels[2];
354
355         size = sizeof(device);
356         err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &size, &device);
357         size = sizeof(channels);
358         err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyPreferredChannelsForStereo, &size, &channels);
359         size = sizeof(vol);
360         if (!err)
361                 err = AudioDeviceSetProperty(device, 0, channels[0], false, kAudioDevicePropertyVolumeScalar, size, &volumeL);
362         if (!err)
363                 err = AudioDeviceSetProperty(device, 0, channels[1], false, kAudioDevicePropertyVolumeScalar, size, &volumeR); 
364         if (err) {
365 #endif
366
367                 fprintf(stderr, "Unable to write mixer volume: %s\n", strerror(errno));
368                 return -1;
369
370         }
371         return 0;
372 }
373
374 #ifndef __Darwin__
375 static int oldvol = 0;
376 static int mutevol = 0;
377 #else
378 static float oldvol = 0;
379 static float mutevol = 0;
380 #endif
381
382 static int mutedlevel(int orig, int mutelevel)
383 {
384         int l = orig >> 8;
385         int r = orig & 0xff;
386         l = (float)(mutelevel) * (float)(l) / 100.0;
387         r = (float)(mutelevel) * (float)(r) / 100.0;
388         return (l << 8) | r;
389 }
390
391 static void mute(void)
392 {
393 #ifndef __Darwin__
394         int vol;
395 #else
396         float vol;
397 #endif
398         int start;
399         int x;
400         vol = getvol();
401         oldvol = vol;
402         if (smoothfade) 
403                 start = 100;
404         else
405                 start = mutelevel;
406         for (x=start;x>=mutelevel;x-=stepsize) {
407                 mutevol = mutedlevel(vol, x);
408                 setvol(mutevol);
409                 /* Wait 0.01 sec */
410                 usleep(10000);
411         }
412         mutevol = mutedlevel(vol, mutelevel);
413         setvol(mutevol);
414         if (debug)
415 #ifdef __Darwin__
416                 printf("Mute from '%f' to '%f'!\n", oldvol, mutevol);
417 #else
418                 printf("Mute from '%04x' to '%04x'!\n", oldvol, mutevol);
419 #endif
420         muted = 1;
421 }
422
423 static void unmute(void)
424 {
425 #ifdef __Darwin__
426         float vol;
427 #else
428         int vol;
429 #endif
430         int start;
431         int x;
432         vol = getvol();
433         if (debug)
434 #ifdef __Darwin__
435                 printf("Unmute from '%f' (should be '%f') to '%f'!\n", vol, mutevol, oldvol);
436 #else
437                 printf("Unmute from '%04x' (should be '%04x') to '%04x'!\n", vol, mutevol, oldvol);
438 #endif
439         if ((int)vol == mutevol) {
440                 if (smoothfade)
441                         start = mutelevel;
442                 else
443                         start = 100;
444                 for (x=start;x<100;x+=stepsize) {
445                         mutevol = mutedlevel(oldvol, x);
446                         setvol(mutevol);
447                         /* Wait 0.01 sec */
448                         usleep(10000);
449                 }
450                 setvol(oldvol);
451         } else
452                 printf("Whoops, it's already been changed!\n");
453         muted = 0;
454 }
455
456 static void check_mute(void)
457 {
458         int offhook = 0;
459         struct channel *chan;
460         chan = channels;
461         while(chan) {
462                 if (chan->subs) {
463                         offhook++;
464                         break;
465                 }
466                 chan = chan->next;
467         }
468         if (offhook && !muted)
469                 mute();
470         else if (!offhook && muted)
471                 unmute();
472 }
473
474 static void delete_sub(struct channel *chan, char *name)
475 {
476         struct subchannel *sub, *prev;
477         prev = NULL;
478         sub = chan->subs;
479         while(sub) {
480                 if (!strcasecmp(sub->name, name)) {
481                         if (prev)
482                                 prev->next = sub->next;
483                         else
484                                 chan->subs = sub->next;
485                         free(sub->name);
486                         free(sub);
487                         return;
488                 }
489                 prev = sub;
490                 sub = sub->next;
491         }
492 }
493
494 static void append_sub(struct channel *chan, char *name)
495 {
496         struct subchannel *sub;
497         sub = chan->subs;
498         while(sub) {
499                 if (!strcasecmp(sub->name, name)) 
500                         return;
501                 sub = sub->next;
502         }
503         sub = malloc(sizeof(struct subchannel));
504         if (sub) {
505                 memset(sub, 0, sizeof(struct subchannel));
506                 sub->name = strdup(name);
507                 sub->next = chan->subs;
508                 chan->subs = sub;
509         }
510 }
511
512 static void hangup_chan(char *channel)
513 {
514         struct channel *chan;
515         if (debug)
516                 printf("Hangup '%s'\n", channel);
517         chan = find_channel(channel);
518         if (chan)
519                 delete_sub(chan, channel);
520         check_mute();
521 }
522
523 static void offhook_chan(char *channel)
524 {
525         struct channel *chan;
526         if (debug)
527                 printf("Offhook '%s'\n", channel);
528         chan = find_channel(channel);
529         if (chan)
530                 append_sub(chan, channel);
531         check_mute();
532 }
533
534 static int wait_event(void)
535 {
536         char *resp;
537         char event[120]="";
538         char channel[120]="";
539         char oldname[120]="";
540         char newname[120]="";
541         resp = get_line();
542         if (!resp) {
543                 fprintf(stderr, "disconnected (6)\n");
544                 return -1;
545         }
546         if (!strncasecmp(resp, "Event: ", strlen("Event: "))) {
547                 strncpy(event, resp + strlen("Event: "), sizeof(event) - 1);
548                 /* Consume the rest of the non-event */
549                 while((resp = get_line()) && strlen(resp)) {
550                         if (!strncasecmp(resp, "Channel: ", strlen("Channel: ")))
551                                 strncpy(channel, resp + strlen("Channel: "), sizeof(channel) - 1);
552                         if (!strncasecmp(resp, "Newname: ", strlen("Newname: ")))
553                                 strncpy(newname, resp + strlen("Newname: "), sizeof(newname) - 1);
554                         if (!strncasecmp(resp, "Oldname: ", strlen("Oldname: ")))
555                                 strncpy(oldname, resp + strlen("Oldname: "), sizeof(oldname) - 1);
556                 }
557                 if (strlen(channel)) {
558                         if (!strcasecmp(event, "Hangup")) 
559                                 hangup_chan(channel);
560                         else
561                                 offhook_chan(channel);
562                 }
563                 if (strlen(newname) && strlen(oldname)) {
564                         if (!strcasecmp(event, "Rename")) {
565                                 hangup_chan(oldname);
566                                 offhook_chan(newname);
567                         }
568                 }
569         } else {
570                 /* Consume the rest of the non-event */
571                 while((resp = get_line()) && strlen(resp));
572         }
573         if (!resp) {
574                 fprintf(stderr, "disconnected (7)\n");
575                 return -1;
576         }
577         return 0;
578 }
579
580 static void usage(void)
581 {
582         printf("Usage: muted [-f] [-d]\n"
583                "        -f : Do not fork\n"
584                    "        -d : Debug (implies -f)\n");
585 }
586
587 int main(int argc, char *argv[])
588 {
589         int x;
590         while((x = getopt(argc, argv, "fhd")) > 0) {
591                 switch(x) {
592                 case 'd':
593                         debug = 1;
594                         needfork = 0;
595                         break;
596                 case 'f':
597                         needfork = 0;
598                         break;
599                 case 'h':
600                         /* Fall through */
601                 default:
602                         usage();
603                         exit(1);
604                 }
605         }
606         if (load_config())
607                 exit(1);
608 #ifndef __Darwin__
609         if (open_mixer())
610                 exit(1);
611 #endif
612         if (connect_asterisk()) {
613 #ifndef __Darwin__
614                 close(mixfd);
615 #endif
616                 exit(1);
617         }
618         if (login_asterisk()) {
619 #ifndef __Darwin__              
620                 close(mixfd);
621 #endif
622                 fclose(astf);
623                 exit(1);
624         }
625         if (needfork)
626                 daemon(0,0);
627         for(;;) {
628                 if (wait_event()) {
629                         fclose(astf);
630                         while(connect_asterisk()) {
631                                 sleep(5);
632                         }
633                         if (login_asterisk()) {
634                                 fclose(astf);
635                                 exit(1);
636                         }
637                 }
638         }
639         exit(0);
640 }