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