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