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