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