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