Add peercontext parameter for default outbound context (bug #1929)
[asterisk/asterisk.git] / channels / chan_alsa.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Copyright (C) 2002, Linux Support Services
5  *
6  * By Matthew Fredrickson <creslin@linux-support.net>
7  *
8  * This program is free software, distributed under the terms of
9  * the GNU General Public License
10  */
11
12 #include <asterisk/frame.h>
13 #include <asterisk/logger.h>
14 #include <asterisk/channel.h>
15 #include <asterisk/module.h>
16 #include <asterisk/channel_pvt.h>
17 #include <asterisk/options.h>
18 #include <asterisk/pbx.h>
19 #include <asterisk/config.h>
20 #include <asterisk/cli.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/time.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29
30 #define ALSA_PCM_NEW_HW_PARAMS_API
31 #define ALSA_PCM_NEW_SW_PARAMS_API
32 #include <alsa/asoundlib.h>
33
34 #include "busy.h"
35 #include "ringtone.h"
36 #include "ring10.h"
37 #include "answer.h"
38
39 #ifdef ALSA_MONITOR
40 #include "alsa-monitor.h"
41 #endif
42
43 #define DEBUG 0
44 /* Which device to use */
45 #define ALSA_INDEV "default"
46 #define ALSA_OUTDEV "default"
47 #define DESIRED_RATE 8000
48
49 /* Lets use 160 sample frames, just like GSM.  */
50 #define FRAME_SIZE 160
51 #define PERIOD_FRAMES 80 /* 80 Frames, at 2 bytes each */
52
53 /* When you set the frame size, you have to come up with
54    the right buffer format as well. */
55 /* 5 64-byte frames = one frame */
56 #define BUFFER_FMT ((buffersize * 10) << 16) | (0x0006);
57
58 /* Don't switch between read/write modes faster than every 300 ms */
59 #define MIN_SWITCH_TIME 600
60
61 static snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
62 //static int block = O_NONBLOCK;
63 static char indevname[50] = ALSA_INDEV;
64 static char outdevname[50] = ALSA_OUTDEV;
65
66 #if 0
67 static struct timeval lasttime;
68 #endif
69
70 static int usecnt;
71 static int silencesuppression = 0;
72 static int silencethreshold = 1000;
73
74 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
75 AST_MUTEX_DEFINE_STATIC(alsalock);
76
77 static char *type = "Console";
78 static char *desc = "ALSA Console Channel Driver";
79 static char *tdesc = "ALSA Console Channel Driver";
80 static char *config = "alsa.conf";
81
82 static char context[AST_MAX_EXTENSION] = "default";
83 static char language[MAX_LANGUAGE] = "";
84 static char exten[AST_MAX_EXTENSION] = "s";
85
86 static int hookstate=0;
87
88 static short silence[FRAME_SIZE] = {0, };
89
90 struct sound {
91         int ind;
92         short *data;
93         int datalen;
94         int samplen;
95         int silencelen;
96         int repeat;
97 };
98
99 static struct sound sounds[] = {
100         { AST_CONTROL_RINGING, ringtone, sizeof(ringtone)/2, 16000, 32000, 1 },
101         { AST_CONTROL_BUSY, busy, sizeof(busy)/2, 4000, 4000, 1 },
102         { AST_CONTROL_CONGESTION, busy, sizeof(busy)/2, 2000, 2000, 1 },
103         { AST_CONTROL_RING, ring10, sizeof(ring10)/2, 16000, 32000, 1 },
104         { AST_CONTROL_ANSWER, answer, sizeof(answer)/2, 2200, 0, 0 },
105 };
106
107 /* Sound command pipe */
108 static int sndcmd[2];
109
110 static struct chan_alsa_pvt {
111         /* We only have one ALSA structure -- near sighted perhaps, but it
112            keeps this driver as simple as possible -- as it should be. */
113         struct ast_channel *owner;
114         char exten[AST_MAX_EXTENSION];
115         char context[AST_MAX_EXTENSION];
116 #if 0
117         snd_pcm_t *card;
118 #endif
119         snd_pcm_t *icard, *ocard;
120         
121 } alsa;
122
123 /* Number of buffers...  Each is FRAMESIZE/8 ms long.  For example
124    with 160 sample frames, and a buffer size of 3, we have a 60ms buffer, 
125    usually plenty. */
126
127 pthread_t sthread;
128
129 #define MAX_BUFFER_SIZE 100
130
131 /* File descriptors for sound device */
132 static int readdev = -1;
133 static int writedev = -1;
134
135 static int autoanswer = 1;
136
137 static int cursound = -1;
138 static int sampsent = 0;
139 static int silencelen=0;
140 static int offset=0;
141 static int nosound=0;
142
143 static int send_sound(void)
144 {
145         short myframe[FRAME_SIZE];
146         int total = FRAME_SIZE;
147         short *frame = NULL;
148         int amt=0;
149         int res;
150         int myoff;
151         snd_pcm_state_t state;
152
153         if (cursound > -1) {
154                 res = total;
155                 if (sampsent < sounds[cursound].samplen) {
156                         myoff=0;
157                         while(total) {
158                                 amt = total;
159                                 if (amt > (sounds[cursound].datalen - offset)) 
160                                         amt = sounds[cursound].datalen - offset;
161                                 memcpy(myframe + myoff, sounds[cursound].data + offset, amt * 2);
162                                 total -= amt;
163                                 offset += amt;
164                                 sampsent += amt;
165                                 myoff += amt;
166                                 if (offset >= sounds[cursound].datalen)
167                                         offset = 0;
168                         }
169                         /* Set it up for silence */
170                         if (sampsent >= sounds[cursound].samplen) 
171                                 silencelen = sounds[cursound].silencelen;
172                         frame = myframe;
173                 } else {
174                         if (silencelen > 0) {
175                                 frame = silence;
176                                 silencelen -= res;
177                         } else {
178                                 if (sounds[cursound].repeat) {
179                                         /* Start over */
180                                         sampsent = 0;
181                                         offset = 0;
182                                 } else {
183                                         cursound = -1;
184                                         nosound = 0;
185                                 }
186                         return 0;
187                         }
188                 }
189                 
190                 if (res == 0 || !frame) {
191                         return 0;
192                 }
193 #ifdef ALSA_MONITOR
194                 alsa_monitor_write((char *)frame, res * 2);
195 #endif          
196                 state = snd_pcm_state(alsa.ocard);
197                 if (state == SND_PCM_STATE_XRUN) {
198                         snd_pcm_prepare(alsa.ocard);
199                 }
200                 res = snd_pcm_writei(alsa.ocard, frame, res);
201                 if (res > 0)
202                         return 0;
203                 return 0;
204         }
205         return 0;
206 }
207
208 static void *sound_thread(void *unused)
209 {
210         fd_set rfds;
211         fd_set wfds;
212         int max;
213         int res;
214         for(;;) {
215                 FD_ZERO(&rfds);
216                 FD_ZERO(&wfds);
217                 max = sndcmd[0];
218                 FD_SET(sndcmd[0], &rfds);
219                 if (cursound > -1) {
220                         FD_SET(writedev, &wfds);
221                         if (writedev > max)
222                                 max = writedev;
223                 }
224 #ifdef ALSA_MONITOR
225                 if (!alsa.owner) {
226                         FD_SET(readdev, &rfds);
227                         if (readdev > max)
228                                 max = readdev;
229                 }
230 #endif
231                 res = ast_select(max + 1, &rfds, &wfds, NULL, NULL);
232                 if (res < 1) {
233                         ast_log(LOG_WARNING, "select failed: %s\n", strerror(errno));
234                         continue;
235                 }
236 #ifdef ALSA_MONITOR
237                 if (FD_ISSET(readdev, &rfds)) {
238                         /* Keep the pipe going with read audio */
239                         snd_pcm_state_t state;
240                         short buf[FRAME_SIZE];
241                         int r;
242                         
243                         state = snd_pcm_state(alsa.ocard);
244                         if (state == SND_PCM_STATE_XRUN) {
245                                 snd_pcm_prepare(alsa.ocard);
246                         }
247                         r = snd_pcm_readi(alsa.icard, buf, FRAME_SIZE);
248                         if (r == -EPIPE) {
249 #if DEBUG
250                                 ast_log(LOG_ERROR, "XRUN read\n");
251 #endif
252                                 snd_pcm_prepare(alsa.icard);
253                         } else if (r == -ESTRPIPE) {
254                                 ast_log(LOG_ERROR, "-ESTRPIPE\n");
255                                 snd_pcm_prepare(alsa.icard);
256                         } else if (r < 0) {
257                                 ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(r));
258                         } else
259                                 alsa_monitor_read((char *)buf, r * 2);
260                 }               
261 #endif          
262                 if (FD_ISSET(sndcmd[0], &rfds)) {
263                         read(sndcmd[0], &cursound, sizeof(cursound));
264                         silencelen = 0;
265                         offset = 0;
266                         sampsent = 0;
267                 }
268                 if (FD_ISSET(writedev, &wfds))
269                         if (send_sound())
270                                 ast_log(LOG_WARNING, "Failed to write sound\n");
271         }
272         /* Never reached */
273         return NULL;
274 }
275
276 static snd_pcm_t *alsa_card_init(char *dev, snd_pcm_stream_t stream)
277 {
278         int err;
279         int direction;
280         snd_pcm_t *handle = NULL;
281         snd_pcm_hw_params_t *hwparams = NULL;
282         snd_pcm_sw_params_t *swparams = NULL;
283         struct pollfd pfd;
284         snd_pcm_uframes_t period_size = PERIOD_FRAMES * 4;
285         //int period_bytes = 0;
286         snd_pcm_uframes_t buffer_size = 0;
287
288         unsigned int rate = DESIRED_RATE;
289 #if 0
290         unsigned int per_min = 1;
291 #endif
292         //unsigned int per_max = 8;
293         snd_pcm_uframes_t start_threshold, stop_threshold;
294
295         err = snd_pcm_open(&handle, dev, stream, O_NONBLOCK);
296         if (err < 0) {
297                 ast_log(LOG_ERROR, "snd_pcm_open failed: %s\n", snd_strerror(err));
298                 return NULL;
299         } else {
300                 ast_log(LOG_DEBUG, "Opening device %s in %s mode\n", dev, (stream == SND_PCM_STREAM_CAPTURE) ? "read" : "write");
301         }
302
303         snd_pcm_hw_params_alloca(&hwparams);
304         snd_pcm_hw_params_any(handle, hwparams);
305
306         err = snd_pcm_hw_params_set_access(handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
307         if (err < 0) {
308                 ast_log(LOG_ERROR, "set_access failed: %s\n", snd_strerror(err));
309         }
310
311         err = snd_pcm_hw_params_set_format(handle, hwparams, format);
312         if (err < 0) {
313                 ast_log(LOG_ERROR, "set_format failed: %s\n", snd_strerror(err));
314         }
315
316         err = snd_pcm_hw_params_set_channels(handle, hwparams, 1);
317         if (err < 0) {
318                 ast_log(LOG_ERROR, "set_channels failed: %s\n", snd_strerror(err));
319         }
320
321         direction = 0;
322         err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &rate, &direction);
323         if (rate != DESIRED_RATE) {
324                 ast_log(LOG_WARNING, "Rate not correct, requested %d, got %d\n", DESIRED_RATE, rate);
325         }
326
327         direction = 0;
328         err = snd_pcm_hw_params_set_period_size_near(handle, hwparams, &period_size, &direction);
329         if (err < 0) {
330                 ast_log(LOG_ERROR, "period_size(%ld frames) is bad: %s\n", period_size, snd_strerror(err));
331         } else {
332                 ast_log(LOG_DEBUG, "Period size is %d\n", err);
333         }
334
335         buffer_size = 4096 * 2; //period_size * 16;
336         err = snd_pcm_hw_params_set_buffer_size_near(handle, hwparams, &buffer_size);
337         if (err < 0) {
338                 ast_log(LOG_WARNING, "Problem setting buffer size of %ld: %s\n", buffer_size, snd_strerror(err));
339         } else {
340                 ast_log(LOG_DEBUG, "Buffer size is set to %d frames\n", err);
341         }
342
343 #if 0
344         direction = 0;
345         err = snd_pcm_hw_params_set_periods_min(handle, hwparams, &per_min, &direction);
346         if (err < 0) {
347                 ast_log(LOG_ERROR, "periods_min: %s\n", snd_strerror(err));
348         }
349
350         err = snd_pcm_hw_params_set_periods_max(handle, hwparams, &per_max, 0);
351         if (err < 0) {
352                 ast_log(LOG_ERROR, "periods_max: %s\n", snd_strerror(err));
353         }
354 #endif
355
356         err = snd_pcm_hw_params(handle, hwparams);
357         if (err < 0) {
358                 ast_log(LOG_ERROR, "Couldn't set the new hw params: %s\n", snd_strerror(err));
359         }
360
361         snd_pcm_sw_params_alloca(&swparams);
362         snd_pcm_sw_params_current(handle, swparams);
363
364 #if 1
365         if (stream == SND_PCM_STREAM_PLAYBACK) {
366                 start_threshold = period_size;
367         } else {
368                 start_threshold = 1;
369         }
370
371         err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
372         if (err < 0) {
373                 ast_log(LOG_ERROR, "start threshold: %s\n", snd_strerror(err));
374         }
375 #endif
376
377 #if 1
378         if (stream == SND_PCM_STREAM_PLAYBACK) {
379                 stop_threshold = buffer_size;
380         } else {
381                 stop_threshold = buffer_size;
382         }
383         err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
384         if (err < 0) {
385                 ast_log(LOG_ERROR, "stop threshold: %s\n", snd_strerror(err));
386         }
387 #endif
388 #if 0
389         err = snd_pcm_sw_params_set_xfer_align(handle, swparams, PERIOD_FRAMES);
390         if (err < 0) {
391                 ast_log(LOG_ERROR, "Unable to set xfer alignment: %s\n", snd_strerror(err));
392         }
393 #endif
394
395 #if 0
396         err = snd_pcm_sw_params_set_silence_threshold(handle, swparams, silencethreshold);
397         if (err < 0) {
398                 ast_log(LOG_ERROR, "Unable to set silence threshold: %s\n", snd_strerror(err));
399         }
400 #endif
401         err = snd_pcm_sw_params(handle, swparams);
402         if (err < 0) {
403                 ast_log(LOG_ERROR, "sw_params: %s\n", snd_strerror(err));
404         }
405
406         err = snd_pcm_poll_descriptors_count(handle);
407         if (err <= 0) {
408                 ast_log(LOG_ERROR, "Unable to get a poll descriptors count, error is %s\n", snd_strerror(err));
409         }
410
411         if (err != 1) {
412                 ast_log(LOG_DEBUG, "Can't handle more than one device\n");
413         }
414
415         snd_pcm_poll_descriptors(handle, &pfd, err);
416         ast_log(LOG_DEBUG, "Acquired fd %d from the poll descriptor\n", pfd.fd);
417
418         if (stream == SND_PCM_STREAM_CAPTURE)
419                 readdev = pfd.fd;
420         else
421                 writedev = pfd.fd;
422
423         return handle;
424 }
425
426 static int soundcard_init(void)
427 {
428         alsa.icard = alsa_card_init(indevname, SND_PCM_STREAM_CAPTURE);
429         alsa.ocard = alsa_card_init(outdevname, SND_PCM_STREAM_PLAYBACK);
430
431         if (!alsa.icard || !alsa.ocard) {
432                 ast_log(LOG_ERROR, "Problem opening alsa I/O devices\n");
433                 return -1;
434         }
435
436         return readdev;
437 }
438
439 static int alsa_digit(struct ast_channel *c, char digit)
440 {
441         ast_mutex_lock(&alsalock);
442         ast_verbose( " << Console Received digit %c >> \n", digit);
443         ast_mutex_unlock(&alsalock);
444         return 0;
445 }
446
447 static int alsa_text(struct ast_channel *c, char *text)
448 {
449         ast_mutex_lock(&alsalock);
450         ast_verbose( " << Console Received text %s >> \n", text);
451         ast_mutex_unlock(&alsalock);
452         return 0;
453 }
454
455 static void grab_owner(void)
456 {
457         while(alsa.owner && ast_mutex_trylock(&alsa.owner->lock)) {
458                 ast_mutex_unlock(&alsalock);
459                 usleep(1);
460                 ast_mutex_lock(&alsalock);
461         }
462 }
463
464 static int alsa_call(struct ast_channel *c, char *dest, int timeout)
465 {
466         int res = 3;
467         struct ast_frame f = { AST_FRAME_CONTROL };
468         ast_mutex_lock(&alsalock);
469         ast_verbose( " << Call placed to '%s' on console >> \n", dest);
470         if (autoanswer) {
471                 ast_verbose( " << Auto-answered >> \n" );
472                 grab_owner();
473                 if (alsa.owner) {
474                         f.subclass = AST_CONTROL_ANSWER;
475                         ast_queue_frame(alsa.owner, &f);
476                         ast_mutex_unlock(&alsa.owner->lock);
477                 }
478         } else {
479                 ast_verbose( " << Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
480                 grab_owner();
481                 if (alsa.owner) {
482                         f.subclass = AST_CONTROL_RINGING;
483                         ast_queue_frame(alsa.owner, &f);
484                         ast_mutex_unlock(&alsa.owner->lock);
485                 }
486                 write(sndcmd[1], &res, sizeof(res));
487         }
488         ast_mutex_unlock(&alsalock);
489         return 0;
490 }
491
492 static void answer_sound(void)
493 {
494         int res;
495         nosound = 1;
496         res = 4;
497         write(sndcmd[1], &res, sizeof(res));
498         
499 }
500
501 static int alsa_answer(struct ast_channel *c)
502 {
503         ast_mutex_lock(&alsalock);
504         ast_verbose( " << Console call has been answered >> \n");
505         answer_sound();
506         ast_setstate(c, AST_STATE_UP);
507         cursound = -1;
508         ast_mutex_unlock(&alsalock);
509         return 0;
510 }
511
512 static int alsa_hangup(struct ast_channel *c)
513 {
514         int res;
515         ast_mutex_lock(&alsalock);
516         cursound = -1;
517         c->pvt->pvt = NULL;
518         alsa.owner = NULL;
519         ast_verbose( " << Hangup on console >> \n");
520         ast_mutex_lock(&usecnt_lock);
521         usecnt--;
522         ast_mutex_unlock(&usecnt_lock);
523         if (hookstate) {
524                 res = 2;
525                 write(sndcmd[1], &res, sizeof(res));
526         }
527         ast_mutex_unlock(&alsalock);
528         return 0;
529 }
530
531 static int alsa_write(struct ast_channel *chan, struct ast_frame *f)
532 {
533         static char sizbuf[8000];
534         static int sizpos = 0;
535         int len = sizpos;
536         int pos;
537         int res = 0;
538         //size_t frames = 0;
539         snd_pcm_state_t state;
540         /* Immediately return if no sound is enabled */
541         if (nosound)
542                 return 0;
543         ast_mutex_lock(&alsalock);
544         /* Stop any currently playing sound */
545         if (cursound != -1) {
546                 snd_pcm_drop(alsa.ocard);
547                 snd_pcm_prepare(alsa.ocard);
548                 cursound = -1;
549         }
550         
551
552         /* We have to digest the frame in 160-byte portions */
553         if (f->datalen > sizeof(sizbuf) - sizpos) {
554                 ast_log(LOG_WARNING, "Frame too large\n");
555                 res = -1;
556         } else {
557                 memcpy(sizbuf + sizpos, f->data, f->datalen);
558                 len += f->datalen;
559                 pos = 0;
560 #ifdef ALSA_MONITOR
561                 alsa_monitor_write(sizbuf, len);
562 #endif
563                 state = snd_pcm_state(alsa.ocard);
564                 if (state == SND_PCM_STATE_XRUN) {
565                         snd_pcm_prepare(alsa.ocard);
566                 }
567                 res = snd_pcm_writei(alsa.ocard, sizbuf, len/2);
568                 if (res == -EPIPE) {
569 #if DEBUG
570                         ast_log(LOG_DEBUG, "XRUN write\n");
571 #endif
572                         snd_pcm_prepare(alsa.ocard);
573                         res = snd_pcm_writei(alsa.ocard, sizbuf, len/2);
574                         if (res != len/2) {
575                                 ast_log(LOG_ERROR, "Write error: %s\n", snd_strerror(res));
576                                 res = -1;
577                         } else if (res < 0) {
578                                 ast_log(LOG_ERROR, "Write error %s\n", snd_strerror(res));
579                                 res = -1;
580                         }
581                 } else {
582                         if (res == -ESTRPIPE) {
583                                 ast_log(LOG_ERROR, "You've got some big problems\n");
584                         }
585                         if (res > 0)
586                                 res = 0;
587                 }
588         }
589         ast_mutex_unlock(&alsalock);
590
591         return res;
592 }
593
594
595 static struct ast_frame *alsa_read(struct ast_channel *chan)
596 {
597         static struct ast_frame f;
598         static short __buf[FRAME_SIZE + AST_FRIENDLY_OFFSET/2];
599         short *buf;
600         static int readpos = 0;
601         static int left = FRAME_SIZE;
602         snd_pcm_state_t state;
603         int r = 0;
604         int off = 0;
605
606         ast_mutex_lock(&alsalock);
607         /* Acknowledge any pending cmd */       
608         f.frametype = AST_FRAME_NULL;
609         f.subclass = 0;
610         f.samples = 0;
611         f.datalen = 0;
612         f.data = NULL;
613         f.offset = 0;
614         f.src = type;
615         f.mallocd = 0;
616         f.delivery.tv_sec = 0;
617         f.delivery.tv_usec = 0;
618
619         state = snd_pcm_state(alsa.ocard);
620         if (state == SND_PCM_STATE_XRUN) {
621                 snd_pcm_prepare(alsa.ocard);
622         }
623
624         buf = __buf + AST_FRIENDLY_OFFSET/2;
625
626         r = snd_pcm_readi(alsa.icard, buf + readpos, left);
627         if (r == -EPIPE) {
628 #if DEBUG
629                 ast_log(LOG_ERROR, "XRUN read\n");
630 #endif
631                 snd_pcm_prepare(alsa.icard);
632         } else if (r == -ESTRPIPE) {
633                 ast_log(LOG_ERROR, "-ESTRPIPE\n");
634                 snd_pcm_prepare(alsa.icard);
635         } else if (r < 0) {
636                 ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(r));
637         } else if (r >= 0) {
638                 off -= r;
639         }
640         /* Update positions */
641         readpos += r;
642         left -= r;
643
644         if (readpos >= FRAME_SIZE) {
645                 /* A real frame */
646                 readpos = 0;
647                 left = FRAME_SIZE;
648                 if (chan->_state != AST_STATE_UP) {
649                         /* Don't transmit unless it's up */
650                         ast_mutex_unlock(&alsalock);
651                         return &f;
652                 }
653                 f.frametype = AST_FRAME_VOICE;
654                 f.subclass = AST_FORMAT_SLINEAR;
655                 f.samples = FRAME_SIZE;
656                 f.datalen = FRAME_SIZE * 2;
657                 f.data = buf;
658                 f.offset = AST_FRIENDLY_OFFSET;
659                 f.src = type;
660                 f.mallocd = 0;
661 #ifdef ALSA_MONITOR
662                 alsa_monitor_read((char *)buf, FRAME_SIZE * 2);
663 #endif          
664
665         }
666         ast_mutex_unlock(&alsalock);
667         return &f;
668 }
669
670 static int alsa_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
671 {
672         struct chan_alsa_pvt *p = newchan->pvt->pvt;
673         ast_mutex_lock(&alsalock);
674         p->owner = newchan;
675         ast_mutex_unlock(&alsalock);
676         return 0;
677 }
678
679 static int alsa_indicate(struct ast_channel *chan, int cond)
680 {
681         int res = 0;
682         ast_mutex_lock(&alsalock);
683         switch(cond) {
684         case AST_CONTROL_BUSY:
685                 res = 1;
686                 break;
687         case AST_CONTROL_CONGESTION:
688                 res = 2;
689                 break;
690         case AST_CONTROL_RINGING:
691                 res = 0;
692                 break;
693         case -1:
694                 res = -1;
695                 break;
696         default:
697                 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
698                 res = -1;
699         }
700         if (res > -1) {
701                 write(sndcmd[1], &res, sizeof(res));
702         }
703         ast_mutex_unlock(&alsalock);
704         return res;     
705 }
706
707 static struct ast_channel *alsa_new(struct chan_alsa_pvt *p, int state)
708 {
709         struct ast_channel *tmp;
710         tmp = ast_channel_alloc(1);
711         if (tmp) {
712                 snprintf(tmp->name, sizeof(tmp->name), "ALSA/%s", indevname);
713                 tmp->type = type;
714                 tmp->fds[0] = readdev;
715                 tmp->nativeformats = AST_FORMAT_SLINEAR;
716                 tmp->pvt->pvt = p;
717                 tmp->pvt->send_digit = alsa_digit;
718                 tmp->pvt->send_text = alsa_text;
719                 tmp->pvt->hangup = alsa_hangup;
720                 tmp->pvt->answer = alsa_answer;
721                 tmp->pvt->read = alsa_read;
722                 tmp->pvt->call = alsa_call;
723                 tmp->pvt->write = alsa_write;
724                 tmp->pvt->indicate = alsa_indicate;
725                 tmp->pvt->fixup = alsa_fixup;
726                 if (strlen(p->context))
727                         strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
728                 if (strlen(p->exten))
729                         strncpy(tmp->exten, p->exten, sizeof(tmp->exten)-1);
730                 if (strlen(language))
731                         strncpy(tmp->language, language, sizeof(tmp->language)-1);
732                 p->owner = tmp;
733                 ast_setstate(tmp, state);
734                 ast_mutex_lock(&usecnt_lock);
735                 usecnt++;
736                 ast_mutex_unlock(&usecnt_lock);
737                 ast_update_use_count();
738                 if (state != AST_STATE_DOWN) {
739                         if (ast_pbx_start(tmp)) {
740                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
741                                 ast_hangup(tmp);
742                                 tmp = NULL;
743                         }
744                 }
745         }
746         return tmp;
747 }
748
749 static struct ast_channel *alsa_request(char *type, int format, void *data)
750 {
751         int oldformat = format;
752         struct ast_channel *tmp=NULL;
753         format &= AST_FORMAT_SLINEAR;
754         if (!format) {
755                 ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
756                 return NULL;
757         }
758         ast_mutex_lock(&alsalock);
759         if (alsa.owner) {
760                 ast_log(LOG_NOTICE, "Already have a call on the ALSA channel\n");
761         } else {
762                 tmp= alsa_new(&alsa, AST_STATE_DOWN);
763                 if (!tmp) {
764                         ast_log(LOG_WARNING, "Unable to create new ALSA channel\n");
765                 }
766         }
767         ast_mutex_unlock(&alsalock);
768         return tmp;
769 }
770
771 static int console_autoanswer(int fd, int argc, char *argv[])
772 {
773         int res = RESULT_SUCCESS;;
774         if ((argc != 1) && (argc != 2))
775                 return RESULT_SHOWUSAGE;
776         ast_mutex_lock(&alsalock);
777         if (argc == 1) {
778                 ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
779         } else {
780                 if (!strcasecmp(argv[1], "on"))
781                         autoanswer = -1;
782                 else if (!strcasecmp(argv[1], "off"))
783                         autoanswer = 0;
784                 else
785                         res = RESULT_SHOWUSAGE;
786         }
787         ast_mutex_unlock(&alsalock);
788         return res;
789 }
790
791 static char *autoanswer_complete(char *line, char *word, int pos, int state)
792 {
793 #ifndef MIN
794 #define MIN(a,b) ((a) < (b) ? (a) : (b))
795 #endif
796         switch(state) {
797         case 0:
798                 if (strlen(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
799                         return strdup("on");
800         case 1:
801                 if (strlen(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
802                         return strdup("off");
803         default:
804                 return NULL;
805         }
806         return NULL;
807 }
808
809 static char autoanswer_usage[] =
810 "Usage: autoanswer [on|off]\n"
811 "       Enables or disables autoanswer feature.  If used without\n"
812 "       argument, displays the current on/off status of autoanswer.\n"
813 "       The default value of autoanswer is in 'alsa.conf'.\n";
814
815 static int console_answer(int fd, int argc, char *argv[])
816 {
817         int res = RESULT_SUCCESS;
818         if (argc != 1)
819                 return RESULT_SHOWUSAGE;
820         ast_mutex_lock(&alsalock);
821         if (!alsa.owner) {
822                 ast_cli(fd, "No one is calling us\n");
823                 res = RESULT_FAILURE;
824         } else {
825                 hookstate = 1;
826                 cursound = -1;
827                 grab_owner();
828                 if (alsa.owner) {
829                         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
830                         ast_queue_frame(alsa.owner, &f);
831                         ast_mutex_unlock(&alsa.owner->lock);
832                 }
833                 answer_sound();
834         }
835         ast_mutex_unlock(&alsalock);
836         return RESULT_SUCCESS;
837 }
838
839 static char sendtext_usage[] =
840 "Usage: send text <message>\n"
841 "       Sends a text message for display on the remote terminal.\n";
842
843 static int console_sendtext(int fd, int argc, char *argv[])
844 {
845         int tmparg = 2;
846         int res = RESULT_SUCCESS;
847         if (argc < 2)
848                 return RESULT_SHOWUSAGE;
849         ast_mutex_lock(&alsalock);
850         if (!alsa.owner) {
851                 ast_cli(fd, "No one is calling us\n");
852                 res = RESULT_FAILURE;
853         } else {
854                 struct ast_frame f = { AST_FRAME_TEXT, 0 };
855                 char text2send[256];
856                 strcpy(text2send, "");
857                 while(tmparg <= argc) {
858                         strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send));
859                         strncat(text2send, " ", sizeof(text2send) - strlen(text2send));
860                 }
861                 f.data = text2send;
862                 f.datalen = strlen(text2send) + 1;
863                 grab_owner();
864                 if (alsa.owner) {
865                         ast_queue_frame(alsa.owner, &f);
866                         f.frametype = AST_FRAME_CONTROL;
867                         f.subclass = AST_CONTROL_ANSWER;
868                         f.data = NULL;
869                         f.datalen = 0;
870                         ast_queue_frame(alsa.owner, &f);
871                         ast_mutex_unlock(&alsa.owner->lock);
872                 }
873         }
874         ast_mutex_unlock(&alsalock);
875         return res;
876 }
877
878 static char answer_usage[] =
879 "Usage: answer\n"
880 "       Answers an incoming call on the console (ALSA) channel.\n";
881
882 static int console_hangup(int fd, int argc, char *argv[])
883 {
884         int res = RESULT_SUCCESS;
885         if (argc != 1)
886                 return RESULT_SHOWUSAGE;
887         cursound = -1;
888         ast_mutex_lock(&alsalock);
889         if (!alsa.owner && !hookstate) {
890                 ast_cli(fd, "No call to hangup up\n");
891                 res = RESULT_FAILURE;
892         } else {
893                 hookstate = 0;
894                 grab_owner();
895                 if (alsa.owner) {
896                         ast_queue_hangup(alsa.owner);
897                         ast_mutex_unlock(&alsa.owner->lock);
898                 }
899         }
900         ast_mutex_unlock(&alsalock);
901         return res;
902 }
903
904 static char hangup_usage[] =
905 "Usage: hangup\n"
906 "       Hangs up any call currently placed on the console.\n";
907
908
909 static int console_dial(int fd, int argc, char *argv[])
910 {
911         char tmp[256], *tmp2;
912         char *mye, *myc;
913         char *d;
914         int res = RESULT_SUCCESS;
915         if ((argc != 1) && (argc != 2))
916                 return RESULT_SHOWUSAGE;
917         ast_mutex_lock(&alsalock);
918         if (alsa.owner) {
919                 if (argc == 2) {
920                         d = argv[1];
921                         grab_owner();
922                         if (alsa.owner) {
923                                 struct ast_frame f = { AST_FRAME_DTMF };
924                                 while(*d) {
925                                         f.subclass = *d;
926                                         ast_queue_frame(alsa.owner, &f);
927                                         d++;
928                                 }
929                                 ast_mutex_unlock(&alsa.owner->lock);
930                         }
931                 } else {
932                         ast_cli(fd, "You're already in a call.  You can use this only to dial digits until you hangup\n");
933                         res = RESULT_FAILURE;
934                 }
935         } else {
936                 mye = exten;
937                 myc = context;
938                 if (argc == 2) {
939                         char *stringp=NULL;
940                         strncpy(tmp, argv[1], sizeof(tmp)-1);
941                         stringp=tmp;
942                         strsep(&stringp, "@");
943                         tmp2 = strsep(&stringp, "@");
944                         if (strlen(tmp))
945                                 mye = tmp;
946                         if (tmp2 && strlen(tmp2))
947                                 myc = tmp2;
948                 }
949                 if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
950                         strncpy(alsa.exten, mye, sizeof(alsa.exten)-1);
951                         strncpy(alsa.context, myc, sizeof(alsa.context)-1);
952                         hookstate = 1;
953                         alsa_new(&alsa, AST_STATE_RINGING);
954                 } else
955                         ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
956         }
957         ast_mutex_unlock(&alsalock);
958         return res;
959 }
960
961 static char dial_usage[] =
962 "Usage: dial [extension[@context]]\n"
963 "       Dials a given extensison (";
964
965
966 static struct ast_cli_entry myclis[] = {
967         { { "answer", NULL }, console_answer, "Answer an incoming console call", answer_usage },
968         { { "hangup", NULL }, console_hangup, "Hangup a call on the console", hangup_usage },
969         { { "dial", NULL }, console_dial, "Dial an extension on the console", dial_usage },
970         { { "send", "text", NULL }, console_sendtext, "Send text to the remote device", sendtext_usage },
971         { { "autoanswer", NULL }, console_autoanswer, "Sets/displays autoanswer", autoanswer_usage, autoanswer_complete }
972 };
973
974 int load_module()
975 {
976         int res;
977         int x;
978         struct ast_config *cfg;
979         struct ast_variable *v;
980         res = pipe(sndcmd);
981         if (res) {
982                 ast_log(LOG_ERROR, "Unable to create pipe\n");
983                 return -1;
984         }
985         res = soundcard_init();
986         if (res < 0) {
987                 if (option_verbose > 1) {
988                         ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
989                         ast_verbose(VERBOSE_PREFIX_2 "Turn off ALSA support by adding 'noload=chan_alsa.so' in /etc/asterisk/modules.conf\n");
990                 }
991                 return 0;
992         }
993 #if 0
994         if (!full_duplex)
995                 ast_log(LOG_WARNING, "XXX I don't work right with non-full duplex sound cards XXX\n");
996 #endif
997         res = ast_channel_register(type, tdesc, AST_FORMAT_SLINEAR, alsa_request);
998         if (res < 0) {
999                 ast_log(LOG_ERROR, "Unable to register channel class '%s'\n", type);
1000                 return -1;
1001         }
1002         for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
1003                 ast_cli_register(myclis + x);
1004         if ((cfg = ast_load(config))) {
1005                 v = ast_variable_browse(cfg, "general");
1006                 while(v) {
1007                         if (!strcasecmp(v->name, "autoanswer"))
1008                                 autoanswer = ast_true(v->value);
1009                         else if (!strcasecmp(v->name, "silencesuppression"))
1010                                 silencesuppression = ast_true(v->value);
1011                         else if (!strcasecmp(v->name, "silencethreshold"))
1012                                 silencethreshold = atoi(v->value);
1013                         else if (!strcasecmp(v->name, "context"))
1014                                 strncpy(context, v->value, sizeof(context)-1);
1015                         else if (!strcasecmp(v->name, "language"))
1016                                 strncpy(language, v->value, sizeof(language)-1);
1017                         else if (!strcasecmp(v->name, "extension"))
1018                                 strncpy(exten, v->value, sizeof(exten)-1);
1019                         else if (!strcasecmp(v->name, "input_device"))
1020                                 strncpy(indevname, v->value, sizeof(indevname)-1);
1021                         else if (!strcasecmp(v->name, "output_device"))
1022                                 strncpy(outdevname, v->value, sizeof(outdevname)-1);
1023                         v=v->next;
1024                 }
1025                 ast_destroy(cfg);
1026         }
1027         pthread_create(&sthread, NULL, sound_thread, NULL);
1028 #ifdef ALSA_MONITOR
1029         if (alsa_monitor_start()) {
1030                 ast_log(LOG_ERROR, "Problem starting Monitoring\n");
1031         }
1032 #endif   
1033         return 0;
1034 }
1035
1036
1037
1038 int unload_module()
1039 {
1040         int x;
1041         for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
1042                 ast_cli_unregister(myclis + x);
1043         close(readdev);
1044         close(writedev);
1045         if (sndcmd[0] > 0) {
1046                 close(sndcmd[0]);
1047                 close(sndcmd[1]);
1048         }
1049         if (alsa.owner)
1050                 ast_softhangup(alsa.owner, AST_SOFTHANGUP_APPUNLOAD);
1051         if (alsa.owner)
1052                 return -1;
1053         return 0;
1054 }
1055
1056 char *description()
1057 {
1058         return desc;
1059 }
1060
1061 int usecount()
1062 {
1063         int res;
1064         ast_mutex_lock(&usecnt_lock);
1065         res = usecnt;
1066         ast_mutex_unlock(&usecnt_lock);
1067         return res;
1068 }
1069
1070 char *key()
1071 {
1072         return ASTERISK_GPL_KEY;
1073 }