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