Add SRV Lookup support on outbound calls to chan_iax2. It's listed in the RFC so...
[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 "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 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                 if (option_debug)
369                         ast_log(LOG_DEBUG, "Opening device %s in %s mode\n", dev, (stream == SND_PCM_STREAM_CAPTURE) ? "read" : "write");
370         }
371
372         snd_pcm_hw_params_alloca(&hwparams);
373         snd_pcm_hw_params_any(handle, hwparams);
374
375         err = snd_pcm_hw_params_set_access(handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
376         if (err < 0)
377                 ast_log(LOG_ERROR, "set_access failed: %s\n", snd_strerror(err));
378
379         err = snd_pcm_hw_params_set_format(handle, hwparams, format);
380         if (err < 0)
381                 ast_log(LOG_ERROR, "set_format failed: %s\n", snd_strerror(err));
382
383         err = snd_pcm_hw_params_set_channels(handle, hwparams, 1);
384         if (err < 0)
385                 ast_log(LOG_ERROR, "set_channels failed: %s\n", snd_strerror(err));
386
387         direction = 0;
388         err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &rate, &direction);
389         if (rate != DESIRED_RATE)
390                 ast_log(LOG_WARNING, "Rate not correct, requested %d, got %d\n", DESIRED_RATE, rate);
391
392         direction = 0;
393         err = snd_pcm_hw_params_set_period_size_near(handle, hwparams, &period_size, &direction);
394         if (err < 0)
395                 ast_log(LOG_ERROR, "period_size(%ld frames) is bad: %s\n", period_size, snd_strerror(err));
396         else {
397                 if (option_debug)
398                         ast_log(LOG_DEBUG, "Period size is %d\n", err);
399         }
400
401         buffer_size = 4096 * 2;         /* period_size * 16; */
402         err = snd_pcm_hw_params_set_buffer_size_near(handle, hwparams, &buffer_size);
403         if (err < 0)
404                 ast_log(LOG_WARNING, "Problem setting buffer size of %ld: %s\n", buffer_size, snd_strerror(err));
405         else {
406                 if (option_debug)
407                         ast_log(LOG_DEBUG, "Buffer size is set to %d frames\n", err);
408         }
409
410 #if 0
411         direction = 0;
412         err = snd_pcm_hw_params_set_periods_min(handle, hwparams, &per_min, &direction);
413         if (err < 0)
414                 ast_log(LOG_ERROR, "periods_min: %s\n", snd_strerror(err));
415
416         err = snd_pcm_hw_params_set_periods_max(handle, hwparams, &per_max, 0);
417         if (err < 0)
418                 ast_log(LOG_ERROR, "periods_max: %s\n", snd_strerror(err));
419 #endif
420
421         err = snd_pcm_hw_params(handle, hwparams);
422         if (err < 0)
423                 ast_log(LOG_ERROR, "Couldn't set the new hw params: %s\n", snd_strerror(err));
424
425         snd_pcm_sw_params_alloca(&swparams);
426         snd_pcm_sw_params_current(handle, swparams);
427
428 #if 1
429         if (stream == SND_PCM_STREAM_PLAYBACK)
430                 start_threshold = period_size;
431         else
432                 start_threshold = 1;
433
434         err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
435         if (err < 0)
436                 ast_log(LOG_ERROR, "start threshold: %s\n", snd_strerror(err));
437 #endif
438
439 #if 1
440         if (stream == SND_PCM_STREAM_PLAYBACK)
441                 stop_threshold = buffer_size;
442         else
443                 stop_threshold = buffer_size;
444
445         err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
446         if (err < 0)
447                 ast_log(LOG_ERROR, "stop threshold: %s\n", snd_strerror(err));
448 #endif
449 #if 0
450         err = snd_pcm_sw_params_set_xfer_align(handle, swparams, PERIOD_FRAMES);
451         if (err < 0)
452                 ast_log(LOG_ERROR, "Unable to set xfer alignment: %s\n", snd_strerror(err));
453 #endif
454
455 #if 0
456         err = snd_pcm_sw_params_set_silence_threshold(handle, swparams, silencethreshold);
457         if (err < 0)
458                 ast_log(LOG_ERROR, "Unable to set silence threshold: %s\n", snd_strerror(err));
459 #endif
460         err = snd_pcm_sw_params(handle, swparams);
461         if (err < 0)
462                 ast_log(LOG_ERROR, "sw_params: %s\n", snd_strerror(err));
463
464         err = snd_pcm_poll_descriptors_count(handle);
465         if (err <= 0)
466                 ast_log(LOG_ERROR, "Unable to get a poll descriptors count, error is %s\n", snd_strerror(err));
467         if (err != 1) {
468                 if (option_debug)
469                         ast_log(LOG_DEBUG, "Can't handle more than one device\n");
470         }
471
472         snd_pcm_poll_descriptors(handle, &pfd, err);
473         if (option_debug)
474                 ast_log(LOG_DEBUG, "Acquired fd %d from the poll descriptor\n", pfd.fd);
475
476         if (stream == SND_PCM_STREAM_CAPTURE)
477                 readdev = pfd.fd;
478         else
479                 writedev = pfd.fd;
480
481         return handle;
482 }
483
484 static int soundcard_init(void)
485 {
486         alsa.icard = alsa_card_init(indevname, SND_PCM_STREAM_CAPTURE);
487         alsa.ocard = alsa_card_init(outdevname, SND_PCM_STREAM_PLAYBACK);
488
489         if (!alsa.icard || !alsa.ocard) {
490                 ast_log(LOG_ERROR, "Problem opening alsa I/O devices\n");
491                 return -1;
492         }
493
494         return readdev;
495 }
496
497 static int alsa_digit(struct ast_channel *c, char digit, unsigned int duration)
498 {
499         ast_mutex_lock(&alsalock);
500         ast_verbose(" << Console Received digit %c of duration %u ms >> \n", 
501                 digit, duration);
502         ast_mutex_unlock(&alsalock);
503         return 0;
504 }
505
506 static int alsa_text(struct ast_channel *c, const char *text)
507 {
508         ast_mutex_lock(&alsalock);
509         ast_verbose(" << Console Received text %s >> \n", text);
510         ast_mutex_unlock(&alsalock);
511         return 0;
512 }
513
514 static void grab_owner(void)
515 {
516         while (alsa.owner && ast_mutex_trylock(&alsa.owner->lock)) {
517                 ast_mutex_unlock(&alsalock);
518                 usleep(1);
519                 ast_mutex_lock(&alsalock);
520         }
521 }
522
523 static int alsa_call(struct ast_channel *c, char *dest, int timeout)
524 {
525         int res = 3;
526         struct ast_frame f = { AST_FRAME_CONTROL };
527         ast_mutex_lock(&alsalock);
528         ast_verbose(" << Call placed to '%s' on console >> \n", dest);
529         if (autoanswer) {
530                 ast_verbose(" << Auto-answered >> \n");
531                 grab_owner();
532                 if (alsa.owner) {
533                         f.subclass = AST_CONTROL_ANSWER;
534                         ast_queue_frame(alsa.owner, &f);
535                         ast_mutex_unlock(&alsa.owner->lock);
536                 }
537         } else {
538                 ast_verbose(" << Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
539                 grab_owner();
540                 if (alsa.owner) {
541                         f.subclass = AST_CONTROL_RINGING;
542                         ast_queue_frame(alsa.owner, &f);
543                         ast_mutex_unlock(&alsa.owner->lock);
544                 }
545                 write(sndcmd[1], &res, sizeof(res));
546         }
547         snd_pcm_prepare(alsa.icard);
548         snd_pcm_start(alsa.icard);
549         ast_mutex_unlock(&alsalock);
550         return 0;
551 }
552
553 static void answer_sound(void)
554 {
555         int res;
556         nosound = 1;
557         res = 4;
558         write(sndcmd[1], &res, sizeof(res));
559
560 }
561
562 static int alsa_answer(struct ast_channel *c)
563 {
564         ast_mutex_lock(&alsalock);
565         ast_verbose(" << Console call has been answered >> \n");
566         answer_sound();
567         ast_setstate(c, AST_STATE_UP);
568         cursound = -1;
569         snd_pcm_prepare(alsa.icard);
570         snd_pcm_start(alsa.icard);
571         ast_mutex_unlock(&alsalock);
572         return 0;
573 }
574
575 static int alsa_hangup(struct ast_channel *c)
576 {
577         int res;
578         ast_mutex_lock(&alsalock);
579         cursound = -1;
580         c->tech_pvt = NULL;
581         alsa.owner = NULL;
582         ast_verbose(" << Hangup on console >> \n");
583         if (hookstate) {
584                 hookstate = 0;
585                 if (!autoanswer) {
586                         /* Congestion noise */
587                         res = 2;
588                         write(sndcmd[1], &res, sizeof(res));
589                 }
590         }
591         snd_pcm_drop(alsa.icard);
592         ast_mutex_unlock(&alsalock);
593         return 0;
594 }
595
596 static int alsa_write(struct ast_channel *chan, struct ast_frame *f)
597 {
598         static char sizbuf[8000];
599         static int sizpos = 0;
600         int len = sizpos;
601         int pos;
602         int res = 0;
603         /* size_t frames = 0; */
604         snd_pcm_state_t state;
605
606         /* Immediately return if no sound is enabled */
607         if (nosound)
608                 return 0;
609
610         ast_mutex_lock(&alsalock);
611         /* Stop any currently playing sound */
612         if (cursound != -1) {
613                 snd_pcm_drop(alsa.ocard);
614                 snd_pcm_prepare(alsa.ocard);
615                 cursound = -1;
616         }
617
618
619         /* We have to digest the frame in 160-byte portions */
620         if (f->datalen > sizeof(sizbuf) - sizpos) {
621                 ast_log(LOG_WARNING, "Frame too large\n");
622                 res = -1;
623         } else {
624                 memcpy(sizbuf + sizpos, f->data, f->datalen);
625                 len += f->datalen;
626                 pos = 0;
627 #ifdef ALSA_MONITOR
628                 alsa_monitor_write(sizbuf, len);
629 #endif
630                 state = snd_pcm_state(alsa.ocard);
631                 if (state == SND_PCM_STATE_XRUN)
632                         snd_pcm_prepare(alsa.ocard);
633                 res = snd_pcm_writei(alsa.ocard, sizbuf, len / 2);
634                 if (res == -EPIPE) {
635 #if DEBUG
636                         if (option_debug)
637                                 ast_log(LOG_DEBUG, "XRUN write\n");
638 #endif
639                         snd_pcm_prepare(alsa.ocard);
640                         res = snd_pcm_writei(alsa.ocard, sizbuf, len / 2);
641                         if (res != len / 2) {
642                                 ast_log(LOG_ERROR, "Write error: %s\n", snd_strerror(res));
643                                 res = -1;
644                         } else if (res < 0) {
645                                 ast_log(LOG_ERROR, "Write error %s\n", snd_strerror(res));
646                                 res = -1;
647                         }
648                 } else {
649                         if (res == -ESTRPIPE)
650                                 ast_log(LOG_ERROR, "You've got some big problems\n");
651                         else if (res < 0)
652                                 ast_log(LOG_NOTICE, "Error %d on write\n", res);
653                 }
654         }
655         ast_mutex_unlock(&alsalock);
656         if (res > 0)
657                 res = 0;
658         return res;
659 }
660
661
662 static struct ast_frame *alsa_read(struct ast_channel *chan)
663 {
664         static struct ast_frame f;
665         static short __buf[FRAME_SIZE + AST_FRIENDLY_OFFSET / 2];
666         short *buf;
667         static int readpos = 0;
668         static int left = FRAME_SIZE;
669         snd_pcm_state_t state;
670         int r = 0;
671         int off = 0;
672
673         ast_mutex_lock(&alsalock);
674         /* Acknowledge any pending cmd */
675         f.frametype = AST_FRAME_NULL;
676         f.subclass = 0;
677         f.samples = 0;
678         f.datalen = 0;
679         f.data = NULL;
680         f.offset = 0;
681         f.src = "Console";
682         f.mallocd = 0;
683         f.delivery.tv_sec = 0;
684         f.delivery.tv_usec = 0;
685
686         state = snd_pcm_state(alsa.icard);
687         if ((state != SND_PCM_STATE_PREPARED) && (state != SND_PCM_STATE_RUNNING)) {
688                 snd_pcm_prepare(alsa.icard);
689         }
690
691         buf = __buf + AST_FRIENDLY_OFFSET / 2;
692
693         r = snd_pcm_readi(alsa.icard, buf + readpos, left);
694         if (r == -EPIPE) {
695 #if DEBUG
696                 ast_log(LOG_ERROR, "XRUN read\n");
697 #endif
698                 snd_pcm_prepare(alsa.icard);
699         } else if (r == -ESTRPIPE) {
700                 ast_log(LOG_ERROR, "-ESTRPIPE\n");
701                 snd_pcm_prepare(alsa.icard);
702         } else if (r < 0) {
703                 ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(r));
704         } else if (r >= 0) {
705                 off -= r;
706         }
707         /* Update positions */
708         readpos += r;
709         left -= r;
710
711         if (readpos >= FRAME_SIZE) {
712                 /* A real frame */
713                 readpos = 0;
714                 left = FRAME_SIZE;
715                 if (chan->_state != AST_STATE_UP) {
716                         /* Don't transmit unless it's up */
717                         ast_mutex_unlock(&alsalock);
718                         return &f;
719                 }
720                 f.frametype = AST_FRAME_VOICE;
721                 f.subclass = AST_FORMAT_SLINEAR;
722                 f.samples = FRAME_SIZE;
723                 f.datalen = FRAME_SIZE * 2;
724                 f.data = buf;
725                 f.offset = AST_FRIENDLY_OFFSET;
726                 f.src = "Console";
727                 f.mallocd = 0;
728 #ifdef ALSA_MONITOR
729                 alsa_monitor_read((char *) buf, FRAME_SIZE * 2);
730 #endif
731
732         }
733         ast_mutex_unlock(&alsalock);
734         return &f;
735 }
736
737 static int alsa_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
738 {
739         struct chan_alsa_pvt *p = newchan->tech_pvt;
740         ast_mutex_lock(&alsalock);
741         p->owner = newchan;
742         ast_mutex_unlock(&alsalock);
743         return 0;
744 }
745
746 static int alsa_indicate(struct ast_channel *chan, int cond, const void *data, size_t datalen)
747 {
748         int res = 0;
749
750         ast_mutex_lock(&alsalock);
751
752         switch (cond) {
753                 case AST_CONTROL_BUSY:
754                         res = 1;
755                         break;
756                 case AST_CONTROL_CONGESTION:
757                         res = 2;
758                         break;
759                 case AST_CONTROL_RINGING:
760                         break;
761                 case -1:
762                         res = -1;
763                         break;
764                 case AST_CONTROL_VIDUPDATE:
765                         res = -1;
766                         break;
767                 case AST_CONTROL_HOLD:
768                         ast_verbose(" << Console Has Been Placed on Hold >> \n");
769                         ast_moh_start(chan, data, mohinterpret);
770                         break;
771                 case AST_CONTROL_UNHOLD:
772                         ast_verbose(" << Console Has Been Retrieved from Hold >> \n");
773                         ast_moh_stop(chan);
774                         break;
775                 default:
776                         ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
777                         res = -1;
778         }
779
780         if (res > -1)
781                 write(sndcmd[1], &res, sizeof(res));
782
783         ast_mutex_unlock(&alsalock);
784
785         return res;
786 }
787
788 static struct ast_channel *alsa_new(struct chan_alsa_pvt *p, int state)
789 {
790         struct ast_channel *tmp = NULL;
791
792         if (!(tmp = ast_channel_alloc(1, state, 0, 0, "ALSA/%s", indevname)))
793                 return NULL;
794
795         tmp->tech = &alsa_tech;
796         tmp->fds[0] = readdev;
797         tmp->nativeformats = AST_FORMAT_SLINEAR;
798         tmp->readformat = AST_FORMAT_SLINEAR;
799         tmp->writeformat = AST_FORMAT_SLINEAR;
800         tmp->tech_pvt = p;
801         if (!ast_strlen_zero(p->context))
802                 ast_copy_string(tmp->context, p->context, sizeof(tmp->context));
803         if (!ast_strlen_zero(p->exten))
804                 ast_copy_string(tmp->exten, p->exten, sizeof(tmp->exten));
805         if (!ast_strlen_zero(language))
806                 ast_string_field_set(tmp, language, language);
807         p->owner = tmp;
808         ast_jb_configure(tmp, &global_jbconf);
809         if (state != AST_STATE_DOWN) {
810                 if (ast_pbx_start(tmp)) {
811                         ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
812                         ast_hangup(tmp);
813                         tmp = NULL;
814                 }
815         }
816
817         return tmp;
818 }
819
820 static struct ast_channel *alsa_request(const char *type, int format, void *data, int *cause)
821 {
822         int oldformat = format;
823         struct ast_channel *tmp = NULL;
824
825         format &= AST_FORMAT_SLINEAR;
826         if (!format) {
827                 ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
828                 return NULL;
829         }
830
831         ast_mutex_lock(&alsalock);
832
833         if (alsa.owner) {
834                 ast_log(LOG_NOTICE, "Already have a call on the ALSA channel\n");
835                 *cause = AST_CAUSE_BUSY;
836         } else if (!(tmp = alsa_new(&alsa, AST_STATE_DOWN)))
837                 ast_log(LOG_WARNING, "Unable to create new ALSA channel\n");
838
839         ast_mutex_unlock(&alsalock);
840
841         return tmp;
842 }
843
844 static int console_autoanswer(int fd, int argc, char *argv[])
845 {
846         int res = RESULT_SUCCESS;;
847         if ((argc != 2) && (argc != 3))
848                 return RESULT_SHOWUSAGE;
849         ast_mutex_lock(&alsalock);
850         if (argc == 2) {
851                 ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
852         } else {
853                 if (!strcasecmp(argv[2], "on"))
854                         autoanswer = -1;
855                 else if (!strcasecmp(argv[2], "off"))
856                         autoanswer = 0;
857                 else
858                         res = RESULT_SHOWUSAGE;
859         }
860         ast_mutex_unlock(&alsalock);
861         return res;
862 }
863
864 static char *autoanswer_complete(const char *line, const char *word, int pos, int state)
865 {
866 #ifndef MIN
867 #define MIN(a,b) ((a) < (b) ? (a) : (b))
868 #endif
869         switch (state) {
870                 case 0:
871                         if (!ast_strlen_zero(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
872                                 return ast_strdup("on");
873                 case 1:
874                         if (!ast_strlen_zero(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
875                                 return ast_strdup("off");
876                 default:
877                         return NULL;
878         }
879         return NULL;
880 }
881
882 static const char autoanswer_usage[] =
883         "Usage: console autoanswer [on|off]\n"
884         "       Enables or disables autoanswer feature.  If used without\n"
885         "       argument, displays the current on/off status of autoanswer.\n"
886         "       The default value of autoanswer is in 'alsa.conf'.\n";
887
888 static int console_answer(int fd, int argc, char *argv[])
889 {
890         int res = RESULT_SUCCESS;
891
892         if (argc != 2)
893                 return RESULT_SHOWUSAGE;
894
895         ast_mutex_lock(&alsalock);
896
897         if (!alsa.owner) {
898                 ast_cli(fd, "No one is calling us\n");
899                 res = RESULT_FAILURE;
900         } else {
901                 hookstate = 1;
902                 cursound = -1;
903                 grab_owner();
904                 if (alsa.owner) {
905                         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
906                         ast_queue_frame(alsa.owner, &f);
907                         ast_mutex_unlock(&alsa.owner->lock);
908                 }
909                 answer_sound();
910         }
911
912         snd_pcm_prepare(alsa.icard);
913         snd_pcm_start(alsa.icard);
914
915         ast_mutex_unlock(&alsalock);
916
917         return RESULT_SUCCESS;
918 }
919
920 static const char sendtext_usage[] =
921         "Usage: console send text <message>\n"
922         "       Sends a text message for display on the remote terminal.\n";
923
924 static int console_sendtext(int fd, int argc, char *argv[])
925 {
926         int tmparg = 3;
927         int res = RESULT_SUCCESS;
928
929         if (argc < 3)
930                 return RESULT_SHOWUSAGE;
931
932         ast_mutex_lock(&alsalock);
933
934         if (!alsa.owner) {
935                 ast_cli(fd, "No one is calling us\n");
936                 res = RESULT_FAILURE;
937         } else {
938                 struct ast_frame f = { AST_FRAME_TEXT, 0 };
939                 char text2send[256] = "";
940                 text2send[0] = '\0';
941                 while (tmparg < argc) {
942                         strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send) - 1);
943                         strncat(text2send, " ", sizeof(text2send) - strlen(text2send) - 1);
944                 }
945                 text2send[strlen(text2send) - 1] = '\n';
946                 f.data = text2send;
947                 f.datalen = strlen(text2send) + 1;
948                 grab_owner();
949                 if (alsa.owner) {
950                         ast_queue_frame(alsa.owner, &f);
951                         f.frametype = AST_FRAME_CONTROL;
952                         f.subclass = AST_CONTROL_ANSWER;
953                         f.data = NULL;
954                         f.datalen = 0;
955                         ast_queue_frame(alsa.owner, &f);
956                         ast_mutex_unlock(&alsa.owner->lock);
957                 }
958         }
959
960         ast_mutex_unlock(&alsalock);
961
962         return res;
963 }
964
965 static const char answer_usage[] =
966         "Usage: console 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
973         if (argc != 2)
974                 return RESULT_SHOWUSAGE;
975
976         cursound = -1;
977
978         ast_mutex_lock(&alsalock);
979
980         if (!alsa.owner && !hookstate) {
981                 ast_cli(fd, "No call to hangup up\n");
982                 res = RESULT_FAILURE;
983         } else {
984                 hookstate = 0;
985                 grab_owner();
986                 if (alsa.owner) {
987                         ast_queue_hangup(alsa.owner);
988                         ast_mutex_unlock(&alsa.owner->lock);
989                 }
990         }
991
992         ast_mutex_unlock(&alsalock);
993
994         return res;
995 }
996
997 static const char hangup_usage[] =
998         "Usage: console hangup\n"
999         "       Hangs up any call currently placed on the console.\n";
1000
1001 static int console_dial(int fd, int argc, char *argv[])
1002 {
1003         char tmp[256], *tmp2;
1004         char *mye, *myc;
1005         char *d;
1006         int res = RESULT_SUCCESS;
1007
1008         if ((argc != 2) && (argc != 3))
1009                 return RESULT_SHOWUSAGE;
1010
1011         ast_mutex_lock(&alsalock);
1012
1013         if (alsa.owner) {
1014                 if (argc == 3) {
1015                         d = argv[2];
1016                         grab_owner();
1017                         if (alsa.owner) {
1018                                 struct ast_frame f = { AST_FRAME_DTMF };
1019                                 while (*d) {
1020                                         f.subclass = *d;
1021                                         ast_queue_frame(alsa.owner, &f);
1022                                         d++;
1023                                 }
1024                                 ast_mutex_unlock(&alsa.owner->lock);
1025                         }
1026                 } else {
1027                         ast_cli(fd, "You're already in a call.  You can use this only to dial digits until you hangup\n");
1028                         res = RESULT_FAILURE;
1029                 }
1030         } else {
1031                 mye = exten;
1032                 myc = context;
1033                 if (argc == 3) {
1034                         char *stringp = NULL;
1035                         ast_copy_string(tmp, argv[2], sizeof(tmp));
1036                         stringp = tmp;
1037                         strsep(&stringp, "@");
1038                         tmp2 = strsep(&stringp, "@");
1039                         if (!ast_strlen_zero(tmp))
1040                                 mye = tmp;
1041                         if (!ast_strlen_zero(tmp2))
1042                                 myc = tmp2;
1043                 }
1044                 if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
1045                         ast_copy_string(alsa.exten, mye, sizeof(alsa.exten));
1046                         ast_copy_string(alsa.context, myc, sizeof(alsa.context));
1047                         hookstate = 1;
1048                         alsa_new(&alsa, AST_STATE_RINGING);
1049                 } else
1050                         ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
1051         }
1052
1053         ast_mutex_unlock(&alsalock);
1054
1055         return res;
1056 }
1057
1058 static const char dial_usage[] =
1059         "Usage: console dial [extension[@context]]\n"
1060         "       Dials a given extension (and context if specified)\n";
1061
1062 static struct ast_cli_entry cli_alsa[] = {
1063         { { "console", "answer", NULL },
1064         console_answer, "Answer an incoming console call",
1065         answer_usage },
1066
1067         { { "console", "hangup", NULL },
1068         console_hangup, "Hangup a call on the console",
1069         hangup_usage },
1070
1071         { { "console", "dial", NULL },
1072         console_dial, "Dial an extension on the console",
1073         dial_usage },
1074
1075         { { "console", "send", "text", NULL },
1076         console_sendtext, "Send text to the remote device",
1077         sendtext_usage },
1078
1079         { { "console", "autoanswer", NULL },
1080         console_autoanswer, "Sets/displays autoanswer",
1081         autoanswer_usage, autoanswer_complete },
1082 };
1083
1084 static int load_module(void)
1085 {
1086         struct ast_config *cfg;
1087         struct ast_variable *v;
1088
1089         /* Copy the default jb config over global_jbconf */
1090         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1091
1092         strcpy(mohinterpret, "default");
1093
1094         if (!(cfg = ast_config_load(config)))
1095                 return AST_MODULE_LOAD_DECLINE;
1096
1097         v = ast_variable_browse(cfg, "general");
1098         for (; v; v = v->next) {
1099                 /* handle jb conf */
1100                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
1101                                 continue;
1102                 
1103                 if (!strcasecmp(v->name, "autoanswer"))
1104                         autoanswer = ast_true(v->value);
1105                 else if (!strcasecmp(v->name, "silencesuppression"))
1106                         silencesuppression = ast_true(v->value);
1107                 else if (!strcasecmp(v->name, "silencethreshold"))
1108                         silencethreshold = atoi(v->value);
1109                 else if (!strcasecmp(v->name, "context"))
1110                         ast_copy_string(context, v->value, sizeof(context));
1111                 else if (!strcasecmp(v->name, "language"))
1112                         ast_copy_string(language, v->value, sizeof(language));
1113                 else if (!strcasecmp(v->name, "extension"))
1114                         ast_copy_string(exten, v->value, sizeof(exten));
1115                 else if (!strcasecmp(v->name, "input_device"))
1116                         ast_copy_string(indevname, v->value, sizeof(indevname));
1117                 else if (!strcasecmp(v->name, "output_device"))
1118                         ast_copy_string(outdevname, v->value, sizeof(outdevname));
1119                 else if (!strcasecmp(v->name, "mohinterpret"))
1120                         ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
1121         }
1122         ast_config_destroy(cfg);
1123
1124         if (pipe(sndcmd)) {
1125                 ast_log(LOG_ERROR, "Unable to create pipe\n");
1126                 return AST_MODULE_LOAD_FAILURE;
1127         }
1128
1129         if (soundcard_init() < 0) {
1130                 if (option_verbose > 1) {
1131                         ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
1132                         ast_verbose(VERBOSE_PREFIX_2 "Turn off ALSA support by adding 'noload=chan_alsa.so' in /etc/asterisk/modules.conf\n");
1133                 }
1134                 return AST_MODULE_LOAD_DECLINE;
1135         }
1136
1137         if (ast_channel_register(&alsa_tech)) {
1138                 ast_log(LOG_ERROR, "Unable to register channel class 'Console'\n");
1139                 return AST_MODULE_LOAD_FAILURE;
1140         }
1141
1142         ast_cli_register_multiple(cli_alsa, sizeof(cli_alsa) / sizeof(struct ast_cli_entry));
1143
1144         ast_pthread_create_background(&sthread, NULL, sound_thread, NULL);
1145 #ifdef ALSA_MONITOR
1146         if (alsa_monitor_start())
1147                 ast_log(LOG_ERROR, "Problem starting Monitoring\n");
1148 #endif
1149         return AST_MODULE_LOAD_SUCCESS;
1150 }
1151
1152 static int unload_module(void)
1153 {
1154         ast_channel_unregister(&alsa_tech);
1155         ast_cli_unregister_multiple(cli_alsa, sizeof(cli_alsa) / sizeof(struct ast_cli_entry));
1156
1157         if (alsa.icard)
1158                 snd_pcm_close(alsa.icard);
1159         if (alsa.ocard)
1160                 snd_pcm_close(alsa.ocard);
1161         if (sndcmd[0] > 0) {
1162                 close(sndcmd[0]);
1163                 close(sndcmd[1]);
1164         }
1165         if (alsa.owner)
1166                 ast_softhangup(alsa.owner, AST_SOFTHANGUP_APPUNLOAD);
1167         if (alsa.owner)
1168                 return -1;
1169         return 0;
1170 }
1171
1172 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "ALSA Console Channel Driver");