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