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