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