Remove more needlock stuff
[asterisk/asterisk.git] / channels / chan_alsa.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Copyright (C) 2002, Linux Support Services
5  *
6  * By Matthew Fredrickson <creslin@linux-support.net>
7  *
8  * This program is free software, distributed under the terms of
9  * the GNU General Public License
10  */
11
12 #include <asterisk/frame.h>
13 #include <asterisk/logger.h>
14 #include <asterisk/channel.h>
15 #include <asterisk/module.h>
16 #include <asterisk/channel_pvt.h>
17 #include <asterisk/options.h>
18 #include <asterisk/pbx.h>
19 #include <asterisk/config.h>
20 #include <asterisk/cli.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/time.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29
30 #define ALSA_PCM_NEW_HW_PARAMS_API
31 #define ALSA_PCM_NEW_SW_PARAMS_API
32 #include <alsa/asoundlib.h>
33
34 #include "busy.h"
35 #include "ringtone.h"
36 #include "ring10.h"
37 #include "answer.h"
38
39 #define DEBUG 0
40 /* Which device to use */
41 #define ALSA_INDEV "default"
42 #define ALSA_OUTDEV "default"
43 #define DESIRED_RATE 8000
44
45 /* Lets use 160 sample frames, just like GSM.  */
46 #define PERIOD_SIZE 160
47 #define ALSA_MAX_BUF PERIOD_SIZE*4 + AST_FRIENDLY_OFFSET
48
49 static snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
50 static char indevname[50] = ALSA_INDEV;
51 static char outdevname[50] = ALSA_OUTDEV;
52
53 static int usecnt;
54 static int silencesuppression = 0;
55 static int silencethreshold = 1000;
56
57 #if 0
58 static struct timeval lasttime;
59 #endif
60
61 static char digits[80] = "";
62 static char text2send[80] = "";
63
64 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
65
66 static char *type = "Console";
67 static char *desc = "ALSA Console Channel Driver";
68 static char *tdesc = "ALSA Console Channel Driver";
69 static char *config = "alsa.conf";
70
71 static char context[AST_MAX_EXTENSION] = "default";
72 static char language[MAX_LANGUAGE] = "";
73 static char exten[AST_MAX_EXTENSION] = "s";
74
75 /* Command pipe */
76 static int cmd[2];
77
78 int hookstate=0;
79
80 static short silence[PERIOD_SIZE] = {0, };
81
82 struct sound {
83         int ind;
84         short *data;
85         int datalen;
86         int samplen;
87         int silencelen;
88         int repeat;
89 };
90
91 static struct sound sounds[] = {
92         { AST_CONTROL_RINGING, ringtone, sizeof(ringtone)/2, 16000, 32000, 1 },
93         { AST_CONTROL_BUSY, busy, sizeof(busy)/2, 4000, 4000, 1 },
94         { AST_CONTROL_CONGESTION, busy, sizeof(busy)/2, 2000, 2000, 1 },
95         { AST_CONTROL_RING, ring10, sizeof(ring10)/2, 16000, 32000, 1 },
96         { AST_CONTROL_ANSWER, answer, sizeof(answer)/2, 2200, 0, 0 },
97 };
98
99 /* Sound command pipe */
100 static int sndcmd[2];
101
102 typedef struct chan_alsa_pvt chan_alsa_pvt_t;
103 struct chan_alsa_pvt {
104         /* We only have one ALSA structure -- near sighted perhaps, but it
105            keeps this driver as simple as possible -- as it should be. */
106         struct ast_channel *owner;
107         char exten[AST_MAX_EXTENSION];
108         char context[AST_MAX_EXTENSION];
109         struct pollfd                *pfd;
110         unsigned int  playback_nfds;
111         unsigned int  capture_nfds;
112         snd_pcm_t *playback_handle;
113         snd_pcm_t *capture_handle;
114         snd_pcm_uframes_t capture_period_size;
115         snd_pcm_uframes_t capture_buffer_size;
116         
117         pthread_t sound_thread;
118         char buf[ALSA_MAX_BUF];          /* buffer for reading frames */
119         char *capture_buf;             /* malloc buffer for reading frames */
120         struct ast_frame fr;
121         int cursound;
122         int cursound_offset;
123         int nosound;
124 };
125
126 static chan_alsa_pvt_t alsa;
127
128 #define MAX_BUFFER_SIZE 100
129
130 static int autoanswer = 1;
131
132 /* Send a announcement */
133 static int send_sound(chan_alsa_pvt_t *driver)
134 {
135         int res;
136         int frames;
137         int cursound=driver->cursound;
138         snd_pcm_state_t state;
139
140         if (cursound > -1) {
141                 driver->nosound=1;
142                 state = snd_pcm_state(alsa.playback_handle);
143                 if (state == SND_PCM_STATE_XRUN) {
144                         snd_pcm_prepare(alsa.playback_handle);
145                 }
146                 frames = sounds[cursound].samplen - driver->cursound_offset;
147                 if (frames >= PERIOD_SIZE)  {
148                         res = snd_pcm_writei(driver->playback_handle,sounds[cursound].data + (driver->cursound_offset*2), PERIOD_SIZE);
149                         driver->cursound_offset+=PERIOD_SIZE;
150                 } else if (frames > 0) {
151                         res = snd_pcm_writei(driver->playback_handle,sounds[cursound].data + (driver->cursound_offset*2), frames);
152                         res = snd_pcm_writei(driver->playback_handle,silence, PERIOD_SIZE - frames);
153                         driver->cursound_offset+=PERIOD_SIZE;
154                         } else {
155                         res = snd_pcm_writei(driver->playback_handle,silence, PERIOD_SIZE);
156                         driver->cursound_offset+=PERIOD_SIZE;
157                 }
158                 if (driver->cursound_offset > ( sounds[cursound].samplen + sounds[cursound].silencelen ) ) {
159                                 if (sounds[cursound].repeat) {
160                                 driver->cursound_offset=0;
161                                 } else {
162                                 driver->cursound = -1;
163                                 driver->nosound=0;
164                                 }
165                         }
166                 }
167                         return 0;
168 }
169
170 static int sound_capture(chan_alsa_pvt_t *driver)
171 {
172         struct ast_frame *fr = &driver->fr;
173         char *readbuf = ((char *)driver->buf) + AST_FRIENDLY_OFFSET;
174         snd_pcm_sframes_t err;
175         snd_pcm_sframes_t avail;
176         snd_pcm_state_t alsa_state;
177         
178         /* Update positions */
179         while ((avail = snd_pcm_avail_update (driver->capture_handle)) >= PERIOD_SIZE) {
180         
181                 /* capture samples from sound card */
182                 err = snd_pcm_readi(driver->capture_handle, readbuf, PERIOD_SIZE);
183                 if (err == -EPIPE) {
184                         ast_log(LOG_ERROR, "XRUN read avail=%ld\n", avail);
185                         snd_pcm_prepare(driver->capture_handle);
186                         alsa_state = snd_pcm_state(driver->capture_handle);
187                         if (alsa_state == SND_PCM_STATE_PREPARED) {
188                                 snd_pcm_start(driver->capture_handle);
189                 }
190                         continue;
191                 } else if (err == -ESTRPIPE) {
192                         ast_log(LOG_ERROR, "-ESTRPIPE\n");
193                         snd_pcm_prepare(driver->capture_handle);
194                         alsa_state = snd_pcm_state(driver->capture_handle);
195                         if (alsa_state == SND_PCM_STATE_PREPARED) {
196                                 snd_pcm_start(driver->capture_handle);
197                 }
198                         continue;
199                 } else if (err < 0) {
200                         ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(err));
201                         return -1;
202         }
203
204                 /* Now send captures samples */
205                 fr->frametype = AST_FRAME_VOICE;
206                 fr->src = type;
207                 fr->mallocd = 0;
208
209                 fr->subclass = AST_FORMAT_SLINEAR;
210                 fr->samples = PERIOD_SIZE;
211                 fr->datalen = PERIOD_SIZE * 2 ; /* 16bit = X * 2 */
212                 fr->data = readbuf;
213                 fr->offset = AST_FRIENDLY_OFFSET;
214
215                 if (driver->owner) ast_queue_frame(driver->owner, fr);
216         }
217         return 0; /* 0 = OK, !=0 -> Error */
218 }
219
220 static void *sound_thread(void *pvt)
221 {
222         chan_alsa_pvt_t *driver = (chan_alsa_pvt_t *)pvt;
223         unsigned int nfds;
224         unsigned int ci;
225         unsigned short revents;
226         snd_pcm_state_t alsa_state;
227         int res;
228         if (driver->playback_handle) {
229                 driver->playback_nfds =
230                         snd_pcm_poll_descriptors_count (
231                                 driver->playback_handle);
232         } else {
233                 driver->playback_nfds = 0;
234                 }
235
236         if (driver->capture_handle) {
237                 driver->capture_nfds =
238                         snd_pcm_poll_descriptors_count (driver->capture_handle);
239         } else {
240                 driver->capture_nfds = 0;
241                 }
242
243         if (driver->pfd) {
244                 free (driver->pfd);
245                 }
246                         
247         driver->pfd = (struct pollfd *)
248                 malloc (sizeof (struct pollfd) *
249                         (driver->playback_nfds + driver->capture_nfds + 2));
250
251         nfds = 0;
252         if (driver->playback_handle) {
253                 snd_pcm_poll_descriptors (driver->playback_handle,
254                                           &driver->pfd[0],
255                                           driver->playback_nfds);
256                 nfds += driver->playback_nfds;
257                         }
258         ci = nfds;
259
260         if (driver->capture_handle) {
261                 snd_pcm_poll_descriptors (driver->capture_handle,
262                                           &driver->pfd[ci],
263                                           driver->capture_nfds);
264                 nfds += driver->capture_nfds;
265                 }               
266         
267         while (hookstate) {
268                 /* When no doing announcements */
269                 if (driver->cursound > -1) {
270                         res = poll(&driver->pfd[0], driver->playback_nfds, -1);
271                 } else {
272                         res = poll(&driver->pfd[ci], driver->capture_nfds, -1);
273                 }
274
275                 /* When doing announcements */
276                 if (driver->cursound > -1) {
277                         snd_pcm_poll_descriptors_revents(driver->playback_handle, &driver->pfd[0], driver->playback_nfds, &revents);
278                         if (revents & POLLOUT) {
279                                 if (send_sound(driver)) {
280                                 ast_log(LOG_WARNING, "Failed to write sound\n");
281         }
282                         }
283                 } else {
284                 snd_pcm_poll_descriptors_revents(driver->capture_handle, &driver->pfd[ci], driver->capture_nfds, &revents);
285                 if (revents & POLLERR) {
286                         alsa_state = snd_pcm_state(driver->capture_handle);
287                         if (alsa_state == SND_PCM_STATE_XRUN) {
288                                 snd_pcm_prepare(driver->capture_handle);
289                         }
290                         alsa_state = snd_pcm_state(driver->capture_handle);
291                         if (alsa_state == SND_PCM_STATE_PREPARED) {
292                                 snd_pcm_start(driver->capture_handle);
293                         }
294                 }
295                 if (revents & POLLIN) {
296                         if (sound_capture(driver)) {
297                                 ast_log(LOG_WARNING, "Failed to read sound\n");
298                         }
299                 }
300                 }
301         }
302         /* Never reached */
303         return NULL;
304 }
305
306 static snd_pcm_t *alsa_card_init(chan_alsa_pvt_t *driver, char *dev, snd_pcm_stream_t stream)
307 {
308         int err;
309         int direction;
310         snd_pcm_t *handle = NULL;
311         snd_pcm_hw_params_t *hwparams = NULL;
312         snd_pcm_sw_params_t *swparams = NULL;
313         snd_pcm_uframes_t period_size = PERIOD_SIZE;
314         snd_pcm_uframes_t buffer_size = 0;
315
316         unsigned int rate = DESIRED_RATE;
317         snd_pcm_uframes_t start_threshold, stop_threshold;
318
319         err = snd_pcm_open(&handle, dev, stream, O_NONBLOCK);
320         if (err < 0) {
321                 ast_log(LOG_ERROR, "snd_pcm_open failed: %s\n", snd_strerror(err));
322                 return NULL;
323         } else {
324                 ast_log(LOG_DEBUG, "Opening device %s in %s mode\n", dev, (stream == SND_PCM_STREAM_CAPTURE) ? "read" : "write");
325         }
326
327         snd_pcm_hw_params_alloca(&hwparams);
328         snd_pcm_hw_params_any(handle, hwparams);
329
330         err = snd_pcm_hw_params_set_access(handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
331         if (err < 0) {
332                 ast_log(LOG_ERROR, "set_access failed: %s\n", snd_strerror(err));
333         }
334
335         err = snd_pcm_hw_params_set_format(handle, hwparams, format);
336         if (err < 0) {
337                 ast_log(LOG_ERROR, "set_format failed: %s\n", snd_strerror(err));
338         }
339
340         err = snd_pcm_hw_params_set_channels(handle, hwparams, 1);
341         if (err < 0) {
342                 ast_log(LOG_ERROR, "set_channels failed: %s\n", snd_strerror(err));
343         }
344
345         direction = 0;
346         err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &rate, &direction);
347         
348         if (rate != DESIRED_RATE) {
349                 ast_log(LOG_WARNING, "Rate not correct, requested %d, got %d\n", DESIRED_RATE, rate);
350         }
351
352         direction = 0;
353         buffer_size = 4096 * 2; /* period_size * 16; */
354         err = snd_pcm_hw_params_set_period_size_near(handle, hwparams, &period_size, &direction);
355         if (err < 0) {
356                 ast_log(LOG_ERROR, "period_size(%ld frames) is bad: %s\n", period_size, snd_strerror(err));
357         } else {
358                 ast_log(LOG_DEBUG, "Period size is %d\n", err);
359         }
360
361         err = snd_pcm_hw_params_set_buffer_size_near(handle, hwparams, &buffer_size);   
362         if (err < 0) {
363                 ast_log(LOG_WARNING, "Problem setting buffer size of %ld: %s\n", buffer_size, snd_strerror(err));
364         } else {
365                 ast_log(LOG_DEBUG, "Buffer size is set to %d frames\n", err);
366         }
367
368 #if 0
369         direction = 0;
370         err = snd_pcm_hw_params_set_periods_min(handle, hwparams, &per_min, &direction);
371         if (err < 0) {
372                 ast_log(LOG_ERROR, "periods_min: %s\n", snd_strerror(err));
373         }
374
375         err = snd_pcm_hw_params_set_periods_max(handle, hwparams, &per_max, 0);
376         if (err < 0) {
377                 ast_log(LOG_ERROR, "periods_max: %s\n", snd_strerror(err));
378         }
379 #endif
380
381         if (stream == SND_PCM_STREAM_CAPTURE) {
382                 driver->capture_period_size=period_size;
383                 driver->capture_buffer_size=buffer_size;
384         }
385
386         err = snd_pcm_hw_params(handle, hwparams);
387         if (err < 0) {
388                 ast_log(LOG_ERROR, "Couldn't set the new hw params: %s\n", snd_strerror(err));
389                 return NULL;
390         }
391
392         snd_pcm_sw_params_alloca(&swparams);
393         snd_pcm_sw_params_current(handle, swparams);
394
395 #if 1
396         if (stream == SND_PCM_STREAM_PLAYBACK) {
397                 start_threshold = period_size*3;
398         } else {
399                 start_threshold = 1;
400         }
401
402         err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
403         if (err < 0) {
404                 ast_log(LOG_ERROR, "start threshold: %s\n", snd_strerror(err));
405         }
406 #endif
407
408 #if 1
409         if (stream == SND_PCM_STREAM_PLAYBACK) {
410                 stop_threshold = buffer_size;
411         } else {
412                 stop_threshold = buffer_size+1;
413         }
414         err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
415         if (err < 0) {
416                 ast_log(LOG_ERROR, "stop threshold: %s\n", snd_strerror(err));
417         }
418 #endif
419 #if 0
420         err = snd_pcm_sw_params_set_xfer_align(handle, swparams, PERIOD_SIZE);
421         if (err < 0) {
422                 ast_log(LOG_ERROR, "Unable to set xfer alignment: %s\n", snd_strerror(err));
423         }
424 #endif
425
426 #if 0
427         err = snd_pcm_sw_params_set_silence_threshold(handle, swparams, silencethreshold);
428         if (err < 0) {
429                 ast_log(LOG_ERROR, "Unable to set silence threshold: %s\n", snd_strerror(err));
430         }
431 #endif
432         err = snd_pcm_sw_params(handle, swparams);
433         if (err < 0) {
434                 ast_log(LOG_ERROR, "sw_params: %s\n", snd_strerror(err));
435         }
436
437         err = snd_pcm_poll_descriptors_count(handle);
438         if (err <= 0) {
439                 ast_log(LOG_ERROR, "Unable to get a poll descriptors count, error is %s\n", snd_strerror(err));
440         }
441
442         if (err != 1) {
443                 ast_log(LOG_DEBUG, "Can't handle more than one device\n");
444         }
445
446         return handle;
447 }
448
449 static int soundcard_init(void)
450 {
451         alsa.capture_handle = alsa_card_init(&alsa, indevname, SND_PCM_STREAM_CAPTURE);
452         alsa.playback_handle = alsa_card_init(&alsa, outdevname, SND_PCM_STREAM_PLAYBACK);
453         if (!alsa.capture_buf) alsa.capture_buf=malloc(alsa.capture_buffer_size * 2);
454
455         if (!alsa.capture_handle || !alsa.playback_handle) {
456                 ast_log(LOG_ERROR, "Problem opening alsa I/O devices\n");
457                 if (alsa.capture_buf) {
458                         free (alsa.capture_buf);
459                         alsa.capture_buf=0;
460                 }
461                 return -1;
462         }
463
464         return 0; /* Success */
465 }
466
467 static int alsa_digit(struct ast_channel *c, char digit)
468 {
469         ast_verbose( " << Console Received digit %c >> \n", digit);
470         return 0;
471 }
472
473 static int alsa_text(struct ast_channel *c, char *text)
474 {
475         ast_verbose( " << Console Received text %s >> \n", text);
476         return 0;
477 }
478
479 static int alsa_call(struct ast_channel *c, char *dest, int timeout)
480 {
481         chan_alsa_pvt_t *driver = (chan_alsa_pvt_t *)c->pvt->pvt;
482         int res = 3;
483         struct ast_frame f = { 0, };
484         ast_verbose( " << Call placed to '%s' on console >> \n", dest);
485         if (autoanswer) {
486                 ast_verbose( " << Auto-answered >> \n" );
487                 f.frametype = AST_FRAME_CONTROL;
488                 f.subclass = AST_CONTROL_ANSWER;
489                 ast_queue_frame(c, &f);
490         } else {
491                 driver->nosound = 1;
492                 ast_verbose( " << Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
493                 f.frametype = AST_FRAME_CONTROL;
494                 f.subclass = AST_CONTROL_RINGING;
495                 ast_queue_frame(c, &f);
496                 driver->cursound = res;
497         }
498         return 0;
499 }
500
501 static void answer_sound(chan_alsa_pvt_t *driver)
502 {
503         int res;
504         driver->nosound = 1;
505         driver->cursound = 4;
506         driver->cursound_offset = 0;
507         
508 }
509
510 static int alsa_answer(struct ast_channel *c)
511 {
512         chan_alsa_pvt_t *driver = (chan_alsa_pvt_t *)c->pvt->pvt;
513         ast_verbose( " << Console call has been answered >> \n");
514         answer_sound(driver);
515         ast_setstate(c, AST_STATE_UP);
516         return 0;
517 }
518
519 /* The new_channel is now freed. */
520 static int alsa_hangup(struct ast_channel *c)
521 {
522         int res;
523         chan_alsa_pvt_t *driver = (chan_alsa_pvt_t *)c->pvt->pvt;
524         
525         driver->cursound = -1;
526         driver->nosound = 0;
527         if (hookstate) {
528                 hookstate = 0;
529         }
530         pthread_join(driver->sound_thread, NULL);
531 /*      snd_pcm_drain(driver->capture_handle); */
532         driver->owner = NULL;
533         c->pvt->pvt = NULL;
534         ast_verbose( " << Hangup on console >> \n");
535         ast_mutex_lock(&usecnt_lock);
536         usecnt--;
537         ast_mutex_unlock(&usecnt_lock);
538         return 0;
539 }
540
541 static int alsa_write(struct ast_channel *chan, struct ast_frame *f)
542 {
543         chan_alsa_pvt_t *driver = (chan_alsa_pvt_t *)chan->pvt->pvt;
544         int res;
545         static char sizbuf[8000];
546         static int sizpos = 0;
547         int len = sizpos;
548         int pos;
549         snd_pcm_state_t state;
550         snd_pcm_sframes_t delay = 0;
551
552         if (driver->nosound) {
553                 return 0;
554         }
555         state = snd_pcm_state(driver->playback_handle);
556         if (state == SND_PCM_STATE_XRUN) {
557                 snd_pcm_prepare(driver->playback_handle);
558         }
559         res = snd_pcm_delay( driver->playback_handle, &delay );
560         if (delay > 4 * PERIOD_SIZE) {
561                 return 0;
562         }
563         res = snd_pcm_writei(driver->playback_handle, f->data, f->samples);
564         if (res == -EPIPE) {
565 #if DEBUG
566                 ast_log(LOG_DEBUG, "XRUN write\n");
567 #endif
568                 snd_pcm_prepare(driver->playback_handle);
569                 res = snd_pcm_writei(driver->playback_handle, f->data, f->samples);
570                 if (res != f->samples) {
571                         ast_log(LOG_ERROR, "Write error: %s\n", snd_strerror(res));
572                         return -1;
573                 } else if (res < 0) {
574                         ast_log(LOG_ERROR, "Write error %s\n", snd_strerror(res));
575                         return -1;
576                 }
577         } else {
578                 if (res == -ESTRPIPE) {
579                         ast_log(LOG_ERROR, "You've got some big problems\n");
580                 }
581         }
582
583         return 0;
584 }
585
586
587 static struct ast_frame *alsa_read(struct ast_channel *chan)
588 {
589         static struct ast_frame f;
590         static short __buf[PERIOD_SIZE + AST_FRIENDLY_OFFSET/2];
591         short *buf;
592         static int readpos = 0;
593         static int left = PERIOD_SIZE;
594         int res;
595         int b;
596         int nonull=0;
597         snd_pcm_state_t state;
598         int r = 0;
599         int off = 0;
600         /* FIXME: This should never been called */
601         ast_log(LOG_WARNING, "ALSA_READ!!!!!\n");
602         return NULL;
603 }
604 #if 0
605         /* Acknowledge any pending cmd */
606         res = read(cmd[0], &b, sizeof(b));
607         if (res > 0)
608                 nonull = 1;
609         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
610         
611         f.frametype = AST_FRAME_NULL;
612         f.subclass = 0;
613         f.samples = 0;
614         f.datalen = 0;
615         f.data = NULL;
616         f.offset = 0;
617         f.src = type;
618         f.mallocd = 0;
619         
620         if (needringing) {
621                 f.frametype = AST_FRAME_CONTROL;
622                 f.subclass = AST_CONTROL_RINGING;
623                 needringing = 0;
624                 return &f;
625         }
626         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
627         
628         if (needhangup) {
629                 needhangup = 0;
630                 return NULL;
631         }
632         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
633         if (strlen(text2send)) {
634                 f.frametype = AST_FRAME_TEXT;
635                 f.subclass = 0;
636                 f.data = text2send;
637                 f.datalen = strlen(text2send);
638                 strcpy(text2send,"");
639                 return &f;
640         }
641         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
642         if (strlen(digits)) {
643                 f.frametype = AST_FRAME_DTMF;
644                 f.subclass = digits[0];
645                 for (res=0;res<strlen(digits);res++)
646                         digits[res] = digits[res + 1];
647                 return &f;
648         }
649         
650         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
651         if (needanswer) {
652                 needanswer = 0;
653                 f.frametype = AST_FRAME_CONTROL;
654                 f.subclass = AST_CONTROL_ANSWER;
655                 ast_setstate(chan, AST_STATE_UP);
656                 return &f;
657         }
658         
659         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
660         if (nonull)
661                 return &f;
662                 
663         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
664         
665         state = snd_pcm_state(alsa.playback_handle);
666         if (state == SND_PCM_STATE_XRUN) {
667                 snd_pcm_prepare(alsa.playback_handle);
668         }
669         ast_log(LOG_WARNING, "alsa: %s:%d\n", __FUNCTION__, __LINE__);
670
671         buf = __buf + AST_FRIENDLY_OFFSET/2;
672
673         r = snd_pcm_readi(alsa.capture_handle, buf + readpos, left);
674         if (r == -EPIPE) {
675 #if DEBUG
676                 ast_log(LOG_ERROR, "XRUN read\n");
677 #endif
678                 snd_pcm_prepare(alsa.capture_handle);
679         } else if (r == -ESTRPIPE) {
680                 ast_log(LOG_ERROR, "-ESTRPIPE\n");
681                 snd_pcm_prepare(alsa.capture_handle);
682         } else if (r < 0) {
683                 ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(r));
684                 return NULL;
685         } else if (r >= 0) {
686                 off -= r;
687         }
688         /* Update positions */
689         readpos += r;
690         left -= r;
691
692         if (readpos >= PERIOD_SIZE) {
693                 /* A real frame */
694                 readpos = 0;
695                 left = PERIOD_SIZE;
696                 if (chan->_state != AST_STATE_UP) {
697                         /* Don't transmit unless it's up */
698                         return &f;
699                 }
700                 f.frametype = AST_FRAME_VOICE;
701                 f.subclass = AST_FORMAT_SLINEAR;
702                 f.samples = PERIOD_SIZE;
703                 f.datalen = PERIOD_SIZE * 2;
704                 f.data = buf;
705                 f.offset = AST_FRIENDLY_OFFSET;
706                 f.src = type;
707                 f.mallocd = 0;
708
709 #if 0
710                 { static int fd = -1;
711                   if (fd < 0)
712                         fd = open("output.raw", O_RDWR | O_TRUNC | O_CREAT);
713                   write(fd, f.data, f.datalen);
714                 }
715 #endif          
716         }
717         return &f;
718 }
719 #endif
720
721 static int alsa_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
722 {
723         struct chan_alsa_pvt *p = newchan->pvt->pvt;
724         p->owner = newchan;
725         return 0;
726 }
727
728 static int alsa_indicate(struct ast_channel *chan, int cond)
729 {
730         chan_alsa_pvt_t *driver = (chan_alsa_pvt_t *)chan->pvt->pvt;
731         int res;
732         switch(cond) {
733         case AST_CONTROL_BUSY:
734                 res = 1;
735                 break;
736         case AST_CONTROL_CONGESTION:
737                 res = 2;
738                 break;
739         case AST_CONTROL_RINGING:
740                 res = 0;
741                 break;
742         default:
743                 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
744                 return -1;
745         }
746         if (res > -1) {
747                 driver->cursound = res;
748                 driver->cursound_offset = 0;
749                 driver->nosound = 1;
750         }
751         return 0;       
752 }
753
754 /* New channel is about to be used */
755 static struct ast_channel *alsa_new(struct chan_alsa_pvt *p, int state)
756 {
757         struct ast_channel *tmp;
758         snd_pcm_state_t alsa_state;
759         if (!p->capture_handle || !p->playback_handle) {
760                 return 0;
761         }
762         tmp = ast_channel_alloc(1);
763         if (tmp) {
764                 snprintf(tmp->name, sizeof(tmp->name), "ALSA/%s", indevname);
765                 tmp->type = type;
766                 tmp->nativeformats = AST_FORMAT_SLINEAR;
767                 tmp->pvt->pvt = p;
768                 tmp->pvt->send_digit = alsa_digit;
769                 tmp->pvt->send_text = alsa_text;
770                 tmp->pvt->hangup = alsa_hangup;
771                 tmp->pvt->answer = alsa_answer;
772                 tmp->pvt->read = alsa_read;
773                 tmp->pvt->call = alsa_call;
774                 tmp->pvt->write = alsa_write;
775                 tmp->pvt->indicate = alsa_indicate;
776                 tmp->pvt->fixup = alsa_fixup;
777                 if (strlen(p->context))
778                         strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
779                 if (strlen(p->exten))
780                         strncpy(tmp->exten, p->exten, sizeof(tmp->exten)-1);
781                 if (strlen(language))
782                         strncpy(tmp->language, language, sizeof(tmp->language)-1);
783                 p->owner = tmp;
784                 p->pfd = NULL;
785                 ast_setstate(tmp, state);
786                 ast_mutex_lock(&usecnt_lock);
787                 usecnt++;
788                 ast_mutex_unlock(&usecnt_lock);
789                 ast_update_use_count();
790                 if (state != AST_STATE_DOWN) {
791                         if (ast_pbx_start(tmp)) {
792                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
793                                 ast_hangup(tmp);
794                                 tmp = NULL;
795                         }
796                 }
797                 pthread_create(&p->sound_thread, NULL, sound_thread, (void *) p);
798                 alsa_state = snd_pcm_state(p->capture_handle);
799                 if (alsa_state == SND_PCM_STATE_XRUN) {
800                         snd_pcm_prepare(p->capture_handle);
801                 }
802                 alsa_state = snd_pcm_state(p->capture_handle);
803                 if (alsa_state == SND_PCM_STATE_PREPARED) {
804                         snd_pcm_start(p->capture_handle);
805                 }
806         }
807         return tmp;
808 }
809
810 static struct ast_channel *alsa_request(char *type, int format, void *data)
811 {
812         int oldformat = format;
813         struct ast_channel *tmp;
814         format &= AST_FORMAT_SLINEAR;
815         if (!format) {
816                 ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
817                 return NULL;
818         }
819         if (alsa.owner) {
820                 ast_log(LOG_NOTICE, "Already have a call on the ALSA channel\n");
821                 return NULL;
822         }
823         tmp= alsa_new(&alsa, AST_STATE_DOWN);
824         if (!tmp) {
825                 ast_log(LOG_WARNING, "Unable to create new ALSA channel\n");
826         }
827         return tmp;
828 }
829
830 static int console_autoanswer(int fd, int argc, char *argv[])
831 {
832         if ((argc != 1) && (argc != 2))
833                 return RESULT_SHOWUSAGE;
834         if (argc == 1) {
835                 ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
836                 return RESULT_SUCCESS;
837         } else {
838                 if (!strcasecmp(argv[1], "on"))
839                         autoanswer = -1;
840                 else if (!strcasecmp(argv[1], "off"))
841                         autoanswer = 0;
842                 else
843                         return RESULT_SHOWUSAGE;
844         }
845         return RESULT_SUCCESS;
846 }
847
848 static char *autoanswer_complete(char *line, char *word, int pos, int state)
849 {
850 #ifndef MIN
851 #define MIN(a,b) ((a) < (b) ? (a) : (b))
852 #endif
853         switch(state) {
854         case 0:
855                 if (strlen(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
856                         return strdup("on");
857         case 1:
858                 if (strlen(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
859                         return strdup("off");
860         default:
861                 return NULL;
862         }
863         return NULL;
864 }
865
866 static char autoanswer_usage[] =
867 "Usage: autoanswer [on|off]\n"
868 "       Enables or disables autoanswer feature.  If used without\n"
869 "       argument, displays the current on/off status of autoanswer.\n"
870 "       The default value of autoanswer is in 'alsa.conf'.\n";
871
872 static int console_answer(int fd, int argc, char *argv[])
873 {
874         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
875         if (argc != 1)
876                 return RESULT_SHOWUSAGE;
877         if (!alsa.owner) {
878                 ast_cli(fd, "No one is calling us\n");
879                 return RESULT_FAILURE;
880         }
881         hookstate = 1;
882         ast_queue_frame(alsa.owner, &f);
883         answer_sound(&alsa);
884         return RESULT_SUCCESS;
885 }
886
887 static char sendtext_usage[] =
888 "Usage: send text <message>\n"
889 "       Sends a text message for display on the remote terminal.\n";
890
891 static int console_sendtext(int fd, int argc, char *argv[])
892 {
893         int tmparg = 2;
894         struct ast_frame f = { 0, };
895         if (argc < 2)
896                 return RESULT_SHOWUSAGE;
897         if (!alsa.owner) {
898                 ast_cli(fd, "No one is calling us\n");
899                 return RESULT_FAILURE;
900         }
901         if (strlen(text2send))
902                 ast_cli(fd, "Warning: message already waiting to be sent, overwriting\n");
903         strcpy(text2send, "");
904         while(tmparg <= argc) {
905                 strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send));
906                 strncat(text2send, " ", sizeof(text2send) - strlen(text2send));
907         }
908        if (strlen(text2send)) {
909                 f.frametype = AST_FRAME_TEXT;
910                 f.subclass = 0;
911                 f.data = text2send;
912                 f.datalen = strlen(text2send);
913                 ast_queue_frame(alsa.owner, &f);
914         }
915         return RESULT_SUCCESS;
916 }
917
918 static char answer_usage[] =
919 "Usage: answer\n"
920 "       Answers an incoming call on the console (ALSA) channel.\n";
921
922 static int console_hangup(int fd, int argc, char *argv[])
923 {
924         if (argc != 1)
925                 return RESULT_SHOWUSAGE;
926         alsa.cursound = -1;
927         alsa.nosound = 0;
928         if (!alsa.owner && !hookstate) {
929                 ast_cli(fd, "No call to hangup up\n");
930                 return RESULT_FAILURE;
931         }
932         hookstate = 0;
933         if (alsa.owner) {
934                 ast_queue_hangup(alsa.owner);
935         }
936         return RESULT_SUCCESS;
937 }
938
939 static char hangup_usage[] =
940 "Usage: hangup\n"
941 "       Hangs up any call currently placed on the console.\n";
942
943
944 static int console_dial(int fd, int argc, char *argv[])
945 {
946         char tmp[256], *tmp2;
947         char *mye, *myc;
948         int b = 0;
949         int x;
950         struct ast_frame f = { AST_FRAME_DTMF, 0 };
951         if ((argc != 1) && (argc != 2))
952                 return RESULT_SHOWUSAGE;
953         if (alsa.owner) {
954                 if (argc == 2) {
955                         for (x=0;x<strlen(argv[1]);x++) {
956                                 f.subclass = argv[1][x];
957                                 ast_queue_frame(alsa.owner, &f);
958                         }
959                 } else {
960                         ast_cli(fd, "You're already in a call.  You can use this only to dial digits until you hangup\n");
961                         return RESULT_FAILURE;
962                 }
963                 return RESULT_SUCCESS;
964         }
965         mye = exten;
966         myc = context;
967         if (argc == 2) {
968                 char *stringp=NULL;
969                 strncpy(tmp, argv[1], sizeof(tmp)-1);
970                 stringp=tmp;
971                 strsep(&stringp, "@");
972                 tmp2 = strsep(&stringp, "@");
973                 if (strlen(tmp))
974                         mye = tmp;
975                 if (tmp2 && strlen(tmp2))
976                         myc = tmp2;
977         }
978         if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
979                 strncpy(alsa.exten, mye, sizeof(alsa.exten)-1);
980                 strncpy(alsa.context, myc, sizeof(alsa.context)-1);
981                 hookstate = 1;
982                 alsa_new(&alsa, AST_STATE_RINGING);
983         } else
984                 ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
985         return RESULT_SUCCESS;
986 }
987
988 static char dial_usage[] =
989 "Usage: dial [extension[@context]]\n"
990 "       Dials a given extensison (";
991
992
993 static struct ast_cli_entry myclis[] = {
994         { { "answer", NULL }, console_answer, "Answer an incoming console call", answer_usage },
995         { { "hangup", NULL }, console_hangup, "Hangup a call on the console", hangup_usage },
996         { { "dial", NULL }, console_dial, "Dial an extension on the console", dial_usage },
997         { { "send", "text", NULL }, console_sendtext, "Send text to the remote device", sendtext_usage },
998         { { "autoanswer", NULL }, console_autoanswer, "Sets/displays autoanswer", autoanswer_usage, autoanswer_complete }
999 };
1000
1001 int load_module()
1002 {
1003         int res;
1004         int x;
1005         int flags;
1006         struct ast_config *cfg;
1007         struct ast_variable *v;
1008 #if 0
1009         res = pipe(cmd);
1010         res = pipe(sndcmd);
1011         
1012         if (res) {
1013                 ast_log(LOG_ERROR, "Unable to create pipe\n");
1014                 return -1;
1015         }
1016         flags = fcntl(cmd[0], F_GETFL);
1017         fcntl(cmd[0], F_SETFL, flags | O_NONBLOCK);
1018         flags = fcntl(cmd[1], F_GETFL);
1019         fcntl(cmd[1], F_SETFL, flags | O_NONBLOCK);
1020 #endif
1021 #if 0
1022         if (!full_duplex)
1023                 ast_log(LOG_WARNING, "XXX I don't work right with non-full duplex sound cards XXX\n");
1024 #endif
1025         res = ast_channel_register(type, tdesc, AST_FORMAT_SLINEAR, alsa_request);
1026         if (res < 0) {
1027                 ast_log(LOG_ERROR, "Unable to register channel class '%s'\n", type);
1028                 return -1;
1029         }
1030         for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
1031                 ast_cli_register(myclis + x);
1032         if ((cfg = ast_load(config))) {
1033                 v = ast_variable_browse(cfg, "general");
1034                 while(v) {
1035                         if (!strcasecmp(v->name, "autoanswer"))
1036                                 autoanswer = ast_true(v->value);
1037                         else if (!strcasecmp(v->name, "silencesuppression"))
1038                                 silencesuppression = ast_true(v->value);
1039                         else if (!strcasecmp(v->name, "silencethreshold"))
1040                                 silencethreshold = atoi(v->value);
1041                         else if (!strcasecmp(v->name, "context"))
1042                                 strncpy(context, v->value, sizeof(context)-1);
1043                         else if (!strcasecmp(v->name, "language"))
1044                                 strncpy(language, v->value, sizeof(language)-1);
1045                         else if (!strcasecmp(v->name, "extension"))
1046                                 strncpy(exten, v->value, sizeof(exten)-1);
1047                         else if (!strcasecmp(v->name, "input_device")) {
1048                                 strncpy(indevname, v->value, sizeof(indevname)-1);
1049                         } else if (!strcasecmp(v->name, "output_device"))
1050                                 strncpy(outdevname, v->value, sizeof(outdevname)-1);
1051                         v=v->next;
1052                 }
1053                 ast_destroy(cfg);
1054         }
1055         res = soundcard_init();
1056         if (res < 0) {
1057                 close(cmd[1]);
1058                 close(cmd[0]);
1059                 if (option_verbose > 1) {
1060                         ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
1061                         ast_verbose(VERBOSE_PREFIX_2 "Turn off ALSA support by adding 'noload=chan_alsa.so' in /etc/asterisk/modules.conf\n");
1062                 }
1063                 return 0;
1064         }
1065         return 0;
1066 }
1067
1068
1069
1070 int unload_module()
1071 {
1072         int x;
1073         for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
1074                 ast_cli_unregister(myclis + x);
1075         if (cmd[0] > 0) {
1076                 close(cmd[0]);
1077                 close(cmd[1]);
1078         }
1079         if (sndcmd[0] > 0) {
1080                 close(sndcmd[0]);
1081                 close(sndcmd[1]);
1082         }
1083         if (alsa.owner)
1084                 ast_softhangup(alsa.owner, AST_SOFTHANGUP_APPUNLOAD);
1085         if (alsa.owner)
1086                 return -1;
1087         if (alsa.capture_buf) {
1088                 free (alsa.capture_buf);
1089                 alsa.capture_buf=0;
1090         }
1091         return 0;
1092 }
1093
1094 char *description()
1095 {
1096         return desc;
1097 }
1098
1099 int usecount()
1100 {
1101         int res;
1102         ast_mutex_lock(&usecnt_lock);
1103         res = usecnt;
1104         ast_mutex_unlock(&usecnt_lock);
1105         return res;
1106 }
1107
1108 char *key()
1109 {
1110         return ASTERISK_GPL_KEY;
1111 }