mer feb 12 14:56:57 CET 2003
[asterisk/asterisk.git] / channel.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <sys/time.h>
19 #include <signal.h>
20 #include <errno.h>
21 #include <unistd.h>
22 #include <math.h>                       /* For PI */
23 #include <asterisk/pbx.h>
24 #include <asterisk/frame.h>
25 #include <asterisk/sched.h>
26 #include <asterisk/options.h>
27 #include <asterisk/channel.h>
28 #include <asterisk/channel_pvt.h>
29 #include <asterisk/logger.h>
30 #include <asterisk/file.h>
31 #include <asterisk/translate.h>
32 #include <asterisk/manager.h>
33 #include <asterisk/chanvars.h>
34 #include <asterisk/linkedlists.h>
35 #include <asterisk/indications.h>
36
37
38 static int shutting_down = 0;
39
40 /* XXX Lock appropriately in more functions XXX */
41
42 #ifdef DEBUG_MUTEX
43 /* Convenient mutex debugging functions */
44 #define PTHREAD_MUTEX_LOCK(a) __PTHREAD_MUTEX_LOCK(__FUNCTION__, a)
45 #define PTHREAD_MUTEX_UNLOCK(a) __PTHREAD_MUTEX_UNLOCK(__FUNCTION__, a)
46
47 static int __PTHREAD_MUTEX_LOCK(char *f, pthread_mutex_t *a) {
48         ast_log(LOG_DEBUG, "Locking %p (%s)\n", a, f); 
49         return ast_pthread_mutex_lock(a);
50 }
51
52 static int __PTHREAD_MUTEX_UNLOCK(char *f, pthread_mutex_t *a) {
53         ast_log(LOG_DEBUG, "Unlocking %p (%s)\n", a, f); 
54         return ast_pthread_mutex_unlock(a);
55 }
56 #else
57 #define PTHREAD_MUTEX_LOCK(a) ast_pthread_mutex_lock(a)
58 #define PTHREAD_MUTEX_UNLOCK(a) ast_pthread_mutex_unlock(a)
59 #endif
60
61 struct chanlist {
62         char type[80];
63         char description[80];
64         int capabilities;
65         struct ast_channel * (*requester)(char *type, int format, void *data);
66         struct chanlist *next;
67 } *backends = NULL;
68 struct ast_channel *channels = NULL;
69
70 /* Protect the channel list (highly unlikely that two things would change
71    it at the same time, but still! */
72    
73 static pthread_mutex_t chlock = AST_MUTEX_INITIALIZER;
74
75 int ast_check_hangup(struct ast_channel *chan)
76 {
77 time_t  myt;
78
79           /* if soft hangup flag, return true */
80         if (chan->_softhangup) return 1;
81           /* if no private structure, return true */
82         if (!chan->pvt->pvt) return 1;
83           /* if no hangup scheduled, just return here */
84         if (!chan->whentohangup) return 0;
85         time(&myt); /* get current time */
86           /* return, if not yet */
87         if (chan->whentohangup > myt) return 0;
88         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
89         return 1;
90 }
91
92 void ast_begin_shutdown(int hangup)
93 {
94         struct ast_channel *c;
95         shutting_down = 1;
96         if (hangup) {
97                 PTHREAD_MUTEX_LOCK(&chlock);
98                 c = channels;
99                 while(c) {
100                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
101                         c = c->next;
102                 }
103                 PTHREAD_MUTEX_UNLOCK(&chlock);
104         }
105 }
106
107 int ast_active_channels(void)
108 {
109         struct ast_channel *c;
110         int cnt = 0;
111         PTHREAD_MUTEX_LOCK(&chlock);
112         c = channels;
113         while(c) {
114                 cnt++;
115                 c = c->next;
116         }
117         PTHREAD_MUTEX_UNLOCK(&chlock);
118         return cnt;
119 }
120
121 void ast_cancel_shutdown(void)
122 {
123         shutting_down = 0;
124 }
125
126 int ast_shutting_down(void)
127 {
128         return shutting_down;
129 }
130
131 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
132 {
133 time_t  myt;
134
135         time(&myt);
136         if (offset)
137           chan->whentohangup = myt + offset;
138         else
139           chan->whentohangup = 0;
140         return;
141 }
142
143 int ast_channel_register(char *type, char *description, int capabilities,
144                 struct ast_channel *(*requester)(char *type, int format, void *data))
145 {
146         struct chanlist *chan, *last=NULL;
147         if (PTHREAD_MUTEX_LOCK(&chlock)) {
148                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
149                 return -1;
150         }
151         chan = backends;
152         while(chan) {
153                 if (!strcasecmp(type, chan->type)) {
154                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
155                         PTHREAD_MUTEX_UNLOCK(&chlock);
156                         return -1;
157                 }
158                 last = chan;
159                 chan = chan->next;
160         }
161         chan = malloc(sizeof(struct chanlist));
162         if (!chan) {
163                 ast_log(LOG_WARNING, "Out of memory\n");
164                 PTHREAD_MUTEX_UNLOCK(&chlock);
165                 return -1;
166         }
167         strncpy(chan->type, type, sizeof(chan->type)-1);
168         strncpy(chan->description, description, sizeof(chan->description)-1);
169         chan->capabilities = capabilities;
170         chan->requester = requester;
171         chan->next = NULL;
172         if (last)
173                 last->next = chan;
174         else
175                 backends = chan;
176         if (option_debug)
177                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
178         else if (option_verbose > 1)
179                 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
180         PTHREAD_MUTEX_UNLOCK(&chlock);
181         return 0;
182 }
183
184 char *ast_state2str(int state)
185 {
186         switch(state) {
187         case AST_STATE_DOWN:
188                 return "Down";
189         case AST_STATE_RESERVED:
190                 return "Rsrvd";
191         case AST_STATE_OFFHOOK:
192                 return "OffHook";
193         case AST_STATE_DIALING:
194                 return "Dialing";
195         case AST_STATE_RING:
196                 return "Ring";
197         case AST_STATE_RINGING:
198                 return "Ringing";
199         case AST_STATE_UP:
200                 return "Up";
201         case AST_STATE_BUSY:
202                 return "Busy";
203         default:
204                 return "Unknown";
205         }
206 }
207
208
209 int ast_best_codec(int fmts)
210 {
211         /* This just our opinion, expressed in code.  We are asked to choose
212            the best codec to use, given no information */
213         int x;
214         static int prefs[] = 
215         {
216                 /* Okay, ulaw is used by all telephony equipment, so start with it */
217                 AST_FORMAT_ULAW,
218                 /* Unless of course, you're a silly European, so then prefer ALAW */
219                 AST_FORMAT_ALAW,
220                 /* Okay, well, signed linear is easy to translate into other stuff */
221                 AST_FORMAT_SLINEAR,
222                 /* ADPCM has great sound quality and is still pretty easy to translate */
223                 AST_FORMAT_ADPCM,
224                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
225                    translate and sounds pretty good */
226                 AST_FORMAT_GSM,
227                 /* Speex is free, but computationally more expensive than GSM */
228                 AST_FORMAT_SPEEX,
229                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
230                    to use it */
231                 AST_FORMAT_LPC10,
232                 /* G.729a is faster than 723 and slightly less expensive */
233                 AST_FORMAT_G729A,
234                 /* Down to G.723.1 which is proprietary but at least designed for voice */
235                 AST_FORMAT_G723_1,
236                 /* Last and least, MP3 which was of course never designed for real-time voice */
237                 AST_FORMAT_MP3,
238         };
239         
240         
241         for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
242                 if (fmts & prefs[x])
243                         return prefs[x];
244         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
245         return 0;
246 }
247
248 struct ast_channel *ast_channel_alloc(int needqueue)
249 {
250         struct ast_channel *tmp;
251         struct ast_channel_pvt *pvt;
252         int x;
253         int flags;
254         struct varshead *headp;        
255                 
256         
257         /* If shutting down, don't allocate any new channels */
258         if (shutting_down)
259                 return NULL;
260         PTHREAD_MUTEX_LOCK(&chlock);
261         tmp = malloc(sizeof(struct ast_channel));
262         memset(tmp, 0, sizeof(struct ast_channel));
263         if (tmp) {
264                 pvt = malloc(sizeof(struct ast_channel_pvt));
265                 if (pvt) {
266                         memset(pvt, 0, sizeof(struct ast_channel_pvt));
267                         tmp->sched = sched_context_create();
268                         if (tmp->sched) {
269                                 for (x=0;x<AST_MAX_FDS - 1;x++)
270                                         tmp->fds[x] = -1;
271                                 if (needqueue &&  
272                                         pipe(pvt->alertpipe)) {
273                                         ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
274                                         free(pvt);
275                                         free(tmp);
276                                         tmp = NULL;
277                                         pvt = NULL;
278                                 } else {
279                                         /* Make sure we've got it done right if they don't */
280                                         if (needqueue) {
281                                                 flags = fcntl(pvt->alertpipe[0], F_GETFL);
282                                                 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
283                                                 flags = fcntl(pvt->alertpipe[1], F_GETFL);
284                                                 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
285                                         } else
286                                                 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
287                                         /* Always watch the alertpipe */
288                                         tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
289                                         strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
290                                         tmp->pvt = pvt;
291                                         /* Initial state */
292                                         tmp->_state = AST_STATE_DOWN;
293                                         tmp->stack = -1;
294                                         tmp->streamid = -1;
295                                         tmp->appl = NULL;
296                                         tmp->data = NULL;
297                                         tmp->fin = 0;
298                                         tmp->fout = 0;
299                                         headp=&tmp->varshead;
300                                         ast_pthread_mutex_init(&tmp->lock);
301                                         AST_LIST_HEAD_INIT(headp);
302                                         tmp->vars=ast_var_assign("tempvar","tempval");
303                                         AST_LIST_INSERT_HEAD(headp,tmp->vars,entries);
304                                         strncpy(tmp->context, "default", sizeof(tmp->context)-1);
305                                         strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
306                                         strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
307                                         tmp->priority=1;
308                                         tmp->amaflags = ast_default_amaflags;
309                                         strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
310                                         tmp->next = channels;
311                                         channels= tmp;
312                                 }
313                         } else {
314                                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
315                                 free(tmp);
316                                 tmp = NULL;
317                         }
318                 } else {
319                         ast_log(LOG_WARNING, "Out of memory\n");
320                         free(tmp);
321                         tmp = NULL;
322                 }
323         } else 
324                 ast_log(LOG_WARNING, "Out of memory\n");
325         PTHREAD_MUTEX_UNLOCK(&chlock);
326         return tmp;
327 }
328
329 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int lock)
330 {
331         struct ast_frame *f;
332         struct ast_frame *prev, *cur;
333         int blah = 1;
334         int qlen = 0;
335         /* Build us a copy and free the original one */
336         f = ast_frdup(fin);
337         if (!f) {
338                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
339                 return -1;
340         }
341         if (lock)
342                 ast_pthread_mutex_lock(&chan->lock);
343         prev = NULL;
344         cur = chan->pvt->readq;
345         while(cur) {
346                 prev = cur;
347                 cur = cur->next;
348                 qlen++;
349         }
350         if (qlen  > 128) {
351                 if (fin->frametype != AST_FRAME_VOICE) {
352                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
353                         CRASH;
354                 } else {
355                         ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
356                         ast_frfree(fin);
357                         if (lock)
358                                 ast_pthread_mutex_unlock(&chan->lock);
359                         return 0;
360                 }
361         }
362         if (prev)
363                 prev->next = f;
364         else
365                 chan->pvt->readq = f;
366         if (chan->pvt->alertpipe[1] > -1) {
367                 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
368                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
369                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
370         }
371         if (lock)
372                 ast_pthread_mutex_unlock(&chan->lock);
373         return 0;
374 }
375
376 int ast_queue_hangup(struct ast_channel *chan, int lock)
377 {
378         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
379         chan->_softhangup |= AST_SOFTHANGUP_DEV;
380         return ast_queue_frame(chan, &f, lock);
381 }
382
383 int ast_queue_control(struct ast_channel *chan, int control, int lock)
384 {
385         struct ast_frame f = { AST_FRAME_CONTROL, };
386         f.subclass = control;
387         return ast_queue_frame(chan, &f, lock);
388 }
389
390 int ast_channel_defer_dtmf(struct ast_channel *chan)
391 {
392         int pre = 0;
393         if (chan) {
394                 pre = chan->deferdtmf;
395                 chan->deferdtmf = 1;
396         }
397         return pre;
398 }
399
400 void ast_channel_undefer_dtmf(struct ast_channel *chan)
401 {
402         if (chan)
403                 chan->deferdtmf = 0;
404 }
405
406 struct ast_channel *ast_channel_walk(struct ast_channel *prev)
407 {
408         struct ast_channel *l, *ret=NULL;
409         PTHREAD_MUTEX_LOCK(&chlock);
410         l = channels;
411         if (!prev) {
412                 PTHREAD_MUTEX_UNLOCK(&chlock);
413                 return l;
414         }
415         while(l) {
416                 if (l == prev)
417                         ret = l->next;
418                 l = l->next;
419         }
420         PTHREAD_MUTEX_UNLOCK(&chlock);
421         return ret;
422         
423 }
424
425 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
426                                                                 int (*cond)(void*), void *data )
427 {
428         struct ast_frame *f;
429
430         while(ms > 0) {
431                 if( cond && ((*cond)(data) == 0 ) )
432                         return 0;
433                 ms = ast_waitfor(chan, ms);
434                 if (ms <0)
435                         return -1;
436                 if (ms > 0) {
437                         f = ast_read(chan);
438                         if (!f)
439                                 return -1;
440                         ast_frfree(f);
441                 }
442         }
443         return 0;
444 }
445
446 int ast_safe_sleep(struct ast_channel *chan, int ms)
447 {
448         struct ast_frame *f;
449         while(ms > 0) {
450                 ms = ast_waitfor(chan, ms);
451                 if (ms <0)
452                         return -1;
453                 if (ms > 0) {
454                         f = ast_read(chan);
455                         if (!f)
456                                 return -1;
457                         ast_frfree(f);
458                 }
459         }
460         return 0;
461 }
462
463 void ast_channel_free(struct ast_channel *chan)
464 {
465         struct ast_channel *last=NULL, *cur;
466         int fd;
467         struct ast_var_t *vardata;
468         struct ast_frame *f, *fp;
469         struct varshead *headp;
470         
471         headp=&chan->varshead;
472         
473         PTHREAD_MUTEX_LOCK(&chlock);
474         cur = channels;
475         while(cur) {
476                 if (cur == chan) {
477                         if (last)
478                                 last->next = cur->next;
479                         else
480                                 channels = cur->next;
481                         break;
482                 }
483                 last = cur;
484                 cur = cur->next;
485         }
486         if (!cur)
487                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
488         if (chan->pvt->pvt)
489                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
490         /* Free translatosr */
491         if (chan->pvt->readtrans)
492                 ast_translator_free_path(chan->pvt->readtrans);
493         if (chan->pvt->writetrans)
494                 ast_translator_free_path(chan->pvt->writetrans);
495         if (chan->pbx) 
496                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
497         if (chan->dnid)
498                 free(chan->dnid);
499         if (chan->callerid)
500                 free(chan->callerid);   
501         if (chan->ani)
502                 free(chan->ani);
503         if (chan->rdnis)
504                 free(chan->rdnis);
505         pthread_mutex_destroy(&chan->lock);
506         /* Close pipes if appropriate */
507         if ((fd = chan->pvt->alertpipe[0]) > -1)
508                 close(fd);
509         if ((fd = chan->pvt->alertpipe[1]) > -1)
510                 close(fd);
511         f = chan->pvt->readq;
512         chan->pvt->readq = NULL;
513         while(f) {
514                 fp = f;
515                 f = f->next;
516                 ast_frfree(fp);
517         }
518         
519         /* loop over the variables list, freeing all data and deleting list items */
520         /* no need to lock the list, as the channel is already locked */
521         
522         while (!AST_LIST_EMPTY(headp)) {           /* List Deletion. */
523                     vardata = AST_LIST_FIRST(headp);
524                     AST_LIST_REMOVE_HEAD(headp, entries);
525 //                  printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata));
526                     ast_var_delete(vardata);
527         }
528                                                          
529
530         free(chan->pvt);
531         chan->pvt = NULL;
532         free(chan);
533         PTHREAD_MUTEX_UNLOCK(&chlock);
534 }
535
536 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
537 {
538         int res = 0;
539         struct ast_frame f = { AST_FRAME_NULL };
540         if (option_debug)
541                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
542         /* Inform channel driver that we need to be hung up, if it cares */
543         chan->_softhangup |= cause;
544         ast_queue_frame(chan, &f, 0);
545         /* Interrupt any select call or such */
546         if (chan->blocking)
547                 pthread_kill(chan->blocker, SIGURG);
548         return res;
549 }
550
551 int ast_softhangup(struct ast_channel *chan, int cause)
552 {
553         int res;
554         ast_pthread_mutex_lock(&chan->lock);
555         res = ast_softhangup_nolock(chan, cause);
556         ast_pthread_mutex_unlock(&chan->lock);
557         return res;
558 }
559
560 static int ast_do_masquerade(struct ast_channel *original);
561
562 static void free_translation(struct ast_channel *clone)
563 {
564         if (clone->pvt->writetrans)
565                 ast_translator_free_path(clone->pvt->writetrans);
566         if (clone->pvt->readtrans)
567                 ast_translator_free_path(clone->pvt->readtrans);
568         clone->pvt->writetrans = NULL;
569         clone->pvt->readtrans = NULL;
570         clone->pvt->rawwriteformat = clone->nativeformats;
571         clone->pvt->rawreadformat = clone->nativeformats;
572 }
573
574 int ast_hangup(struct ast_channel *chan)
575 {
576         int res = 0;
577         /* Don't actually hang up a channel that will masquerade as someone else, or
578            if someone is going to masquerade as us */
579         ast_pthread_mutex_lock(&chan->lock);
580         if (chan->masq) {
581                 if (ast_do_masquerade(chan)) 
582                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
583         }
584
585         if (chan->masq) {
586                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
587                 ast_pthread_mutex_unlock(&chan->lock);
588                 return 0;
589         }
590         /* If this channel is one which will be masqueraded into something, 
591            mark it as a zombie already, so we know to free it later */
592         if (chan->masqr) {
593                 ast_pthread_mutex_unlock(&chan->lock);
594                 chan->zombie=1;
595                 return 0;
596         }
597         free_translation(chan);
598         if (chan->stream)
599                 ast_stopstream(chan);
600         if (chan->sched)
601                 sched_context_destroy(chan->sched);
602         /* Clear any tone stuff remaining */
603         if (chan->generatordata)
604                 chan->generator->release(chan, chan->generatordata);
605         chan->generatordata = NULL;
606         chan->generator = NULL;
607         if (chan->cdr) {
608                 /* End the CDR if it hasn't already */
609                 ast_cdr_end(chan->cdr);
610                 /* Post and Free the CDR */
611                 ast_cdr_post(chan->cdr);
612                 ast_cdr_free(chan->cdr);
613         }
614         if (chan->blocking) {
615                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
616                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
617                                         pthread_self(), chan->name, chan->blocker, chan->blockproc);
618                 CRASH;
619         }
620         if (!chan->zombie) {
621                 if (option_debug)
622                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
623                 if (chan->pvt->hangup)
624                         res = chan->pvt->hangup(chan);
625         } else
626                 if (option_debug)
627                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
628                         
629         ast_pthread_mutex_unlock(&chan->lock);
630         manager_event(EVENT_FLAG_CALL, "Hangup", 
631                         "Channel: %s\r\n",
632                         chan->name);
633         ast_channel_free(chan);
634         return res;
635 }
636
637 void ast_channel_unregister(char *type)
638 {
639         struct chanlist *chan, *last=NULL;
640         if (option_debug)
641                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
642         if (PTHREAD_MUTEX_LOCK(&chlock)) {
643                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
644                 return;
645         }
646         chan = backends;
647         while(chan) {
648                 if (!strcasecmp(chan->type, type)) {
649                         if (last)
650                                 last->next = chan->next;
651                         else
652                                 backends = backends->next;
653                         free(chan);
654                         PTHREAD_MUTEX_UNLOCK(&chlock);
655                         return;
656                 }
657                 last = chan;
658                 chan = chan->next;
659         }
660         PTHREAD_MUTEX_UNLOCK(&chlock);
661 }
662
663 int ast_answer(struct ast_channel *chan)
664 {
665         int res = 0;
666         /* Stop if we're a zombie or need a soft hangup */
667         if (chan->zombie || ast_check_hangup(chan)) 
668                 return -1;
669         switch(chan->_state) {
670         case AST_STATE_RINGING:
671         case AST_STATE_RING:
672                 if (chan->pvt->answer)
673                         res = chan->pvt->answer(chan);
674                 ast_setstate(chan, AST_STATE_UP);
675                 if (chan->cdr)
676                         ast_cdr_answer(chan->cdr);
677                 return res;
678                 break;
679         case AST_STATE_UP:
680                 if (chan->cdr)
681                         ast_cdr_answer(chan->cdr);
682                 break;
683         }
684         return 0;
685 }
686
687 void ast_deactivate_generator(struct ast_channel *chan)
688 {
689         if (chan->generatordata) {
690                 chan->generator->release(chan, chan->generatordata);
691                 chan->generatordata = NULL;
692                 chan->generator = NULL;
693                 chan->writeinterrupt = 0;
694         }
695 }
696
697 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
698 {
699         if (chan->generatordata) {
700                 chan->generator->release(chan, chan->generatordata);
701                 chan->generatordata = NULL;
702         }
703         if ((chan->generatordata = gen->alloc(chan, params))) {
704                 chan->generator = gen;
705         } else {
706                 return -1;
707         }
708         return 0;
709 }
710
711 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
712 {
713         /* Wait for x amount of time on a file descriptor to have input.  */
714         struct timeval tv;
715         fd_set rfds, efds;
716         int res;
717         int x, max=-1;
718         int winner = -1;
719         
720         tv.tv_sec = *ms / 1000;
721         tv.tv_usec = (*ms % 1000) * 1000;
722         FD_ZERO(&rfds);
723         FD_ZERO(&efds);
724         for (x=0;x<n;x++) {
725                 if (fds[x] > -1) {
726                         FD_SET(fds[x], &rfds);
727                         FD_SET(fds[x], &efds);
728                         if (fds[x] > max)
729                                 max = fds[x];
730                 }
731         }
732         if (*ms >= 0) 
733                 res = select(max + 1, &rfds, NULL, &efds, &tv);
734         else
735                 res = select(max + 1, &rfds, NULL, &efds, NULL);
736
737         if (res < 0) {
738                 /* Simulate a timeout if we were interrupted */
739                 if (errno != EINTR)
740                         *ms = -1;
741                 else
742                         *ms = 0;
743                 return -1;
744         }
745
746         for (x=0;x<n;x++) {
747                 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
748                         if (exception)
749                                 *exception = FD_ISSET(fds[x], &efds);
750                         winner = fds[x];
751                 }
752         }
753         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
754         return winner;
755 }
756
757 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
758         int *exception, int *outfd, int *ms)
759 {
760         /* Wait for x amount of time on a file descriptor to have input.  */
761         struct timeval tv;
762         fd_set rfds, efds;
763         int res;
764         int x, y, max=-1;
765         struct ast_channel *winner = NULL;
766         if (outfd)
767                 *outfd = -1;
768         if (exception)
769                 *exception = 0;
770         
771         /* Perform any pending masquerades */
772         for (x=0;x<n;x++) {
773                 if (c[x]->masq) {
774                         if (ast_do_masquerade(c[x])) {
775                                 ast_log(LOG_WARNING, "Masquerade failed\n");
776                                 *ms = -1;
777                                 return NULL;
778                         }
779                 }
780         }
781         
782         tv.tv_sec = *ms / 1000;
783         tv.tv_usec = (*ms % 1000) * 1000;
784         FD_ZERO(&rfds);
785         FD_ZERO(&efds);
786
787         for (x=0;x<n;x++) {
788                 for (y=0;y<AST_MAX_FDS;y++) {
789                         if (c[x]->fds[y] > -1) {
790                                 FD_SET(c[x]->fds[y], &rfds);
791                                 FD_SET(c[x]->fds[y], &efds);
792                                 if (c[x]->fds[y] > max)
793                                         max = c[x]->fds[y];
794                         }
795                 }
796                 CHECK_BLOCKING(c[x]);
797         }
798         for (x=0;x<nfds; x++) {
799                 FD_SET(fds[x], &rfds);
800                 FD_SET(fds[x], &efds);
801                 if (fds[x] > max)
802                         max = fds[x];
803         }
804         if (*ms >= 0) 
805                 res = select(max + 1, &rfds, NULL, &efds, &tv);
806         else
807                 res = select(max + 1, &rfds, NULL, &efds, NULL);
808
809         if (res < 0) {
810                 for (x=0;x<n;x++) 
811                         c[x]->blocking = 0;
812                 /* Simulate a timeout if we were interrupted */
813                 if (errno != EINTR)
814                         *ms = -1;
815                 else {
816                         /* Just an interrupt */
817 #if 0
818                         *ms = 0;
819 #endif                  
820                 }
821                 return NULL;
822         }
823
824         for (x=0;x<n;x++) {
825                 c[x]->blocking = 0;
826                 for (y=0;y<AST_MAX_FDS;y++) {
827                         if (c[x]->fds[y] > -1) {
828                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
829                                         /* Set exception flag if appropriate */
830                                         if (FD_ISSET(c[x]->fds[y], &efds))
831                                                 c[x]->exception = 1;
832                                         c[x]->fdno = y;
833                                         winner = c[x];
834                                 }
835                         }
836                 }
837         }
838         for (x=0;x<nfds;x++) {
839                 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
840                         if (outfd)
841                                 *outfd = fds[x];
842                         if (FD_ISSET(fds[x], &efds) && exception)
843                                 *exception = 1;
844                         winner = NULL;
845                 }
846         }
847         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
848         return winner;
849 }
850
851 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
852 {
853         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
854 }
855
856 int ast_waitfor(struct ast_channel *c, int ms)
857 {
858         struct ast_channel *chan;
859         int oldms = ms;
860         chan = ast_waitfor_n(&c, 1, &ms);
861         if (ms < 0) {
862                 if (oldms < 0)
863                         return 0;
864                 else
865                         return -1;
866         }
867         return ms;
868 }
869
870 char ast_waitfordigit(struct ast_channel *c, int ms)
871 {
872         struct ast_frame *f;
873         char result = 0;
874         /* Stop if we're a zombie or need a soft hangup */
875         if (c->zombie || ast_check_hangup(c)) 
876                 return -1;
877         /* Wait for a digit, no more than ms milliseconds total. */
878         while(ms && !result) {
879                 ms = ast_waitfor(c, ms);
880                 if (ms < 0) /* Error */
881                         result = -1; 
882                 else if (ms > 0) {
883                         /* Read something */
884                         f = ast_read(c);
885                         if (f) {
886                                 if (f->frametype == AST_FRAME_DTMF) 
887                                         result = f->subclass;
888                                 ast_frfree(f);
889                         } else
890                                 result = -1;
891                 }
892         }
893         return result;
894 }
895
896 struct ast_frame *ast_read(struct ast_channel *chan)
897 {
898         struct ast_frame *f = NULL;
899         int blah;
900         static struct ast_frame null_frame = 
901         {
902                 AST_FRAME_NULL,
903         };
904         
905         ast_pthread_mutex_lock(&chan->lock);
906         if (chan->masq) {
907                 if (ast_do_masquerade(chan)) {
908                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
909                         f = NULL;
910                 } else
911                         f =  &null_frame;
912                 pthread_mutex_unlock(&chan->lock);
913                 return f;
914         }
915
916         /* Stop if we're a zombie or need a soft hangup */
917         if (chan->zombie || ast_check_hangup(chan)) {
918                 if (chan->generator)
919                         ast_deactivate_generator(chan);
920                 pthread_mutex_unlock(&chan->lock);
921                 return NULL;
922         }
923
924         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
925                 /* We have DTMF that has been deferred.  Return it now */
926                 chan->dtmff.frametype = AST_FRAME_DTMF;
927                 chan->dtmff.subclass = chan->dtmfq[0];
928                 /* Drop first digit */
929                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
930                 pthread_mutex_unlock(&chan->lock);
931                 return &chan->dtmff;
932         }
933         
934         /* Read and ignore anything on the alertpipe, but read only
935            one sizeof(blah) per frame that we send from it */
936         if (chan->pvt->alertpipe[0] > -1) {
937                 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
938         }
939
940         /* Check for pending read queue */
941         if (chan->pvt->readq) {
942                 f = chan->pvt->readq;
943                 chan->pvt->readq = f->next;
944                 /* Interpret hangup and return NULL */
945                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))
946                         f = NULL;
947         } else {
948                 chan->blocker = pthread_self();
949                 if (chan->exception) {
950                         if (chan->pvt->exception) 
951                                 f = chan->pvt->exception(chan);
952                         else {
953                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
954                                 f = &null_frame;
955                         }
956                         /* Clear the exception flag */
957                         chan->exception = 0;
958                 } else
959                 if (chan->pvt->read)
960                         f = chan->pvt->read(chan);
961                 else
962                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
963         }
964
965
966         if (f && (f->frametype == AST_FRAME_VOICE)) {
967                 if (!(f->subclass & chan->nativeformats)) {
968                         /* This frame can't be from the current native formats -- drop it on the
969                            floor */
970                         ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s since our native format has changed\n", chan->name);
971                         f = &null_frame;
972                 } else if (chan->pvt->readtrans) {
973                         f = ast_translate(chan->pvt->readtrans, f, 1);
974                         if (!f)
975                                 f = &null_frame;
976                 }
977         }
978
979         /* Make sure we always return NULL in the future */
980         if (!f) {
981                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
982                 if (chan->generator)
983                         ast_deactivate_generator(chan);
984                 /* End the CDR if appropriate */
985                 if (chan->cdr)
986                         ast_cdr_end(chan->cdr);
987         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
988                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
989                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
990                 else
991                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
992                 f = &null_frame;
993         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
994                 /* Answer the CDR */
995                 ast_setstate(chan, AST_STATE_UP);
996                 ast_cdr_answer(chan->cdr);
997         }
998         pthread_mutex_unlock(&chan->lock);
999
1000         /* Run any generator sitting on the line */
1001         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1002                 /* Mask generator data temporarily */
1003                 void *tmp;
1004                 int res;
1005                 tmp = chan->generatordata;
1006                 chan->generatordata = NULL;
1007                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1008                 chan->generatordata = tmp;
1009                 if (res) {
1010                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1011                         ast_deactivate_generator(chan);
1012                 }
1013         }
1014         chan->fin++;
1015         return f;
1016 }
1017
1018 int ast_indicate(struct ast_channel *chan, int condition)
1019 {
1020         int res = -1;
1021         /* Stop if we're a zombie or need a soft hangup */
1022         if (chan->zombie || ast_check_hangup(chan)) 
1023                 return -1;
1024         if (chan->pvt->indicate)
1025                 res = chan->pvt->indicate(chan, condition);
1026         if (!chan->pvt->indicate || res) {
1027                 /*
1028                  * Device does not support (that) indication, lets fake
1029                  * it by doing our own tone generation. (PM2002)
1030                  */
1031                 if (condition >= 0) {
1032                         const struct tone_zone_sound *ts = NULL;
1033                         switch (condition) {
1034                          case AST_CONTROL_RINGING:
1035                                 ts = ast_get_indication_tone(chan->zone, "ring");
1036                                 break;
1037                          case AST_CONTROL_BUSY:
1038                                 ts = ast_get_indication_tone(chan->zone, "busy");
1039                                 break;
1040                          case AST_CONTROL_CONGESTION:
1041                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1042                                 break;
1043                         }
1044                         if (ts && ts->data[0]) {
1045                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1046                                 ast_playtones_start(chan,0,ts->data);
1047                         }
1048                         else  {
1049                                 /* not handled */
1050                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1051                                 return -1;
1052                         }
1053                 }
1054                 else ast_playtones_stop(chan);
1055         }
1056         return 0;
1057 }
1058
1059 int ast_recvchar(struct ast_channel *chan, int timeout)
1060 {
1061         int res,ourto,c;
1062         struct ast_frame *f;
1063         
1064         ourto = timeout;
1065         for(;;)
1066            {
1067                 if (ast_check_hangup(chan)) return -1;
1068                 res = ast_waitfor(chan,ourto);
1069                 if (res <= 0) /* if timeout */
1070                    {
1071                         return 0;
1072                    }
1073                 ourto = res;
1074                 f = ast_read(chan);
1075                 if (f == NULL) return -1; /* if hangup */
1076                 if ((f->frametype == AST_FRAME_CONTROL) &&
1077                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1078                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1079                    {
1080                         c = *((char *)f->data);  /* get the data */
1081                         ast_frfree(f);
1082                         return(c);
1083                    }
1084                 ast_frfree(f);
1085         }
1086 }
1087
1088 int ast_sendtext(struct ast_channel *chan, char *text)
1089 {
1090         int res = 0;
1091         /* Stop if we're a zombie or need a soft hangup */
1092         if (chan->zombie || ast_check_hangup(chan)) 
1093                 return -1;
1094         CHECK_BLOCKING(chan);
1095         if (chan->pvt->send_text)
1096                 res = chan->pvt->send_text(chan, text);
1097         chan->blocking = 0;
1098         return res;
1099 }
1100
1101 static int do_senddigit(struct ast_channel *chan, char digit)
1102 {
1103         int res = -1;
1104
1105         if (chan->pvt->send_digit)
1106                 res = chan->pvt->send_digit(chan, digit);
1107         if (!chan->pvt->send_digit || res) {
1108                 /*
1109                  * Device does not support DTMF tones, lets fake
1110                  * it by doing our own generation. (PM2002)
1111                  */
1112                 static const char* dtmf_tones[] = {
1113                         "!941+1336/50,!0/50",   /* 0 */
1114                         "!697+1209/50,!0/50",   /* 1 */
1115                         "!697+1336/50,!0/50",   /* 2 */
1116                         "!697+1477/50,!0/50",   /* 3 */
1117                         "!770+1209/50,!0/50",   /* 4 */
1118                         "!770+1336/50,!0/50",   /* 5 */
1119                         "!770+1477/50,!0/50",   /* 6 */
1120                         "!852+1209/50,!0/50",   /* 7 */
1121                         "!852+1336/50,!0/50",   /* 8 */
1122                         "!852+1477/50,!0/50",   /* 9 */
1123                         "!697+1633/50,!0/50",   /* A */
1124                         "!770+1633/50,!0/50",   /* B */
1125                         "!852+1633/50,!0/50",   /* C */
1126                         "!941+1633/50,!0/50",   /* D */
1127                         "!941+1209/50,!0/50",   /* * */
1128                         "!941+1477/50,!0/50" }; /* # */
1129                 if (digit >= '0' && digit <='9')
1130                         ast_playtones_start(chan,0,dtmf_tones[digit-'0']);
1131                 else if (digit >= 'A' && digit <= 'D')
1132                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10]);
1133                 else if (digit == '*')
1134                         ast_playtones_start(chan,0,dtmf_tones[14]);
1135                 else if (digit == '#')
1136                         ast_playtones_start(chan,0,dtmf_tones[15]);
1137                 else {
1138                         /* not handled */
1139                         ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1140                         return -1;
1141                 }
1142         }
1143         return 0;
1144 }
1145
1146 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1147 {
1148         int res = -1;
1149         struct ast_frame *f = NULL;
1150         /* Stop if we're a zombie or need a soft hangup */
1151         if (chan->zombie || ast_check_hangup(chan)) 
1152                 return -1;
1153         /* Handle any pending masquerades */
1154         if (chan->masq) {
1155                 if (ast_do_masquerade(chan)) {
1156                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1157                         return -1;
1158                 }
1159         }
1160         if (chan->masqr)
1161                 return 0;
1162         if (chan->generatordata) {
1163                 if (chan->writeinterrupt)
1164                         ast_deactivate_generator(chan);
1165                 else
1166                         return 0;
1167         }
1168         CHECK_BLOCKING(chan);
1169         switch(fr->frametype) {
1170         case AST_FRAME_CONTROL:
1171                 /* XXX Interpret control frames XXX */
1172                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1173                 break;
1174         case AST_FRAME_DTMF:
1175                 res = do_senddigit(chan,fr->subclass);
1176                 break;
1177         case AST_FRAME_TEXT:
1178                 if (chan->pvt->send_text)
1179                         res = chan->pvt->send_text(chan, (char *) fr->data);
1180                 break;
1181         default:
1182                 if (chan->pvt->write) {
1183                         if (chan->pvt->writetrans) {
1184                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1185                         } else
1186                                 f = fr;
1187                         if (f)  
1188                                 res = chan->pvt->write(chan, f);
1189                         else
1190                                 res = 0;
1191                 }
1192         }
1193         if (f && (f != fr))
1194                 ast_frfree(f);
1195         chan->blocking = 0;
1196         /* Consider a write failure to force a soft hangup */
1197         if (res < 0)
1198                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1199         else
1200                 chan->fout++;
1201         return res;
1202 }
1203
1204 int ast_set_write_format(struct ast_channel *chan, int fmts)
1205 {
1206         int fmt;
1207         int native;
1208         int res;
1209         
1210         native = chan->nativeformats;
1211         fmt = fmts;
1212         
1213         res = ast_translator_best_choice(&native, &fmt);
1214         if (res < 0) {
1215                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
1216                 return -1;
1217         }
1218         
1219         /* Now we have a good choice for both.  We'll write using our native format. */
1220         chan->pvt->rawwriteformat = native;
1221         /* User perspective is fmt */
1222         chan->writeformat = fmt;
1223         /* Free any write translation we have right now */
1224         if (chan->pvt->writetrans)
1225                 ast_translator_free_path(chan->pvt->writetrans);
1226         /* Build a translation path from the user write format to the raw writing format */
1227         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1228         if (option_debug)
1229                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
1230         return 0;
1231 }
1232
1233 int ast_set_read_format(struct ast_channel *chan, int fmts)
1234 {
1235         int fmt;
1236         int native;
1237         int res;
1238         
1239         native = chan->nativeformats;
1240         fmt = fmts;
1241         /* Find a translation path from the native read format to one of the user's read formats */
1242         res = ast_translator_best_choice(&fmt, &native);
1243         if (res < 0) {
1244                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
1245                 return -1;
1246         }
1247         
1248         /* Now we have a good choice for both.  We'll write using our native format. */
1249         chan->pvt->rawreadformat = native;
1250         /* User perspective is fmt */
1251         chan->readformat = fmt;
1252         /* Free any read translation we have right now */
1253         if (chan->pvt->readtrans)
1254                 ast_translator_free_path(chan->pvt->readtrans);
1255         /* Build a translation path from the raw read format to the user reading format */
1256         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1257         if (option_debug)
1258                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
1259         return 0;
1260 }
1261
1262 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1263 {
1264         int state = 0;
1265         struct ast_channel *chan;
1266         struct ast_frame *f;
1267         int res;
1268         
1269         chan = ast_request(type, format, data);
1270         if (chan) {
1271                 if (callerid)
1272                         ast_set_callerid(chan, callerid, 1);
1273                 if (!ast_call(chan, data, 0)) {
1274                         while(timeout && (chan->_state != AST_STATE_UP)) {
1275                                 res = ast_waitfor(chan, timeout);
1276                                 if (res < 0) {
1277                                         /* Something not cool, or timed out */
1278                                         ast_hangup(chan);
1279                                         chan = NULL;
1280                                         break;
1281                                 }
1282                                 /* If done, break out */
1283                                 if (!res)
1284                                         break;
1285                                 if (timeout > -1)
1286                                         timeout = res;
1287                                 f = ast_read(chan);
1288                                 if (!f) {
1289                                         state = AST_CONTROL_HANGUP;
1290                                         ast_hangup(chan);
1291                                         chan = NULL;
1292                                         break;
1293                                 }
1294                                 if (f->frametype == AST_FRAME_CONTROL) {
1295                                         if (f->subclass == AST_CONTROL_RINGING)
1296                                                 state = AST_CONTROL_RINGING;
1297                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1298                                                 state = f->subclass;
1299                                                 break;
1300                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1301                                                 state = f->subclass;
1302                                                 break;
1303                                         } else {
1304                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1305                                         }
1306                                 }
1307                                 ast_frfree(f);
1308                         }
1309                 } else {
1310                         ast_hangup(chan);
1311                         chan = NULL;
1312                         ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1313                 }
1314         } else
1315                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1316         if (chan && (chan->_state == AST_STATE_UP))
1317                 state = AST_CONTROL_ANSWER;
1318         if (outstate)
1319                 *outstate = state;
1320         return chan;
1321 }
1322
1323 struct ast_channel *ast_request(char *type, int format, void *data)
1324 {
1325         struct chanlist *chan;
1326         struct ast_channel *c = NULL;
1327         int capabilities;
1328         int fmt;
1329         int res;
1330         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1331                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1332                 return NULL;
1333         }
1334         chan = backends;
1335         while(chan) {
1336                 if (!strcasecmp(type, chan->type)) {
1337                         capabilities = chan->capabilities;
1338                         fmt = format;
1339                         res = ast_translator_best_choice(&fmt, &capabilities);
1340                         if (res < 0) {
1341                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1342                                 PTHREAD_MUTEX_UNLOCK(&chlock);
1343                                 return NULL;
1344                         }
1345                         PTHREAD_MUTEX_UNLOCK(&chlock);
1346                         if (chan->requester)
1347                                 c = chan->requester(type, capabilities, data);
1348                         if (c) {
1349                                 manager_event(EVENT_FLAG_CALL, "Newchannel",
1350                                 "Channel: %s\r\n"
1351                                 "State: %s\r\n"
1352                                 "Callerid: %s\r\n",
1353                                 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>");
1354                         }
1355                         return c;
1356                 }
1357                 chan = chan->next;
1358         }
1359         if (!chan)
1360                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1361         PTHREAD_MUTEX_UNLOCK(&chlock);
1362         return c;
1363 }
1364
1365 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1366 {
1367         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1368            If the remote end does not answer within the timeout, then do NOT hang up, but 
1369            return anyway.  */
1370         int res = -1;
1371         /* Stop if we're a zombie or need a soft hangup */
1372         ast_pthread_mutex_lock(&chan->lock);
1373         if (!chan->zombie && !ast_check_hangup(chan)) 
1374                 if (chan->pvt->call)
1375                         res = chan->pvt->call(chan, addr, timeout);
1376         pthread_mutex_unlock(&chan->lock);
1377         return res;
1378 }
1379
1380 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1381 {
1382         int pos=0;
1383         int to = ftimeout;
1384         char d;
1385         /* Stop if we're a zombie or need a soft hangup */
1386         if (c->zombie || ast_check_hangup(c)) 
1387                 return -1;
1388         if (!len)
1389                 return -1;
1390         do {
1391                 if (c->streamid > -1) {
1392                         d = ast_waitstream(c, AST_DIGIT_ANY);
1393                         ast_stopstream(c);
1394                         usleep(1000);
1395                         if (!d)
1396                                 d = ast_waitfordigit(c, to);
1397                 } else {
1398                         d = ast_waitfordigit(c, to);
1399                 }
1400                 if (d < 0)
1401                         return -1;
1402                 if (d == 0) {
1403                         s[pos]='\0';
1404                         return 1;
1405                 }
1406                 if (!strchr(enders, d))
1407                         s[pos++] = d;
1408                 if (strchr(enders, d) || (pos >= len)) {
1409                         s[pos]='\0';
1410                         return 0;
1411                 }
1412                 to = timeout;
1413         } while(1);
1414         /* Never reached */
1415         return 0;
1416 }
1417
1418 int ast_channel_supports_html(struct ast_channel *chan)
1419 {
1420         if (chan->pvt->send_html)
1421                 return 1;
1422         return 0;
1423 }
1424
1425 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1426 {
1427         if (chan->pvt->send_html)
1428                 return chan->pvt->send_html(chan, subclass, data, datalen);
1429         return -1;
1430 }
1431
1432 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1433 {
1434         if (chan->pvt->send_html)
1435                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1436         return -1;
1437 }
1438
1439 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1440 {
1441         int peerf;
1442         int chanf;
1443         int res;
1444         peerf = peer->nativeformats;
1445         chanf = chan->nativeformats;
1446         res = ast_translator_best_choice(&peerf, &chanf);
1447         if (res < 0) {
1448                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1449                 return -1;
1450         }
1451         /* Set read format on channel */
1452         res = ast_set_read_format(chan, peerf);
1453         if (res < 0) {
1454                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1455                 return -1;
1456         }
1457         /* Set write format on peer channel */
1458         res = ast_set_write_format(peer, peerf);
1459         if (res < 0) {
1460                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1461                 return -1;
1462         }
1463         /* Now we go the other way */
1464         peerf = peer->nativeformats;
1465         chanf = chan->nativeformats;
1466         res = ast_translator_best_choice(&chanf, &peerf);
1467         if (res < 0) {
1468                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1469                 return -1;
1470         }
1471         /* Set writeformat on channel */
1472         res = ast_set_write_format(chan, chanf);
1473         if (res < 0) {
1474                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1475                 return -1;
1476         }
1477         /* Set read format on peer channel */
1478         res = ast_set_read_format(peer, chanf);
1479         if (res < 0) {
1480                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1481                 return -1;
1482         }
1483         return 0;
1484 }
1485
1486 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1487 {
1488         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1489                 clone->name, original->name);
1490         if (original->masq) {
1491                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1492                         original->masq->name, original->name);
1493                 return -1;
1494         }
1495         if (clone->masqr) {
1496                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1497                         clone->name, clone->masqr->name);
1498                 return -1;
1499         }
1500         original->masq = clone;
1501         clone->masqr = original;
1502         return 0;
1503 }
1504
1505 void ast_change_name(struct ast_channel *chan, char *newname)
1506 {
1507         char tmp[256];
1508         strncpy(tmp, chan->name, 256);
1509         strncpy(chan->name, newname, sizeof(chan->name) - 1);
1510         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", tmp, chan->name);
1511 }
1512
1513 static int ast_do_masquerade(struct ast_channel *original)
1514 {
1515         int x;
1516         int res=0;
1517         char *tmp;
1518         void *tmpv;
1519         struct ast_channel_pvt *p;
1520         struct ast_channel *clone = original->masq;
1521         int rformat = original->readformat;
1522         int wformat = original->writeformat;
1523         char newn[100];
1524         char orig[100];
1525         char masqn[100];
1526         char zombn[100];
1527         
1528 #if 1
1529         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1530                 clone->name, clone->_state, original->name, original->_state);
1531 #endif
1532         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1533            the clone channel into the original channel.  Start by killing off the original
1534            channel's backend.   I'm not sure we're going to keep this function, because 
1535            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1536
1537         /* Having remembered the original read/write formats, we turn off any translation on either
1538            one */
1539         free_translation(clone);
1540         free_translation(original);
1541
1542         /* We need the clone's lock, too */
1543         ast_pthread_mutex_lock(&clone->lock);
1544
1545         /* Unlink the masquerade */
1546         original->masq = NULL;
1547         clone->masqr = NULL;
1548         
1549         /* Save the original name */
1550         strncpy(orig, original->name, sizeof(orig) - 1);
1551         /* Save the new name */
1552         strncpy(newn, clone->name, sizeof(newn) - 1);
1553         /* Create the masq name */
1554         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1555                 
1556         /* Copy the name from the clone channel */
1557         strncpy(original->name, newn, sizeof(original->name)-1);
1558
1559         /* Mangle the name of the clone channel */
1560         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1561         
1562         /* Notify any managers of the change, first the masq then the other */
1563         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1564         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1565
1566         /* Swap the guts */     
1567         p = original->pvt;
1568         original->pvt = clone->pvt;
1569         clone->pvt = p;
1570         
1571         clone->_softhangup = AST_SOFTHANGUP_DEV;
1572
1573
1574         if (clone->pvt->fixup){
1575                 res = clone->pvt->fixup(original, clone);
1576                 if (res) 
1577                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1578         }
1579
1580         /* Start by disconnecting the original's physical side */
1581         if (clone->pvt->hangup)
1582                 res = clone->pvt->hangup(clone);
1583         if (res) {
1584                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1585                 pthread_mutex_unlock(&clone->lock);
1586                 return -1;
1587         }
1588         
1589         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
1590         /* Mangle the name of the clone channel */
1591         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
1592         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
1593
1594         /* Keep the same language.  */
1595         /* Update the type. */
1596         original->type = clone->type;
1597         /* Copy the FD's */
1598         for (x=0;x<AST_MAX_FDS;x++)
1599                 original->fds[x] = clone->fds[x];
1600         /* Move the variables */
1601         tmpv = original->varshead.first;
1602         original->varshead.first = clone->varshead.first;
1603         clone->varshead.first = tmpv;
1604         /* Presense of ADSI capable CPE follows clone */
1605         original->adsicpe = clone->adsicpe;
1606         /* Bridge remains the same */
1607         /* CDR fields remain the same */
1608         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1609         /* Application and data remain the same */
1610         /* Clone exception  becomes real one, as with fdno */
1611         original->exception = clone->exception;
1612         original->fdno = clone->fdno;
1613         /* Schedule context remains the same */
1614         /* Stream stuff stays the same */
1615         /* Keep the original state.  The fixup code will need to work with it most likely */
1616
1617         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1618            fields back into the defunct 'clone' so that they will be freed when
1619            ast_frfree is eventually called */
1620         tmp = original->dnid;
1621         original->dnid = clone->dnid;
1622         clone->dnid = tmp;
1623         
1624         tmp = original->callerid;
1625         original->callerid = clone->callerid;
1626         clone->callerid = tmp;
1627         
1628         /* Our native formats are different now */
1629         original->nativeformats = clone->nativeformats;
1630
1631         /* And of course, so does our current state.  Note we need not
1632            call ast_setstate since the event manager doesn't really consider
1633            these separate */
1634         original->_state = clone->_state;
1635         
1636         /* Context, extension, priority, app data, jump table,  remain the same */
1637         /* pvt switches.  pbx stays the same, as does next */
1638         
1639         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1640            a zombie so nothing tries to touch it.  If it's already been marked as a
1641            zombie, then free it now (since it already is considered invalid). */
1642         if (clone->zombie) {
1643                 pthread_mutex_unlock(&clone->lock);
1644                 ast_channel_free(clone);
1645                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
1646         } else {
1647                 clone->zombie=1;
1648                 pthread_mutex_unlock(&clone->lock);
1649         }
1650         /* Set the write format */
1651         ast_set_write_format(original, wformat);
1652
1653         /* Set the read format */
1654         ast_set_read_format(original, rformat);
1655
1656         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1657
1658         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1659            can fix up everything as best as possible */
1660         if (original->pvt->fixup) {
1661                 res = original->pvt->fixup(clone, original);
1662                 if (res) {
1663                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1664                                 original->type, original->name);
1665                         return -1;
1666                 }
1667         } else
1668                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
1669                         original->type, original->name);
1670         /* Signal any blocker */
1671         if (original->blocking)
1672                 pthread_kill(original->blocker, SIGURG);
1673         return 0;
1674 }
1675
1676 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
1677 {
1678         if (chan->callerid)
1679                 free(chan->callerid);
1680         if (anitoo && chan->ani)
1681                 free(chan->ani);
1682         if (callerid) {
1683                 chan->callerid = strdup(callerid);
1684                 if (anitoo)
1685                         chan->ani = strdup(callerid);
1686         } else {
1687                 chan->callerid = NULL;
1688                 if (anitoo)
1689                         chan->ani = NULL;
1690         }
1691         if (chan->cdr)
1692                 ast_cdr_setcid(chan->cdr, chan);
1693         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
1694                                 "Channel: %s\r\n"
1695                                 "Callerid: %s\r\n",
1696                                 chan->name, chan->callerid ? 
1697                                 chan->callerid : "<Unknown>");
1698 }
1699
1700 int ast_setstate(struct ast_channel *chan, int state)
1701 {
1702         if (chan->_state != state) {
1703                 int oldstate = chan->_state;
1704                 chan->_state = state;
1705                 if (oldstate == AST_STATE_DOWN) {
1706                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1707                         "Channel: %s\r\n"
1708                         "State: %s\r\n"
1709                         "Callerid: %s\r\n",
1710                         chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1711                 } else {
1712                         manager_event(EVENT_FLAG_CALL, "Newstate", 
1713                                 "Channel: %s\r\n"
1714                                 "State: %s\r\n"
1715                                 "Callerid: %s\r\n",
1716                                 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1717                 }
1718         }
1719         return 0;
1720 }
1721
1722 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1723 {
1724         /* Copy voice back and forth between the two channels.  Give the peer
1725            the ability to transfer calls with '#<extension' syntax. */
1726         struct ast_channel *cs[3];
1727         int to = -1;
1728         struct ast_frame *f;
1729         struct ast_channel *who = NULL;
1730         int res;
1731         int nativefailed=0;
1732
1733         /* Stop if we're a zombie or need a soft hangup */
1734         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
1735                 return -1;
1736         if (c0->bridge) {
1737                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1738                         c0->name, c0->bridge->name);
1739                 return -1;
1740         }
1741         if (c1->bridge) {
1742                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1743                         c1->name, c1->bridge->name);
1744                 return -1;
1745         }
1746         
1747         /* Keep track of bridge */
1748         c0->bridge = c1;
1749         c1->bridge = c0;
1750         cs[0] = c0;
1751         cs[1] = c1;
1752         
1753         manager_event(EVENT_FLAG_CALL, "Link", 
1754                         "Channel1: %s\r\n"
1755                         "Channel2: %s\r\n",
1756                         c0->name, c1->name);
1757
1758         for (/* ever */;;) {
1759                 /* Stop if we're a zombie or need a soft hangup */
1760                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
1761                         *fo = NULL;
1762                         if (who) *rc = who;
1763                         res = 0;
1764                         break;
1765                 }
1766                 if (c0->pvt->bridge && 
1767                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed) {
1768                                 /* Looks like they share a bridge code */
1769                         if (option_verbose > 2) 
1770                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
1771                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
1772                                 c0->bridge = NULL;
1773                                 c1->bridge = NULL;
1774                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
1775                                         "Channel1: %s\r\n"
1776                                         "Channel2: %s\r\n",
1777                                         c0->name, c1->name);
1778                                 return 0;
1779                         }
1780                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
1781                            my not wanting to bridge */
1782                         if ((res != -2) && (res != -3))
1783                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
1784                         if (res != -3) nativefailed++;
1785                 }
1786         
1787                         
1788                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
1789                         !(c0->generator || c1->generator))  {
1790                         if (ast_channel_make_compatible(c0, c1)) {
1791                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
1792                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
1793                                         "Channel1: %s\r\n"
1794                                         "Channel2: %s\r\n",
1795                                         c0->name, c1->name);
1796                                 return -1;
1797                         }
1798                 }
1799                 who = ast_waitfor_n(cs, 2, &to);
1800                 if (!who) {
1801                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
1802                         continue;
1803                 }
1804                 f = ast_read(who);
1805                 if (!f) {
1806                         *fo = NULL;
1807                         *rc = who;
1808                         res = 0;
1809                         break;
1810                 }
1811
1812                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1813                         *fo = f;
1814                         *rc = who;
1815                         res =  0;
1816                         break;
1817                 }
1818                 if ((f->frametype == AST_FRAME_VOICE) ||
1819                         (f->frametype == AST_FRAME_TEXT) ||
1820                         (f->frametype == AST_FRAME_VIDEO) || 
1821                         (f->frametype == AST_FRAME_IMAGE) ||
1822                         (f->frametype == AST_FRAME_DTMF)) {
1823                         if ((f->frametype == AST_FRAME_DTMF) && 
1824                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1825                                 if ((who == c0)) {
1826                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1827                                                 *rc = c0;
1828                                                 *fo = f;
1829                                                 /* Take out of conference mode */
1830                                                 res = 0;
1831                                                 break;
1832                                         } else 
1833                                                 goto tackygoto;
1834                                 } else
1835                                 if ((who == c1)) {
1836                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1837                                                 *rc = c1;
1838                                                 *fo = f;
1839                                                 res =  0;
1840                                                 break;
1841                                         } else
1842                                                 goto tackygoto;
1843                                 }
1844                         } else {
1845 #if 0
1846                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1847                                 if (who == last) 
1848                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1849                                 last = who;
1850 #endif
1851 tackygoto:
1852                                 /* Don't copy packets if there is a generator on either one, since they're
1853                                    not supposed to be listening anyway */
1854                                 if (!c0->generator && !c1->generator) {
1855                                         if (who == c0) 
1856                                                 ast_write(c1, f);
1857                                         else 
1858                                                 ast_write(c0, f);
1859                                 }
1860                         }
1861                         ast_frfree(f);
1862                 } else
1863                         ast_frfree(f);
1864                 /* Swap who gets priority */
1865                 cs[2] = cs[0];
1866                 cs[0] = cs[1];
1867                 cs[1] = cs[2];
1868         }
1869         c0->bridge = NULL;
1870         c1->bridge = NULL;
1871         manager_event(EVENT_FLAG_CALL, "Unlink", 
1872                                         "Channel1: %s\r\n"
1873                                         "Channel2: %s\r\n",
1874                                         c0->name, c1->name);
1875         return res;
1876 }
1877
1878 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
1879 {
1880         int res;
1881         if (chan->pvt->setoption) {
1882                 res = chan->pvt->setoption(chan, option, data, datalen);
1883                 if (res < 0)
1884                         return res;
1885         } else {
1886                 errno = ENOSYS;
1887                 return -1;
1888         }
1889         if (block) {
1890                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
1891                    intermediate packets. XXX */
1892                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
1893                 return -1;
1894         }
1895         return 0;
1896 }
1897
1898 struct tonepair_def {
1899         int freq1;
1900         int freq2;
1901         int duration;
1902         int vol;
1903 };
1904
1905 struct tonepair_state {
1906         float freq1;
1907         float freq2;
1908         float vol;
1909         int duration;
1910         int pos;
1911         int origwfmt;
1912         struct ast_frame f;
1913         unsigned char offset[AST_FRIENDLY_OFFSET];
1914         short data[4000];
1915 };
1916
1917 static void tonepair_release(struct ast_channel *chan, void *params)
1918 {
1919         struct tonepair_state *ts = params;
1920         if (chan) {
1921                 ast_set_write_format(chan, ts->origwfmt);
1922         }
1923         free(ts);
1924 }
1925
1926 static void * tonepair_alloc(struct ast_channel *chan, void *params)
1927 {
1928         struct tonepair_state *ts;
1929         struct tonepair_def *td = params;
1930         ts = malloc(sizeof(struct tonepair_state));
1931         if (!ts)
1932                 return NULL;
1933         memset(ts, 0, sizeof(struct tonepair_state));
1934         ts->origwfmt = chan->writeformat;
1935         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
1936                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
1937                 tonepair_release(NULL, ts);
1938                 ts = NULL;
1939         } else {
1940                 ts->freq1 = td->freq1;
1941                 ts->freq2 = td->freq2;
1942                 ts->duration = td->duration;
1943                 ts->vol = td->vol;
1944         }
1945         /* Let interrupts interrupt :) */
1946         chan->writeinterrupt = 1;
1947         return ts;
1948 }
1949
1950 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
1951 {
1952         struct tonepair_state *ts = data;
1953         int x;
1954
1955         /* we need to prepare a frame with 16 * timelen samples as we're 
1956          * generating SLIN audio
1957          */
1958         len = samples * 2;
1959
1960         if (len > sizeof(ts->data) / 2 - 1) {
1961                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
1962                 return -1;
1963         }
1964         memset(&ts->f, 0, sizeof(ts->f));
1965         for (x=0;x<len/2;x++) {
1966                 ts->data[x] = ts->vol * (
1967                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
1968                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
1969                         );
1970         }
1971         ts->f.frametype = AST_FRAME_VOICE;
1972         ts->f.subclass = AST_FORMAT_SLINEAR;
1973         ts->f.datalen = len;
1974         ts->f.samples = samples;
1975         ts->f.offset = AST_FRIENDLY_OFFSET;
1976         ts->f.data = ts->data;
1977         ast_write(chan, &ts->f);
1978         ts->pos += x;
1979         if (ts->duration > 0) {
1980                 if (ts->pos >= ts->duration * 8)
1981                         return -1;
1982         }
1983         return 0;
1984 }
1985
1986 static struct ast_generator tonepair = {
1987         alloc: tonepair_alloc,
1988         release: tonepair_release,
1989         generate: tonepair_generator,
1990 };
1991
1992 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
1993 {
1994         struct tonepair_def d = { 0, };
1995         d.freq1 = freq1;
1996         d.freq2 = freq2;
1997         d.duration = duration;
1998         if (vol < 1)
1999                 d.vol = 8192;
2000         else
2001                 d.vol = vol;
2002         if (ast_activate_generator(chan, &tonepair, &d))
2003                 return -1;
2004         return 0;
2005 }
2006
2007 void ast_tonepair_stop(struct ast_channel *chan)
2008 {
2009         ast_deactivate_generator(chan);
2010 }
2011
2012 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2013 {
2014         struct ast_frame *f;
2015         int res;
2016         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2017                 return res;
2018
2019         /* Give us some wiggle room */
2020         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2021                 f = ast_read(chan);
2022                 if (f)
2023                         ast_frfree(f);
2024                 else
2025                         return -1;
2026         }
2027         return 0;
2028 }