b8ae8b94c064b1422adae9c0e4030feef86d09f7
[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                         return &f;
651                 }
652                 f.frametype = AST_FRAME_VOICE;
653                 f.subclass = AST_FORMAT_SLINEAR;
654                 f.samples = FRAME_SIZE;
655                 f.datalen = FRAME_SIZE * 2;
656                 f.data = buf;
657                 f.offset = AST_FRIENDLY_OFFSET;
658                 f.src = type;
659                 f.mallocd = 0;
660 #ifdef ALSA_MONITOR
661                 alsa_monitor_read((char *)buf, FRAME_SIZE * 2);
662 #endif          
663
664         }
665         ast_mutex_unlock(&alsalock);
666         return &f;
667 }
668
669 static int alsa_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
670 {
671         struct chan_alsa_pvt *p = newchan->pvt->pvt;
672         ast_mutex_lock(&alsalock);
673         p->owner = newchan;
674         ast_mutex_unlock(&alsalock);
675         return 0;
676 }
677
678 static int alsa_indicate(struct ast_channel *chan, int cond)
679 {
680         int res = 0;
681         ast_mutex_lock(&alsalock);
682         switch(cond) {
683         case AST_CONTROL_BUSY:
684                 res = 1;
685                 break;
686         case AST_CONTROL_CONGESTION:
687                 res = 2;
688                 break;
689         case AST_CONTROL_RINGING:
690                 res = 0;
691                 break;
692         case -1:
693                 res = -1;
694                 break;
695         default:
696                 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
697                 res = -1;
698         }
699         if (res > -1) {
700                 write(sndcmd[1], &res, sizeof(res));
701         }
702         ast_mutex_unlock(&alsalock);
703         return res;     
704 }
705
706 static struct ast_channel *alsa_new(struct chan_alsa_pvt *p, int state)
707 {
708         struct ast_channel *tmp;
709         tmp = ast_channel_alloc(1);
710         if (tmp) {
711                 snprintf(tmp->name, sizeof(tmp->name), "ALSA/%s", indevname);
712                 tmp->type = type;
713                 tmp->fds[0] = readdev;
714                 tmp->nativeformats = AST_FORMAT_SLINEAR;
715                 tmp->pvt->pvt = p;
716                 tmp->pvt->send_digit = alsa_digit;
717                 tmp->pvt->send_text = alsa_text;
718                 tmp->pvt->hangup = alsa_hangup;
719                 tmp->pvt->answer = alsa_answer;
720                 tmp->pvt->read = alsa_read;
721                 tmp->pvt->call = alsa_call;
722                 tmp->pvt->write = alsa_write;
723                 tmp->pvt->indicate = alsa_indicate;
724                 tmp->pvt->fixup = alsa_fixup;
725                 if (strlen(p->context))
726                         strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
727                 if (strlen(p->exten))
728                         strncpy(tmp->exten, p->exten, sizeof(tmp->exten)-1);
729                 if (strlen(language))
730                         strncpy(tmp->language, language, sizeof(tmp->language)-1);
731                 p->owner = tmp;
732                 ast_setstate(tmp, state);
733                 ast_mutex_lock(&usecnt_lock);
734                 usecnt++;
735                 ast_mutex_unlock(&usecnt_lock);
736                 ast_update_use_count();
737                 if (state != AST_STATE_DOWN) {
738                         if (ast_pbx_start(tmp)) {
739                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
740                                 ast_hangup(tmp);
741                                 tmp = NULL;
742                         }
743                 }
744         }
745         return tmp;
746 }
747
748 static struct ast_channel *alsa_request(char *type, int format, void *data)
749 {
750         int oldformat = format;
751         struct ast_channel *tmp=NULL;
752         format &= AST_FORMAT_SLINEAR;
753         if (!format) {
754                 ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
755                 return NULL;
756         }
757         ast_mutex_lock(&alsalock);
758         if (alsa.owner) {
759                 ast_log(LOG_NOTICE, "Already have a call on the ALSA channel\n");
760         } else {
761                 tmp= alsa_new(&alsa, AST_STATE_DOWN);
762                 if (!tmp) {
763                         ast_log(LOG_WARNING, "Unable to create new ALSA channel\n");
764                 }
765         }
766         ast_mutex_unlock(&alsalock);
767         return tmp;
768 }
769
770 static int console_autoanswer(int fd, int argc, char *argv[])
771 {
772         int res = RESULT_SUCCESS;;
773         if ((argc != 1) && (argc != 2))
774                 return RESULT_SHOWUSAGE;
775         ast_mutex_lock(&alsalock);
776         if (argc == 1) {
777                 ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
778         } else {
779                 if (!strcasecmp(argv[1], "on"))
780                         autoanswer = -1;
781                 else if (!strcasecmp(argv[1], "off"))
782                         autoanswer = 0;
783                 else
784                         res = RESULT_SHOWUSAGE;
785         }
786         ast_mutex_unlock(&alsalock);
787         return res;
788 }
789
790 static char *autoanswer_complete(char *line, char *word, int pos, int state)
791 {
792 #ifndef MIN
793 #define MIN(a,b) ((a) < (b) ? (a) : (b))
794 #endif
795         switch(state) {
796         case 0:
797                 if (strlen(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
798                         return strdup("on");
799         case 1:
800                 if (strlen(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
801                         return strdup("off");
802         default:
803                 return NULL;
804         }
805         return NULL;
806 }
807
808 static char autoanswer_usage[] =
809 "Usage: autoanswer [on|off]\n"
810 "       Enables or disables autoanswer feature.  If used without\n"
811 "       argument, displays the current on/off status of autoanswer.\n"
812 "       The default value of autoanswer is in 'alsa.conf'.\n";
813
814 static int console_answer(int fd, int argc, char *argv[])
815 {
816         int res = RESULT_SUCCESS;
817         if (argc != 1)
818                 return RESULT_SHOWUSAGE;
819         ast_mutex_lock(&alsalock);
820         if (!alsa.owner) {
821                 ast_cli(fd, "No one is calling us\n");
822                 res = RESULT_FAILURE;
823         } else {
824                 hookstate = 1;
825                 cursound = -1;
826                 grab_owner();
827                 if (alsa.owner) {
828                         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
829                         ast_queue_frame(alsa.owner, &f);
830                         ast_mutex_unlock(&alsa.owner->lock);
831                 }
832                 answer_sound();
833         }
834         ast_mutex_unlock(&alsalock);
835         return RESULT_SUCCESS;
836 }
837
838 static char sendtext_usage[] =
839 "Usage: send text <message>\n"
840 "       Sends a text message for display on the remote terminal.\n";
841
842 static int console_sendtext(int fd, int argc, char *argv[])
843 {
844         int tmparg = 2;
845         int res = RESULT_SUCCESS;
846         if (argc < 2)
847                 return RESULT_SHOWUSAGE;
848         ast_mutex_lock(&alsalock);
849         if (!alsa.owner) {
850                 ast_cli(fd, "No one is calling us\n");
851                 res = RESULT_FAILURE;
852         } else {
853                 struct ast_frame f = { AST_FRAME_TEXT, 0 };
854                 char text2send[256];
855                 strcpy(text2send, "");
856                 while(tmparg <= argc) {
857                         strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send));
858                         strncat(text2send, " ", sizeof(text2send) - strlen(text2send));
859                 }
860                 f.data = text2send;
861                 f.datalen = strlen(text2send) + 1;
862                 grab_owner();
863                 if (alsa.owner) {
864                         ast_queue_frame(alsa.owner, &f);
865                         f.frametype = AST_FRAME_CONTROL;
866                         f.subclass = AST_CONTROL_ANSWER;
867                         f.data = NULL;
868                         f.datalen = 0;
869                         ast_queue_frame(alsa.owner, &f);
870                         ast_mutex_unlock(&alsa.owner->lock);
871                 }
872         }
873         ast_mutex_unlock(&alsalock);
874         return res;
875 }
876
877 static char answer_usage[] =
878 "Usage: answer\n"
879 "       Answers an incoming call on the console (ALSA) channel.\n";
880
881 static int console_hangup(int fd, int argc, char *argv[])
882 {
883         int res = RESULT_SUCCESS;
884         if (argc != 1)
885                 return RESULT_SHOWUSAGE;
886         cursound = -1;
887         ast_mutex_lock(&alsalock);
888         if (!alsa.owner && !hookstate) {
889                 ast_cli(fd, "No call to hangup up\n");
890                 res = RESULT_FAILURE;
891         } else {
892                 hookstate = 0;
893                 grab_owner();
894                 if (alsa.owner) {
895                         ast_queue_hangup(alsa.owner);
896                         ast_mutex_unlock(&alsa.owner->lock);
897                 }
898         }
899         ast_mutex_unlock(&alsalock);
900         return res;
901 }
902
903 static char hangup_usage[] =
904 "Usage: hangup\n"
905 "       Hangs up any call currently placed on the console.\n";
906
907
908 static int console_dial(int fd, int argc, char *argv[])
909 {
910         char tmp[256], *tmp2;
911         char *mye, *myc;
912         char *d;
913         int res = RESULT_SUCCESS;
914         if ((argc != 1) && (argc != 2))
915                 return RESULT_SHOWUSAGE;
916         ast_mutex_lock(&alsalock);
917         if (alsa.owner) {
918                 if (argc == 2) {
919                         d = argv[1];
920                         grab_owner();
921                         if (alsa.owner) {
922                                 struct ast_frame f = { AST_FRAME_DTMF };
923                                 while(*d) {
924                                         f.subclass = *d;
925                                         ast_queue_frame(alsa.owner, &f);
926                                         d++;
927                                 }
928                                 ast_mutex_unlock(&alsa.owner->lock);
929                         }
930                 } else {
931                         ast_cli(fd, "You're already in a call.  You can use this only to dial digits until you hangup\n");
932                         res = RESULT_FAILURE;
933                 }
934         } else {
935                 mye = exten;
936                 myc = context;
937                 if (argc == 2) {
938                         char *stringp=NULL;
939                         strncpy(tmp, argv[1], sizeof(tmp)-1);
940                         stringp=tmp;
941                         strsep(&stringp, "@");
942                         tmp2 = strsep(&stringp, "@");
943                         if (strlen(tmp))
944                                 mye = tmp;
945                         if (tmp2 && strlen(tmp2))
946                                 myc = tmp2;
947                 }
948                 if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
949                         strncpy(alsa.exten, mye, sizeof(alsa.exten)-1);
950                         strncpy(alsa.context, myc, sizeof(alsa.context)-1);
951                         hookstate = 1;
952                         alsa_new(&alsa, AST_STATE_RINGING);
953                 } else
954                         ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
955         }
956         ast_mutex_unlock(&alsalock);
957         return res;
958 }
959
960 static char dial_usage[] =
961 "Usage: dial [extension[@context]]\n"
962 "       Dials a given extensison (";
963
964
965 static struct ast_cli_entry myclis[] = {
966         { { "answer", NULL }, console_answer, "Answer an incoming console call", answer_usage },
967         { { "hangup", NULL }, console_hangup, "Hangup a call on the console", hangup_usage },
968         { { "dial", NULL }, console_dial, "Dial an extension on the console", dial_usage },
969         { { "send", "text", NULL }, console_sendtext, "Send text to the remote device", sendtext_usage },
970         { { "autoanswer", NULL }, console_autoanswer, "Sets/displays autoanswer", autoanswer_usage, autoanswer_complete }
971 };
972
973 int load_module()
974 {
975         int res;
976         int x;
977         struct ast_config *cfg;
978         struct ast_variable *v;
979         res = pipe(sndcmd);
980         if (res) {
981                 ast_log(LOG_ERROR, "Unable to create pipe\n");
982                 return -1;
983         }
984         res = soundcard_init();
985         if (res < 0) {
986                 if (option_verbose > 1) {
987                         ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
988                         ast_verbose(VERBOSE_PREFIX_2 "Turn off ALSA support by adding 'noload=chan_alsa.so' in /etc/asterisk/modules.conf\n");
989                 }
990                 return 0;
991         }
992 #if 0
993         if (!full_duplex)
994                 ast_log(LOG_WARNING, "XXX I don't work right with non-full duplex sound cards XXX\n");
995 #endif
996         res = ast_channel_register(type, tdesc, AST_FORMAT_SLINEAR, alsa_request);
997         if (res < 0) {
998                 ast_log(LOG_ERROR, "Unable to register channel class '%s'\n", type);
999                 return -1;
1000         }
1001         for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
1002                 ast_cli_register(myclis + x);
1003         if ((cfg = ast_load(config))) {
1004                 v = ast_variable_browse(cfg, "general");
1005                 while(v) {
1006                         if (!strcasecmp(v->name, "autoanswer"))
1007                                 autoanswer = ast_true(v->value);
1008                         else if (!strcasecmp(v->name, "silencesuppression"))
1009                                 silencesuppression = ast_true(v->value);
1010                         else if (!strcasecmp(v->name, "silencethreshold"))
1011                                 silencethreshold = atoi(v->value);
1012                         else if (!strcasecmp(v->name, "context"))
1013                                 strncpy(context, v->value, sizeof(context)-1);
1014                         else if (!strcasecmp(v->name, "language"))
1015                                 strncpy(language, v->value, sizeof(language)-1);
1016                         else if (!strcasecmp(v->name, "extension"))
1017                                 strncpy(exten, v->value, sizeof(exten)-1);
1018                         else if (!strcasecmp(v->name, "input_device"))
1019                                 strncpy(indevname, v->value, sizeof(indevname)-1);
1020                         else if (!strcasecmp(v->name, "output_device"))
1021                                 strncpy(outdevname, v->value, sizeof(outdevname)-1);
1022                         v=v->next;
1023                 }
1024                 ast_destroy(cfg);
1025         }
1026         pthread_create(&sthread, NULL, sound_thread, NULL);
1027 #ifdef ALSA_MONITOR
1028         if (alsa_monitor_start()) {
1029                 ast_log(LOG_ERROR, "Problem starting Monitoring\n");
1030         }
1031 #endif   
1032         return 0;
1033 }
1034
1035
1036
1037 int unload_module()
1038 {
1039         int x;
1040         for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
1041                 ast_cli_unregister(myclis + x);
1042         close(readdev);
1043         close(writedev);
1044         if (sndcmd[0] > 0) {
1045                 close(sndcmd[0]);
1046                 close(sndcmd[1]);
1047         }
1048         if (alsa.owner)
1049                 ast_softhangup(alsa.owner, AST_SOFTHANGUP_APPUNLOAD);
1050         if (alsa.owner)
1051                 return -1;
1052         return 0;
1053 }
1054
1055 char *description()
1056 {
1057         return desc;
1058 }
1059
1060 int usecount()
1061 {
1062         int res;
1063         ast_mutex_lock(&usecnt_lock);
1064         res = usecnt;
1065         ast_mutex_unlock(&usecnt_lock);
1066         return res;
1067 }
1068
1069 char *key()
1070 {
1071         return ASTERISK_GPL_KEY;
1072 }