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