Small fix in outbound proxy support.
[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         ast_module_unref(ast_module_info->self);
584         if (hookstate) {
585                 hookstate = 0;
586                 if (!autoanswer) {
587                         /* Congestion noise */
588                         res = 2;
589                         write(sndcmd[1], &res, sizeof(res));
590                 }
591         }
592         snd_pcm_drop(alsa.icard);
593         ast_mutex_unlock(&alsalock);
594         return 0;
595 }
596
597 static int alsa_write(struct ast_channel *chan, struct ast_frame *f)
598 {
599         static char sizbuf[8000];
600         static int sizpos = 0;
601         int len = sizpos;
602         int pos;
603         int res = 0;
604         /* size_t frames = 0; */
605         snd_pcm_state_t state;
606
607         /* Immediately return if no sound is enabled */
608         if (nosound)
609                 return 0;
610
611         ast_mutex_lock(&alsalock);
612         /* Stop any currently playing sound */
613         if (cursound != -1) {
614                 snd_pcm_drop(alsa.ocard);
615                 snd_pcm_prepare(alsa.ocard);
616                 cursound = -1;
617         }
618
619
620         /* We have to digest the frame in 160-byte portions */
621         if (f->datalen > sizeof(sizbuf) - sizpos) {
622                 ast_log(LOG_WARNING, "Frame too large\n");
623                 res = -1;
624         } else {
625                 memcpy(sizbuf + sizpos, f->data, f->datalen);
626                 len += f->datalen;
627                 pos = 0;
628 #ifdef ALSA_MONITOR
629                 alsa_monitor_write(sizbuf, len);
630 #endif
631                 state = snd_pcm_state(alsa.ocard);
632                 if (state == SND_PCM_STATE_XRUN)
633                         snd_pcm_prepare(alsa.ocard);
634                 res = snd_pcm_writei(alsa.ocard, sizbuf, len / 2);
635                 if (res == -EPIPE) {
636 #if DEBUG
637                         if (option_debug)
638                                 ast_log(LOG_DEBUG, "XRUN write\n");
639 #endif
640                         snd_pcm_prepare(alsa.ocard);
641                         res = snd_pcm_writei(alsa.ocard, sizbuf, len / 2);
642                         if (res != len / 2) {
643                                 ast_log(LOG_ERROR, "Write error: %s\n", snd_strerror(res));
644                                 res = -1;
645                         } else if (res < 0) {
646                                 ast_log(LOG_ERROR, "Write error %s\n", snd_strerror(res));
647                                 res = -1;
648                         }
649                 } else {
650                         if (res == -ESTRPIPE)
651                                 ast_log(LOG_ERROR, "You've got some big problems\n");
652                         else if (res < 0)
653                                 ast_log(LOG_NOTICE, "Error %d on write\n", res);
654                 }
655         }
656         ast_mutex_unlock(&alsalock);
657         if (res > 0)
658                 res = 0;
659         return res;
660 }
661
662
663 static struct ast_frame *alsa_read(struct ast_channel *chan)
664 {
665         static struct ast_frame f;
666         static short __buf[FRAME_SIZE + AST_FRIENDLY_OFFSET / 2];
667         short *buf;
668         static int readpos = 0;
669         static int left = FRAME_SIZE;
670         snd_pcm_state_t state;
671         int r = 0;
672         int off = 0;
673
674         ast_mutex_lock(&alsalock);
675         /* Acknowledge any pending cmd */
676         f.frametype = AST_FRAME_NULL;
677         f.subclass = 0;
678         f.samples = 0;
679         f.datalen = 0;
680         f.data = NULL;
681         f.offset = 0;
682         f.src = "Console";
683         f.mallocd = 0;
684         f.delivery.tv_sec = 0;
685         f.delivery.tv_usec = 0;
686
687         state = snd_pcm_state(alsa.icard);
688         if ((state != SND_PCM_STATE_PREPARED) && (state != SND_PCM_STATE_RUNNING)) {
689                 snd_pcm_prepare(alsa.icard);
690         }
691
692         buf = __buf + AST_FRIENDLY_OFFSET / 2;
693
694         r = snd_pcm_readi(alsa.icard, buf + readpos, left);
695         if (r == -EPIPE) {
696 #if DEBUG
697                 ast_log(LOG_ERROR, "XRUN read\n");
698 #endif
699                 snd_pcm_prepare(alsa.icard);
700         } else if (r == -ESTRPIPE) {
701                 ast_log(LOG_ERROR, "-ESTRPIPE\n");
702                 snd_pcm_prepare(alsa.icard);
703         } else if (r < 0) {
704                 ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(r));
705         } else if (r >= 0) {
706                 off -= r;
707         }
708         /* Update positions */
709         readpos += r;
710         left -= r;
711
712         if (readpos >= FRAME_SIZE) {
713                 /* A real frame */
714                 readpos = 0;
715                 left = FRAME_SIZE;
716                 if (chan->_state != AST_STATE_UP) {
717                         /* Don't transmit unless it's up */
718                         ast_mutex_unlock(&alsalock);
719                         return &f;
720                 }
721                 f.frametype = AST_FRAME_VOICE;
722                 f.subclass = AST_FORMAT_SLINEAR;
723                 f.samples = FRAME_SIZE;
724                 f.datalen = FRAME_SIZE * 2;
725                 f.data = buf;
726                 f.offset = AST_FRIENDLY_OFFSET;
727                 f.src = "Console";
728                 f.mallocd = 0;
729 #ifdef ALSA_MONITOR
730                 alsa_monitor_read((char *) buf, FRAME_SIZE * 2);
731 #endif
732
733         }
734         ast_mutex_unlock(&alsalock);
735         return &f;
736 }
737
738 static int alsa_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
739 {
740         struct chan_alsa_pvt *p = newchan->tech_pvt;
741         ast_mutex_lock(&alsalock);
742         p->owner = newchan;
743         ast_mutex_unlock(&alsalock);
744         return 0;
745 }
746
747 static int alsa_indicate(struct ast_channel *chan, int cond, const void *data, size_t datalen)
748 {
749         int res = 0;
750
751         ast_mutex_lock(&alsalock);
752
753         switch (cond) {
754                 case AST_CONTROL_BUSY:
755                         res = 1;
756                         break;
757                 case AST_CONTROL_CONGESTION:
758                         res = 2;
759                         break;
760                 case AST_CONTROL_RINGING:
761                         break;
762                 case -1:
763                         res = -1;
764                         break;
765                 case AST_CONTROL_VIDUPDATE:
766                         res = -1;
767                         break;
768                 case AST_CONTROL_HOLD:
769                         ast_verbose(" << Console Has Been Placed on Hold >> \n");
770                         ast_moh_start(chan, data, mohinterpret);
771                         break;
772                 case AST_CONTROL_UNHOLD:
773                         ast_verbose(" << Console Has Been Retrieved from Hold >> \n");
774                         ast_moh_stop(chan);
775                         break;
776                 default:
777                         ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
778                         res = -1;
779         }
780
781         if (res > -1)
782                 write(sndcmd[1], &res, sizeof(res));
783
784         ast_mutex_unlock(&alsalock);
785
786         return res;
787 }
788
789 static struct ast_channel *alsa_new(struct chan_alsa_pvt *p, int state)
790 {
791         struct ast_channel *tmp = NULL;
792
793         if (!(tmp = ast_channel_alloc(1, state, 0, 0, "ALSA/%s", indevname)))
794                 return NULL;
795
796         tmp->tech = &alsa_tech;
797         tmp->fds[0] = readdev;
798         tmp->nativeformats = AST_FORMAT_SLINEAR;
799         tmp->readformat = AST_FORMAT_SLINEAR;
800         tmp->writeformat = AST_FORMAT_SLINEAR;
801         tmp->tech_pvt = p;
802         if (!ast_strlen_zero(p->context))
803                 ast_copy_string(tmp->context, p->context, sizeof(tmp->context));
804         if (!ast_strlen_zero(p->exten))
805                 ast_copy_string(tmp->exten, p->exten, sizeof(tmp->exten));
806         if (!ast_strlen_zero(language))
807                 ast_string_field_set(tmp, language, language);
808         p->owner = tmp;
809         ast_module_ref(ast_module_info->self);
810         ast_jb_configure(tmp, &global_jbconf);
811         if (state != AST_STATE_DOWN) {
812                 if (ast_pbx_start(tmp)) {
813                         ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
814                         ast_hangup(tmp);
815                         tmp = NULL;
816                 }
817         }
818
819         return tmp;
820 }
821
822 static struct ast_channel *alsa_request(const char *type, int format, void *data, int *cause)
823 {
824         int oldformat = format;
825         struct ast_channel *tmp = NULL;
826
827         format &= AST_FORMAT_SLINEAR;
828         if (!format) {
829                 ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
830                 return NULL;
831         }
832
833         ast_mutex_lock(&alsalock);
834
835         if (alsa.owner) {
836                 ast_log(LOG_NOTICE, "Already have a call on the ALSA channel\n");
837                 *cause = AST_CAUSE_BUSY;
838         } else if (!(tmp = alsa_new(&alsa, AST_STATE_DOWN)))
839                 ast_log(LOG_WARNING, "Unable to create new ALSA channel\n");
840
841         ast_mutex_unlock(&alsalock);
842
843         return tmp;
844 }
845
846 static int console_autoanswer(int fd, int argc, char *argv[])
847 {
848         int res = RESULT_SUCCESS;;
849         if ((argc != 2) && (argc != 3))
850                 return RESULT_SHOWUSAGE;
851         ast_mutex_lock(&alsalock);
852         if (argc == 2) {
853                 ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
854         } else {
855                 if (!strcasecmp(argv[2], "on"))
856                         autoanswer = -1;
857                 else if (!strcasecmp(argv[2], "off"))
858                         autoanswer = 0;
859                 else
860                         res = RESULT_SHOWUSAGE;
861         }
862         ast_mutex_unlock(&alsalock);
863         return res;
864 }
865
866 static char *autoanswer_complete(const char *line, const char *word, int pos, int state)
867 {
868 #ifndef MIN
869 #define MIN(a,b) ((a) < (b) ? (a) : (b))
870 #endif
871         switch (state) {
872                 case 0:
873                         if (!ast_strlen_zero(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
874                                 return ast_strdup("on");
875                 case 1:
876                         if (!ast_strlen_zero(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
877                                 return ast_strdup("off");
878                 default:
879                         return NULL;
880         }
881         return NULL;
882 }
883
884 static const char autoanswer_usage[] =
885         "Usage: console autoanswer [on|off]\n"
886         "       Enables or disables autoanswer feature.  If used without\n"
887         "       argument, displays the current on/off status of autoanswer.\n"
888         "       The default value of autoanswer is in 'alsa.conf'.\n";
889
890 static int console_answer(int fd, int argc, char *argv[])
891 {
892         int res = RESULT_SUCCESS;
893
894         if (argc != 2)
895                 return RESULT_SHOWUSAGE;
896
897         ast_mutex_lock(&alsalock);
898
899         if (!alsa.owner) {
900                 ast_cli(fd, "No one is calling us\n");
901                 res = RESULT_FAILURE;
902         } else {
903                 hookstate = 1;
904                 cursound = -1;
905                 grab_owner();
906                 if (alsa.owner) {
907                         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
908                         ast_queue_frame(alsa.owner, &f);
909                         ast_mutex_unlock(&alsa.owner->lock);
910                 }
911                 answer_sound();
912         }
913
914         snd_pcm_prepare(alsa.icard);
915         snd_pcm_start(alsa.icard);
916
917         ast_mutex_unlock(&alsalock);
918
919         return RESULT_SUCCESS;
920 }
921
922 static const char sendtext_usage[] =
923         "Usage: console send text <message>\n"
924         "       Sends a text message for display on the remote terminal.\n";
925
926 static int console_sendtext(int fd, int argc, char *argv[])
927 {
928         int tmparg = 3;
929         int res = RESULT_SUCCESS;
930
931         if (argc < 3)
932                 return RESULT_SHOWUSAGE;
933
934         ast_mutex_lock(&alsalock);
935
936         if (!alsa.owner) {
937                 ast_cli(fd, "No one is calling us\n");
938                 res = RESULT_FAILURE;
939         } else {
940                 struct ast_frame f = { AST_FRAME_TEXT, 0 };
941                 char text2send[256] = "";
942                 text2send[0] = '\0';
943                 while (tmparg < argc) {
944                         strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send) - 1);
945                         strncat(text2send, " ", sizeof(text2send) - strlen(text2send) - 1);
946                 }
947                 text2send[strlen(text2send) - 1] = '\n';
948                 f.data = text2send;
949                 f.datalen = strlen(text2send) + 1;
950                 grab_owner();
951                 if (alsa.owner) {
952                         ast_queue_frame(alsa.owner, &f);
953                         f.frametype = AST_FRAME_CONTROL;
954                         f.subclass = AST_CONTROL_ANSWER;
955                         f.data = NULL;
956                         f.datalen = 0;
957                         ast_queue_frame(alsa.owner, &f);
958                         ast_mutex_unlock(&alsa.owner->lock);
959                 }
960         }
961
962         ast_mutex_unlock(&alsalock);
963
964         return res;
965 }
966
967 static const char answer_usage[] =
968         "Usage: console answer\n"
969         "       Answers an incoming call on the console (ALSA) channel.\n";
970
971 static int console_hangup(int fd, int argc, char *argv[])
972 {
973         int res = RESULT_SUCCESS;
974
975         if (argc != 2)
976                 return RESULT_SHOWUSAGE;
977
978         cursound = -1;
979
980         ast_mutex_lock(&alsalock);
981
982         if (!alsa.owner && !hookstate) {
983                 ast_cli(fd, "No call to hangup up\n");
984                 res = RESULT_FAILURE;
985         } else {
986                 hookstate = 0;
987                 grab_owner();
988                 if (alsa.owner) {
989                         ast_queue_hangup(alsa.owner);
990                         ast_mutex_unlock(&alsa.owner->lock);
991                 }
992         }
993
994         ast_mutex_unlock(&alsalock);
995
996         return res;
997 }
998
999 static const char hangup_usage[] =
1000         "Usage: console hangup\n"
1001         "       Hangs up any call currently placed on the console.\n";
1002
1003 static int console_dial(int fd, int argc, char *argv[])
1004 {
1005         char tmp[256], *tmp2;
1006         char *mye, *myc;
1007         char *d;
1008         int res = RESULT_SUCCESS;
1009
1010         if ((argc != 2) && (argc != 3))
1011                 return RESULT_SHOWUSAGE;
1012
1013         ast_mutex_lock(&alsalock);
1014
1015         if (alsa.owner) {
1016                 if (argc == 3) {
1017                         d = argv[2];
1018                         grab_owner();
1019                         if (alsa.owner) {
1020                                 struct ast_frame f = { AST_FRAME_DTMF };
1021                                 while (*d) {
1022                                         f.subclass = *d;
1023                                         ast_queue_frame(alsa.owner, &f);
1024                                         d++;
1025                                 }
1026                                 ast_mutex_unlock(&alsa.owner->lock);
1027                         }
1028                 } else {
1029                         ast_cli(fd, "You're already in a call.  You can use this only to dial digits until you hangup\n");
1030                         res = RESULT_FAILURE;
1031                 }
1032         } else {
1033                 mye = exten;
1034                 myc = context;
1035                 if (argc == 3) {
1036                         char *stringp = NULL;
1037                         ast_copy_string(tmp, argv[2], sizeof(tmp));
1038                         stringp = tmp;
1039                         strsep(&stringp, "@");
1040                         tmp2 = strsep(&stringp, "@");
1041                         if (!ast_strlen_zero(tmp))
1042                                 mye = tmp;
1043                         if (!ast_strlen_zero(tmp2))
1044                                 myc = tmp2;
1045                 }
1046                 if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
1047                         ast_copy_string(alsa.exten, mye, sizeof(alsa.exten));
1048                         ast_copy_string(alsa.context, myc, sizeof(alsa.context));
1049                         hookstate = 1;
1050                         alsa_new(&alsa, AST_STATE_RINGING);
1051                 } else
1052                         ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
1053         }
1054
1055         ast_mutex_unlock(&alsalock);
1056
1057         return res;
1058 }
1059
1060 static const char dial_usage[] =
1061         "Usage: console dial [extension[@context]]\n"
1062         "       Dials a given extension (and context if specified)\n";
1063
1064 static struct ast_cli_entry cli_alsa[] = {
1065         { { "console", "answer", NULL },
1066         console_answer, "Answer an incoming console call",
1067         answer_usage },
1068
1069         { { "console", "hangup", NULL },
1070         console_hangup, "Hangup a call on the console",
1071         hangup_usage },
1072
1073         { { "console", "dial", NULL },
1074         console_dial, "Dial an extension on the console",
1075         dial_usage },
1076
1077         { { "console", "send", "text", NULL },
1078         console_sendtext, "Send text to the remote device",
1079         sendtext_usage },
1080
1081         { { "console", "autoanswer", NULL },
1082         console_autoanswer, "Sets/displays autoanswer",
1083         autoanswer_usage, autoanswer_complete },
1084 };
1085
1086 static int load_module(void)
1087 {
1088         struct ast_config *cfg;
1089         struct ast_variable *v;
1090
1091         /* Copy the default jb config over global_jbconf */
1092         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1093
1094         strcpy(mohinterpret, "default");
1095
1096         if (!(cfg = ast_config_load(config)))
1097                 return AST_MODULE_LOAD_DECLINE;
1098
1099         v = ast_variable_browse(cfg, "general");
1100         for (; v; v = v->next) {
1101                 /* handle jb conf */
1102                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
1103                                 continue;
1104                 
1105                 if (!strcasecmp(v->name, "autoanswer"))
1106                         autoanswer = ast_true(v->value);
1107                 else if (!strcasecmp(v->name, "silencesuppression"))
1108                         silencesuppression = ast_true(v->value);
1109                 else if (!strcasecmp(v->name, "silencethreshold"))
1110                         silencethreshold = atoi(v->value);
1111                 else if (!strcasecmp(v->name, "context"))
1112                         ast_copy_string(context, v->value, sizeof(context));
1113                 else if (!strcasecmp(v->name, "language"))
1114                         ast_copy_string(language, v->value, sizeof(language));
1115                 else if (!strcasecmp(v->name, "extension"))
1116                         ast_copy_string(exten, v->value, sizeof(exten));
1117                 else if (!strcasecmp(v->name, "input_device"))
1118                         ast_copy_string(indevname, v->value, sizeof(indevname));
1119                 else if (!strcasecmp(v->name, "output_device"))
1120                         ast_copy_string(outdevname, v->value, sizeof(outdevname));
1121                 else if (!strcasecmp(v->name, "mohinterpret"))
1122                         ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
1123         }
1124         ast_config_destroy(cfg);
1125
1126         if (pipe(sndcmd)) {
1127                 ast_log(LOG_ERROR, "Unable to create pipe\n");
1128                 return AST_MODULE_LOAD_FAILURE;
1129         }
1130
1131         if (soundcard_init() < 0) {
1132                 if (option_verbose > 1) {
1133                         ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
1134                         ast_verbose(VERBOSE_PREFIX_2 "Turn off ALSA support by adding 'noload=chan_alsa.so' in /etc/asterisk/modules.conf\n");
1135                 }
1136                 return AST_MODULE_LOAD_DECLINE;
1137         }
1138
1139         if (ast_channel_register(&alsa_tech)) {
1140                 ast_log(LOG_ERROR, "Unable to register channel class 'Console'\n");
1141                 return AST_MODULE_LOAD_FAILURE;
1142         }
1143
1144         ast_cli_register_multiple(cli_alsa, sizeof(cli_alsa) / sizeof(struct ast_cli_entry));
1145
1146         ast_pthread_create_background(&sthread, NULL, sound_thread, NULL);
1147 #ifdef ALSA_MONITOR
1148         if (alsa_monitor_start())
1149                 ast_log(LOG_ERROR, "Problem starting Monitoring\n");
1150 #endif
1151         return AST_MODULE_LOAD_SUCCESS;
1152 }
1153
1154 static int unload_module(void)
1155 {
1156         ast_channel_unregister(&alsa_tech);
1157         ast_cli_unregister_multiple(cli_alsa, sizeof(cli_alsa) / sizeof(struct ast_cli_entry));
1158
1159         if (alsa.icard)
1160                 snd_pcm_close(alsa.icard);
1161         if (alsa.ocard)
1162                 snd_pcm_close(alsa.ocard);
1163         if (sndcmd[0] > 0) {
1164                 close(sndcmd[0]);
1165                 close(sndcmd[1]);
1166         }
1167         if (alsa.owner)
1168                 ast_softhangup(alsa.owner, AST_SOFTHANGUP_APPUNLOAD);
1169         if (alsa.owner)
1170                 return -1;
1171         return 0;
1172 }
1173
1174 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "ALSA Console Channel Driver");