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