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