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