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