2 * Asterisk -- A telephony toolkit for Linux.
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
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>
43 /* uncomment if you have problems with 'monitoring' synchronized files */
45 #define MONITOR_CONSTANT_DELAY
46 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
49 static int shutting_down = 0;
50 static int uniqueint = 0;
52 /* XXX Lock appropriately in more functions XXX */
58 struct ast_channel * (*requester)(char *type, int format, void *data);
59 int (*devicestate)(void *data);
60 struct chanlist *next;
62 struct ast_channel *channels = NULL;
64 /* Protect the channel list (highly unlikely that two things would change
65 it at the same time, but still! */
67 static ast_mutex_t chlock = AST_MUTEX_INITIALIZER;
69 int ast_check_hangup(struct ast_channel *chan)
73 /* if soft hangup flag, return true */
74 if (chan->_softhangup) return 1;
75 /* if no private structure, return true */
76 if (!chan->pvt->pvt) return 1;
77 /* if no hangup scheduled, just return here */
78 if (!chan->whentohangup) return 0;
79 time(&myt); /* get current time */
80 /* return, if not yet */
81 if (chan->whentohangup > myt) return 0;
82 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
86 static int ast_check_hangup_locked(struct ast_channel *chan)
89 ast_mutex_lock(&chan->lock);
90 res = ast_check_hangup(chan);
91 ast_mutex_unlock(&chan->lock);
95 void ast_begin_shutdown(int hangup)
97 struct ast_channel *c;
100 ast_mutex_lock(&chlock);
103 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
106 ast_mutex_unlock(&chlock);
110 int ast_active_channels(void)
112 struct ast_channel *c;
114 ast_mutex_lock(&chlock);
120 ast_mutex_unlock(&chlock);
124 void ast_cancel_shutdown(void)
129 int ast_shutting_down(void)
131 return shutting_down;
134 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
140 chan->whentohangup = myt + offset;
142 chan->whentohangup = 0;
146 int ast_channel_register(char *type, char *description, int capabilities,
147 struct ast_channel *(*requester)(char *type, int format, void *data))
149 return ast_channel_register_ex(type, description, capabilities, requester, NULL);
152 int ast_channel_register_ex(char *type, char *description, int capabilities,
153 struct ast_channel *(*requester)(char *type, int format, void *data),
154 int (*devicestate)(void *data))
156 struct chanlist *chan, *last=NULL;
157 if (ast_mutex_lock(&chlock)) {
158 ast_log(LOG_WARNING, "Unable to lock channel list\n");
163 if (!strcasecmp(type, chan->type)) {
164 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
165 ast_mutex_unlock(&chlock);
171 chan = malloc(sizeof(struct chanlist));
173 ast_log(LOG_WARNING, "Out of memory\n");
174 ast_mutex_unlock(&chlock);
177 strncpy(chan->type, type, sizeof(chan->type)-1);
178 strncpy(chan->description, description, sizeof(chan->description)-1);
179 chan->capabilities = capabilities;
180 chan->requester = requester;
181 chan->devicestate = devicestate;
188 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
189 else if (option_verbose > 1)
190 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
191 ast_mutex_unlock(&chlock);
195 char *ast_state2str(int state)
197 /* XXX Not reentrant XXX */
198 static char localtmp[256];
202 case AST_STATE_RESERVED:
204 case AST_STATE_OFFHOOK:
206 case AST_STATE_DIALING:
210 case AST_STATE_RINGING:
217 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
223 int ast_best_codec(int fmts)
225 /* This just our opinion, expressed in code. We are asked to choose
226 the best codec to use, given no information */
230 /* Okay, ulaw is used by all telephony equipment, so start with it */
232 /* Unless of course, you're a silly European, so then prefer ALAW */
234 /* Okay, well, signed linear is easy to translate into other stuff */
236 /* G.726 is standard ADPCM */
238 /* ADPCM has great sound quality and is still pretty easy to translate */
240 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
241 translate and sounds pretty good */
243 /* iLBC is not too bad */
245 /* Speex is free, but computationally more expensive than GSM */
247 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
250 /* G.729a is faster than 723 and slightly less expensive */
252 /* Down to G.723.1 which is proprietary but at least designed for voice */
257 for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
260 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
264 struct ast_channel *ast_channel_alloc(int needqueue)
266 struct ast_channel *tmp;
267 struct ast_channel_pvt *pvt;
270 struct varshead *headp;
273 /* If shutting down, don't allocate any new channels */
276 ast_mutex_lock(&chlock);
277 tmp = malloc(sizeof(struct ast_channel));
279 memset(tmp, 0, sizeof(struct ast_channel));
280 pvt = malloc(sizeof(struct ast_channel_pvt));
282 memset(pvt, 0, sizeof(struct ast_channel_pvt));
283 tmp->sched = sched_context_create();
285 for (x=0;x<AST_MAX_FDS - 1;x++)
288 pipe(pvt->alertpipe)) {
289 ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
295 /* Make sure we've got it done right if they don't */
297 flags = fcntl(pvt->alertpipe[0], F_GETFL);
298 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
299 flags = fcntl(pvt->alertpipe[1], F_GETFL);
300 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
302 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
303 #ifdef ZAPTEL_OPTIMIZATIONS
304 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
308 /* Always watch the alertpipe */
309 tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
310 /* And timing pipe */
311 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
312 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
315 tmp->_state = AST_STATE_DOWN;
322 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
323 headp=&tmp->varshead;
324 ast_mutex_init(&tmp->lock);
325 AST_LIST_HEAD_INIT(headp);
326 tmp->vars=ast_var_assign("tempvar","tempval");
327 AST_LIST_INSERT_HEAD(headp,tmp->vars,entries);
328 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
329 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
330 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
332 tmp->amaflags = ast_default_amaflags;
333 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
334 tmp->next = channels;
338 ast_log(LOG_WARNING, "Unable to create schedule context\n");
343 ast_log(LOG_WARNING, "Out of memory\n");
348 ast_log(LOG_WARNING, "Out of memory\n");
349 ast_mutex_unlock(&chlock);
353 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int lock)
356 struct ast_frame *prev, *cur;
359 /* Build us a copy and free the original one */
362 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
366 ast_mutex_lock(&chan->lock);
368 cur = chan->pvt->readq;
374 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
375 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
376 if (fin->frametype != AST_FRAME_VOICE) {
377 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
380 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
383 ast_mutex_unlock(&chan->lock);
390 chan->pvt->readq = f;
391 if (chan->pvt->alertpipe[1] > -1) {
392 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
393 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
394 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
395 } else if (chan->blocking) {
396 pthread_kill(chan->blocker, SIGURG);
399 ast_mutex_unlock(&chan->lock);
403 int ast_queue_hangup(struct ast_channel *chan, int lock)
405 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
406 chan->_softhangup |= AST_SOFTHANGUP_DEV;
407 return ast_queue_frame(chan, &f, lock);
410 int ast_queue_control(struct ast_channel *chan, int control, int lock)
412 struct ast_frame f = { AST_FRAME_CONTROL, };
413 f.subclass = control;
414 return ast_queue_frame(chan, &f, lock);
417 int ast_channel_defer_dtmf(struct ast_channel *chan)
421 pre = chan->deferdtmf;
427 void ast_channel_undefer_dtmf(struct ast_channel *chan)
433 struct ast_channel *ast_channel_walk(struct ast_channel *prev)
435 struct ast_channel *l, *ret=NULL;
436 ast_mutex_lock(&chlock);
439 ast_mutex_unlock(&chlock);
447 ast_mutex_unlock(&chlock);
452 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
453 int (*cond)(void*), void *data )
458 if( cond && ((*cond)(data) == 0 ) )
460 ms = ast_waitfor(chan, ms);
473 int ast_safe_sleep(struct ast_channel *chan, int ms)
477 ms = ast_waitfor(chan, ms);
490 void ast_channel_free(struct ast_channel *chan)
492 struct ast_channel *last=NULL, *cur;
494 struct ast_var_t *vardata;
495 struct ast_frame *f, *fp;
496 struct varshead *headp;
497 char name[AST_CHANNEL_NAME];
499 headp=&chan->varshead;
501 ast_mutex_lock(&chlock);
506 last->next = cur->next;
508 channels = cur->next;
515 ast_log(LOG_WARNING, "Unable to find channel in list\n");
517 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
519 strncpy(name, chan->name, sizeof(name)-1);
521 /* Stop monitoring */
523 chan->monitor->stop( chan, 0 );
526 /* Free translatosr */
527 if (chan->pvt->readtrans)
528 ast_translator_free_path(chan->pvt->readtrans);
529 if (chan->pvt->writetrans)
530 ast_translator_free_path(chan->pvt->writetrans);
532 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
536 free(chan->callerid);
541 ast_mutex_destroy(&chan->lock);
542 /* Close pipes if appropriate */
543 if ((fd = chan->pvt->alertpipe[0]) > -1)
545 if ((fd = chan->pvt->alertpipe[1]) > -1)
547 if ((fd = chan->timingfd) > -1)
549 f = chan->pvt->readq;
550 chan->pvt->readq = NULL;
557 /* loop over the variables list, freeing all data and deleting list items */
558 /* no need to lock the list, as the channel is already locked */
560 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
561 vardata = AST_LIST_FIRST(headp);
562 AST_LIST_REMOVE_HEAD(headp, entries);
563 // printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata));
564 ast_var_delete(vardata);
571 ast_mutex_unlock(&chlock);
573 ast_device_state_changed(name);
576 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
579 struct ast_frame f = { AST_FRAME_NULL };
581 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
582 /* Inform channel driver that we need to be hung up, if it cares */
583 chan->_softhangup |= cause;
584 ast_queue_frame(chan, &f, 0);
585 /* Interrupt any select call or such */
587 pthread_kill(chan->blocker, SIGURG);
591 int ast_softhangup(struct ast_channel *chan, int cause)
594 ast_mutex_lock(&chan->lock);
595 res = ast_softhangup_nolock(chan, cause);
596 ast_mutex_unlock(&chan->lock);
600 static int ast_do_masquerade(struct ast_channel *original);
602 static void free_translation(struct ast_channel *clone)
604 if (clone->pvt->writetrans)
605 ast_translator_free_path(clone->pvt->writetrans);
606 if (clone->pvt->readtrans)
607 ast_translator_free_path(clone->pvt->readtrans);
608 clone->pvt->writetrans = NULL;
609 clone->pvt->readtrans = NULL;
610 clone->pvt->rawwriteformat = clone->nativeformats;
611 clone->pvt->rawreadformat = clone->nativeformats;
614 int ast_hangup(struct ast_channel *chan)
617 /* Don't actually hang up a channel that will masquerade as someone else, or
618 if someone is going to masquerade as us */
619 ast_mutex_lock(&chan->lock);
621 if (ast_do_masquerade(chan))
622 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
626 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
627 ast_mutex_unlock(&chan->lock);
630 /* If this channel is one which will be masqueraded into something,
631 mark it as a zombie already, so we know to free it later */
633 ast_mutex_unlock(&chan->lock);
637 free_translation(chan);
639 ast_stopstream(chan);
641 sched_context_destroy(chan->sched);
642 /* Clear any tone stuff remaining */
643 if (chan->generatordata)
644 chan->generator->release(chan, chan->generatordata);
645 chan->generatordata = NULL;
646 chan->generator = NULL;
648 /* End the CDR if it hasn't already */
649 ast_cdr_end(chan->cdr);
650 /* Post and Free the CDR */
651 ast_cdr_post(chan->cdr);
652 ast_cdr_free(chan->cdr);
654 if (chan->blocking) {
655 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
656 "is blocked by thread %ld in procedure %s! Expect a failure\n",
657 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
662 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
663 if (chan->pvt->hangup)
664 res = chan->pvt->hangup(chan);
667 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
669 ast_mutex_unlock(&chan->lock);
670 manager_event(EVENT_FLAG_CALL, "Hangup",
673 chan->name, chan->uniqueid);
674 ast_channel_free(chan);
678 void ast_channel_unregister(char *type)
680 struct chanlist *chan, *last=NULL;
682 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
683 if (ast_mutex_lock(&chlock)) {
684 ast_log(LOG_WARNING, "Unable to lock channel list\n");
687 if (option_verbose > 1)
688 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", type);
692 if (!strcasecmp(chan->type, type)) {
694 last->next = chan->next;
696 backends = backends->next;
698 ast_mutex_unlock(&chlock);
704 ast_mutex_unlock(&chlock);
707 int ast_answer(struct ast_channel *chan)
710 /* Stop if we're a zombie or need a soft hangup */
711 if (chan->zombie || ast_check_hangup(chan))
713 switch(chan->_state) {
714 case AST_STATE_RINGING:
716 ast_mutex_lock(&chan->lock);
717 if (chan->pvt->answer)
718 res = chan->pvt->answer(chan);
719 ast_mutex_unlock(&chan->lock);
720 ast_setstate(chan, AST_STATE_UP);
722 ast_cdr_answer(chan->cdr);
727 ast_cdr_answer(chan->cdr);
733 void ast_deactivate_generator(struct ast_channel *chan)
735 if (chan->generatordata) {
736 chan->generator->release(chan, chan->generatordata);
737 chan->generatordata = NULL;
738 chan->generator = NULL;
739 chan->writeinterrupt = 0;
743 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
745 if (chan->generatordata) {
746 chan->generator->release(chan, chan->generatordata);
747 chan->generatordata = NULL;
750 if ((chan->generatordata = gen->alloc(chan, params))) {
751 chan->generator = gen;
758 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
760 /* Wait for x amount of time on a file descriptor to have input. */
767 tv.tv_sec = *ms / 1000;
768 tv.tv_usec = (*ms % 1000) * 1000;
773 FD_SET(fds[x], &rfds);
774 FD_SET(fds[x], &efds);
780 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
782 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
785 /* Simulate a timeout if we were interrupted */
794 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
796 *exception = FD_ISSET(fds[x], &efds);
800 *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
804 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
805 int *exception, int *outfd, int *ms)
807 /* Wait for x amount of time on a file descriptor to have input. */
812 struct ast_channel *winner = NULL;
818 /* Perform any pending masquerades */
820 ast_mutex_lock(&c[x]->lock);
822 if (ast_do_masquerade(c[x])) {
823 ast_log(LOG_WARNING, "Masquerade failed\n");
825 ast_mutex_unlock(&c[x]->lock);
829 ast_mutex_unlock(&c[x]->lock);
832 tv.tv_sec = *ms / 1000;
833 tv.tv_usec = (*ms % 1000) * 1000;
838 for (y=0;y<AST_MAX_FDS;y++) {
839 if (c[x]->fds[y] > -1) {
840 FD_SET(c[x]->fds[y], &rfds);
841 FD_SET(c[x]->fds[y], &efds);
842 if (c[x]->fds[y] > max)
846 CHECK_BLOCKING(c[x]);
848 for (x=0;x<nfds; x++) {
849 FD_SET(fds[x], &rfds);
850 FD_SET(fds[x], &efds);
855 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
857 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
862 /* Simulate a timeout if we were interrupted */
866 /* Just an interrupt */
876 for (y=0;y<AST_MAX_FDS;y++) {
877 if (c[x]->fds[y] > -1) {
878 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
879 /* Set exception flag if appropriate */
880 if (FD_ISSET(c[x]->fds[y], &efds))
888 for (x=0;x<nfds;x++) {
889 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
892 if (FD_ISSET(fds[x], &efds) && exception)
897 *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
901 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
903 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
906 int ast_waitfor(struct ast_channel *c, int ms)
908 struct ast_channel *chan;
910 chan = ast_waitfor_n(&c, 1, &ms);
920 char ast_waitfordigit(struct ast_channel *c, int ms)
922 /* XXX Should I be merged with waitfordigit_full XXX */
925 /* Stop if we're a zombie or need a soft hangup */
926 if (c->zombie || ast_check_hangup(c))
928 /* Wait for a digit, no more than ms milliseconds total. */
929 while(ms && !result) {
930 ms = ast_waitfor(c, ms);
931 if (ms < 0) /* Error */
937 if (f->frametype == AST_FRAME_DTMF)
938 result = f->subclass;
947 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
950 #ifdef ZAPTEL_OPTIMIZATIONS
951 if (c->timingfd > -1) {
956 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
957 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
958 c->timingfunc = func;
959 c->timingdata = data;
964 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audio, int ctrl)
968 struct ast_channel *rchan;
970 /* Stop if we're a zombie or need a soft hangup */
971 if (c->zombie || ast_check_hangup(c))
973 /* Wait for a digit, no more than ms milliseconds total. */
974 while(ms && !result) {
975 rchan = ast_waitfor_nandfds(&c, 1, &audio, (audio > -1) ? 1 : 0, NULL, &outfd, &ms);
976 if ((!rchan) && (outfd < 0) && (ms)) /* Error */
978 else if (outfd > -1) {
984 if (f->frametype == AST_FRAME_DTMF)
985 result = f->subclass;
994 struct ast_frame *ast_read(struct ast_channel *chan)
996 struct ast_frame *f = NULL;
998 #ifdef ZAPTEL_OPTIMIZATIONS
1002 static struct ast_frame null_frame =
1007 ast_mutex_lock(&chan->lock);
1009 if (ast_do_masquerade(chan)) {
1010 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1014 ast_mutex_unlock(&chan->lock);
1018 /* Stop if we're a zombie or need a soft hangup */
1019 if (chan->zombie || ast_check_hangup(chan)) {
1020 if (chan->generator)
1021 ast_deactivate_generator(chan);
1022 ast_mutex_unlock(&chan->lock);
1026 if (!chan->deferdtmf && strlen(chan->dtmfq)) {
1027 /* We have DTMF that has been deferred. Return it now */
1028 chan->dtmff.frametype = AST_FRAME_DTMF;
1029 chan->dtmff.subclass = chan->dtmfq[0];
1030 /* Drop first digit */
1031 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1032 ast_mutex_unlock(&chan->lock);
1033 return &chan->dtmff;
1036 /* Read and ignore anything on the alertpipe, but read only
1037 one sizeof(blah) per frame that we send from it */
1038 if (chan->pvt->alertpipe[0] > -1) {
1039 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1041 #ifdef ZAPTEL_OPTIMIZATIONS
1042 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && chan->exception) {
1043 chan->exception = 0;
1045 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1046 func = chan->timingfunc;
1047 data = chan->timingdata;
1048 ast_mutex_unlock(&chan->lock);
1051 ast_log(LOG_DEBUG, "Calling private function\n");
1056 ast_mutex_lock(&chan->lock);
1057 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1058 chan->timingdata = NULL;
1059 ast_mutex_unlock(&chan->lock);
1065 /* Check for pending read queue */
1066 if (chan->pvt->readq) {
1067 f = chan->pvt->readq;
1068 chan->pvt->readq = f->next;
1069 /* Interpret hangup and return NULL */
1070 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1075 chan->blocker = pthread_self();
1076 if (chan->exception) {
1077 if (chan->pvt->exception)
1078 f = chan->pvt->exception(chan);
1080 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1083 /* Clear the exception flag */
1084 chan->exception = 0;
1086 if (chan->pvt->read)
1087 f = chan->pvt->read(chan);
1089 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1093 if (f && (f->frametype == AST_FRAME_VOICE)) {
1094 if (!(f->subclass & chan->nativeformats)) {
1095 /* This frame can't be from the current native formats -- drop it on the
1097 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));
1101 if (chan->monitor && chan->monitor->read_stream ) {
1102 #ifndef MONITOR_CONSTANT_DELAY
1103 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1105 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1106 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1107 chan->insmpl += jump + 2 * f->samples;
1109 chan->insmpl+= f->samples;
1111 int jump = chan->outsmpl - chan->insmpl;
1112 if (jump - MONITOR_DELAY >= 0) {
1113 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1114 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1115 chan->insmpl += jump;
1117 chan->insmpl += f->samples;
1119 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1120 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1122 if (chan->pvt->readtrans) {
1123 f = ast_translate(chan->pvt->readtrans, f, 1);
1130 /* Make sure we always return NULL in the future */
1132 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1133 if (chan->generator)
1134 ast_deactivate_generator(chan);
1135 /* End the CDR if appropriate */
1137 ast_cdr_end(chan->cdr);
1138 } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
1139 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1140 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1142 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1144 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1145 /* Answer the CDR */
1146 ast_setstate(chan, AST_STATE_UP);
1147 ast_cdr_answer(chan->cdr);
1149 ast_mutex_unlock(&chan->lock);
1151 /* Run any generator sitting on the line */
1152 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1153 /* Mask generator data temporarily */
1156 tmp = chan->generatordata;
1157 chan->generatordata = NULL;
1158 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1159 chan->generatordata = tmp;
1161 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1162 ast_deactivate_generator(chan);
1165 if (chan->fin & 0x80000000)
1166 ast_frame_dump(chan->name, f, "<<");
1167 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1168 chan->fin &= 0x80000000;
1174 int ast_indicate(struct ast_channel *chan, int condition)
1177 /* Stop if we're a zombie or need a soft hangup */
1178 if (chan->zombie || ast_check_hangup(chan))
1180 ast_mutex_lock(&chan->lock);
1181 if (chan->pvt->indicate)
1182 res = chan->pvt->indicate(chan, condition);
1183 ast_mutex_unlock(&chan->lock);
1184 if (!chan->pvt->indicate || res) {
1186 * Device does not support (that) indication, lets fake
1187 * it by doing our own tone generation. (PM2002)
1189 if (condition >= 0) {
1190 const struct tone_zone_sound *ts = NULL;
1191 switch (condition) {
1192 case AST_CONTROL_RINGING:
1193 ts = ast_get_indication_tone(chan->zone, "ring");
1195 case AST_CONTROL_BUSY:
1196 ts = ast_get_indication_tone(chan->zone, "busy");
1198 case AST_CONTROL_CONGESTION:
1199 ts = ast_get_indication_tone(chan->zone, "congestion");
1202 if (ts && ts->data[0]) {
1203 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1204 ast_playtones_start(chan,0,ts->data, 1);
1206 } else if (condition == AST_CONTROL_PROGRESS) {
1207 /* ast_playtones_stop(chan); */
1210 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1214 else ast_playtones_stop(chan);
1219 int ast_recvchar(struct ast_channel *chan, int timeout)
1222 struct ast_frame *f;
1227 if (ast_check_hangup(chan)) return -1;
1228 res = ast_waitfor(chan,ourto);
1229 if (res <= 0) /* if timeout */
1235 if (f == NULL) return -1; /* if hangup */
1236 if ((f->frametype == AST_FRAME_CONTROL) &&
1237 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1238 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1240 c = *((char *)f->data); /* get the data */
1248 int ast_sendtext(struct ast_channel *chan, char *text)
1251 /* Stop if we're a zombie or need a soft hangup */
1252 if (chan->zombie || ast_check_hangup(chan))
1254 CHECK_BLOCKING(chan);
1255 if (chan->pvt->send_text)
1256 res = chan->pvt->send_text(chan, text);
1261 static int do_senddigit(struct ast_channel *chan, char digit)
1265 if (chan->pvt->send_digit)
1266 res = chan->pvt->send_digit(chan, digit);
1267 if (!chan->pvt->send_digit || res) {
1269 * Device does not support DTMF tones, lets fake
1270 * it by doing our own generation. (PM2002)
1272 static const char* dtmf_tones[] = {
1273 "!941+1336/50,!0/50", /* 0 */
1274 "!697+1209/50,!0/50", /* 1 */
1275 "!697+1336/50,!0/50", /* 2 */
1276 "!697+1477/50,!0/50", /* 3 */
1277 "!770+1209/50,!0/50", /* 4 */
1278 "!770+1336/50,!0/50", /* 5 */
1279 "!770+1477/50,!0/50", /* 6 */
1280 "!852+1209/50,!0/50", /* 7 */
1281 "!852+1336/50,!0/50", /* 8 */
1282 "!852+1477/50,!0/50", /* 9 */
1283 "!697+1633/50,!0/50", /* A */
1284 "!770+1633/50,!0/50", /* B */
1285 "!852+1633/50,!0/50", /* C */
1286 "!941+1633/50,!0/50", /* D */
1287 "!941+1209/50,!0/50", /* * */
1288 "!941+1477/50,!0/50" }; /* # */
1289 if (digit >= '0' && digit <='9')
1290 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1291 else if (digit >= 'A' && digit <= 'D')
1292 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1293 else if (digit == '*')
1294 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1295 else if (digit == '#')
1296 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1299 ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1306 int ast_prod(struct ast_channel *chan)
1308 struct ast_frame a = { AST_FRAME_VOICE };
1310 /* Send an empty audio frame to get things moving */
1311 if (chan->_state != AST_STATE_UP) {
1312 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1313 a.subclass = chan->pvt->rawwriteformat;
1314 a.data = nothing + AST_FRIENDLY_OFFSET;
1315 if (ast_write(chan, &a))
1316 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1321 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1324 if (!chan->pvt->write_video)
1326 res = ast_write(chan, fr);
1332 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1335 struct ast_frame *f = NULL;
1336 /* Stop if we're a zombie or need a soft hangup */
1337 ast_mutex_lock(&chan->lock);
1338 if (chan->zombie || ast_check_hangup(chan)) {
1339 ast_mutex_unlock(&chan->lock);
1342 /* Handle any pending masquerades */
1344 if (ast_do_masquerade(chan)) {
1345 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1346 ast_mutex_unlock(&chan->lock);
1351 ast_mutex_unlock(&chan->lock);
1354 if (chan->generatordata) {
1355 if (chan->writeinterrupt)
1356 ast_deactivate_generator(chan);
1358 ast_mutex_unlock(&chan->lock);
1362 if (chan->fout & 0x80000000)
1363 ast_frame_dump(chan->name, fr, ">>");
1364 CHECK_BLOCKING(chan);
1365 switch(fr->frametype) {
1366 case AST_FRAME_CONTROL:
1367 /* XXX Interpret control frames XXX */
1368 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1370 case AST_FRAME_DTMF:
1372 ast_mutex_unlock(&chan->lock);
1373 res = do_senddigit(chan,fr->subclass);
1374 ast_mutex_lock(&chan->lock);
1375 CHECK_BLOCKING(chan);
1377 case AST_FRAME_TEXT:
1378 if (chan->pvt->send_text)
1379 res = chan->pvt->send_text(chan, (char *) fr->data);
1381 case AST_FRAME_VIDEO:
1382 /* XXX Handle translation of video codecs one day XXX */
1383 if (chan->pvt->write_video)
1384 res = chan->pvt->write_video(chan, fr);
1389 if (chan->pvt->write) {
1390 if (chan->pvt->writetrans) {
1391 f = ast_translate(chan->pvt->writetrans, fr, 0);
1395 res = chan->pvt->write(chan, f);
1396 if( chan->monitor &&
1397 chan->monitor->write_stream &&
1398 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1399 #ifndef MONITOR_CONSTANT_DELAY
1400 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1402 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1403 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1404 chan->outsmpl += jump + 2 * f->samples;
1406 chan->outsmpl += f->samples;
1408 int jump = chan->insmpl - chan->outsmpl;
1409 if (jump - MONITOR_DELAY >= 0) {
1410 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1411 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1412 chan->outsmpl += jump;
1414 chan->outsmpl += f->samples;
1416 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1417 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1426 /* Consider a write failure to force a soft hangup */
1428 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1430 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1431 chan->fout &= 0x80000000;
1436 ast_mutex_unlock(&chan->lock);
1440 int ast_set_write_format(struct ast_channel *chan, int fmts)
1446 native = chan->nativeformats;
1449 res = ast_translator_best_choice(&native, &fmt);
1451 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1452 ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1456 /* Now we have a good choice for both. We'll write using our native format. */
1457 chan->pvt->rawwriteformat = native;
1458 /* User perspective is fmt */
1459 chan->writeformat = fmt;
1460 /* Free any write translation we have right now */
1461 if (chan->pvt->writetrans)
1462 ast_translator_free_path(chan->pvt->writetrans);
1463 /* Build a translation path from the user write format to the raw writing format */
1464 chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1466 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1470 int ast_set_read_format(struct ast_channel *chan, int fmts)
1476 native = chan->nativeformats;
1478 /* Find a translation path from the native read format to one of the user's read formats */
1479 res = ast_translator_best_choice(&fmt, &native);
1481 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1482 ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1486 /* Now we have a good choice for both. We'll write using our native format. */
1487 chan->pvt->rawreadformat = native;
1488 /* User perspective is fmt */
1489 chan->readformat = fmt;
1490 /* Free any read translation we have right now */
1491 if (chan->pvt->readtrans)
1492 ast_translator_free_path(chan->pvt->readtrans);
1493 /* Build a translation path from the raw read format to the user reading format */
1494 chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1496 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n",
1497 chan->name, ast_getformatname(chan->readformat));
1501 struct ast_channel *__ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid, struct outgoing_helper *oh)
1504 struct ast_channel *chan;
1505 struct ast_frame *f;
1507 chan = ast_request(type, format, data);
1513 /* FIXME replace this call with strsep NOT*/
1514 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1515 pbx_builtin_setvar( chan, var );
1517 if (oh->callerid && *oh->callerid)
1518 ast_set_callerid(chan, oh->callerid, 1);
1519 if (oh->account && *oh->account)
1520 ast_cdr_setaccount(chan, oh->account);
1522 if (callerid && strlen(callerid))
1523 ast_set_callerid(chan, callerid, 1);
1525 if (!ast_call(chan, data, 0)) {
1526 while(timeout && (chan->_state != AST_STATE_UP)) {
1527 res = ast_waitfor(chan, timeout);
1529 /* Something not cool, or timed out */
1532 /* If done, break out */
1539 state = AST_CONTROL_HANGUP;
1543 if (f->frametype == AST_FRAME_CONTROL) {
1544 if (f->subclass == AST_CONTROL_RINGING)
1545 state = AST_CONTROL_RINGING;
1546 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1547 state = f->subclass;
1550 } else if (f->subclass == AST_CONTROL_ANSWER) {
1551 state = f->subclass;
1555 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1561 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1563 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1567 if (oh->context && *oh->context)
1568 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1569 if (oh->exten && *oh->exten)
1570 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1571 chan->priority = oh->priority;
1573 if (chan->_state == AST_STATE_UP)
1574 state = AST_CONTROL_ANSWER;
1578 if (chan && res <= 0) {
1580 chan->cdr = ast_cdr_alloc();
1582 ast_cdr_init(chan->cdr, chan);
1586 sprintf(tmp, "%s/%s",type,(char *)data);
1587 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1588 ast_cdr_update(chan);
1589 ast_cdr_start(chan->cdr);
1590 ast_cdr_end(chan->cdr);
1591 /* If the cause wasn't handled properly */
1592 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1593 ast_cdr_failed(chan->cdr);
1595 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1602 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1604 return __ast_request_and_dial(type, format, data, timeout, outstate, callerid, NULL);
1607 struct ast_channel *ast_request(char *type, int format, void *data)
1609 struct chanlist *chan;
1610 struct ast_channel *c = NULL;
1614 if (ast_mutex_lock(&chlock)) {
1615 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1620 if (!strcasecmp(type, chan->type)) {
1621 capabilities = chan->capabilities;
1623 res = ast_translator_best_choice(&fmt, &capabilities);
1625 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1626 ast_mutex_unlock(&chlock);
1629 ast_mutex_unlock(&chlock);
1630 if (chan->requester)
1631 c = chan->requester(type, capabilities, data);
1633 if (c->_state == AST_STATE_DOWN) {
1634 manager_event(EVENT_FLAG_CALL, "Newchannel",
1639 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>", c->uniqueid);
1647 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1648 ast_mutex_unlock(&chlock);
1652 int ast_parse_device_state(char *device)
1654 char name[AST_CHANNEL_NAME] = "";
1656 struct ast_channel *chan;
1658 chan = ast_channel_walk(NULL);
1660 strncpy(name, chan->name, sizeof(name)-1);
1661 cut = strchr(name,'-');
1664 if (!strcmp(name, device))
1665 return AST_DEVICE_INUSE;
1666 chan = ast_channel_walk(chan);
1668 return AST_DEVICE_UNKNOWN;
1671 int ast_device_state(char *device)
1673 char tech[AST_MAX_EXTENSION] = "";
1675 struct chanlist *chanls;
1678 strncpy(tech, device, sizeof(tech)-1);
1679 number = strchr(tech, '/');
1681 return AST_DEVICE_INVALID;
1686 if (ast_mutex_lock(&chlock)) {
1687 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1692 if (!strcasecmp(tech, chanls->type)) {
1693 ast_mutex_unlock(&chlock);
1694 if (!chanls->devicestate)
1695 return ast_parse_device_state(device);
1697 res = chanls->devicestate(number);
1698 if (res == AST_DEVICE_UNKNOWN)
1699 return ast_parse_device_state(device);
1704 chanls = chanls->next;
1706 ast_mutex_unlock(&chlock);
1707 return AST_DEVICE_INVALID;
1710 int ast_call(struct ast_channel *chan, char *addr, int timeout)
1712 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
1713 If the remote end does not answer within the timeout, then do NOT hang up, but
1716 /* Stop if we're a zombie or need a soft hangup */
1717 ast_mutex_lock(&chan->lock);
1718 if (!chan->zombie && !ast_check_hangup(chan))
1719 if (chan->pvt->call)
1720 res = chan->pvt->call(chan, addr, timeout);
1721 ast_mutex_unlock(&chan->lock);
1725 int ast_transfer(struct ast_channel *chan, char *dest)
1727 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
1728 If the remote end does not answer within the timeout, then do NOT hang up, but
1731 /* Stop if we're a zombie or need a soft hangup */
1732 ast_mutex_lock(&chan->lock);
1733 if (!chan->zombie && !ast_check_hangup(chan)) {
1734 if (chan->pvt->transfer) {
1735 res = chan->pvt->transfer(chan, dest);
1741 ast_mutex_unlock(&chan->lock);
1745 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1750 /* XXX Merge with full version? XXX */
1751 /* Stop if we're a zombie or need a soft hangup */
1752 if (c->zombie || ast_check_hangup(c))
1758 d = ast_waitstream(c, AST_DIGIT_ANY);
1762 d = ast_waitfordigit(c, to);
1764 d = ast_waitfordigit(c, to);
1772 if (!strchr(enders, d))
1774 if (strchr(enders, d) || (pos >= len)) {
1784 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1789 /* Stop if we're a zombie or need a soft hangup */
1790 if (c->zombie || ast_check_hangup(c))
1796 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1800 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1802 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1814 if (!strchr(enders, d))
1816 if (strchr(enders, d) || (pos >= len)) {
1826 int ast_channel_supports_html(struct ast_channel *chan)
1828 if (chan->pvt->send_html)
1833 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1835 if (chan->pvt->send_html)
1836 return chan->pvt->send_html(chan, subclass, data, datalen);
1840 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1842 if (chan->pvt->send_html)
1843 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1847 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1852 peerf = peer->nativeformats;
1853 chanf = chan->nativeformats;
1854 res = ast_translator_best_choice(&peerf, &chanf);
1856 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1859 /* Set read format on channel */
1860 res = ast_set_read_format(chan, peerf);
1862 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1865 /* Set write format on peer channel */
1866 res = ast_set_write_format(peer, peerf);
1868 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1871 /* Now we go the other way */
1872 peerf = peer->nativeformats;
1873 chanf = chan->nativeformats;
1874 res = ast_translator_best_choice(&chanf, &peerf);
1876 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1879 /* Set writeformat on channel */
1880 res = ast_set_write_format(chan, chanf);
1882 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1885 /* Set read format on peer channel */
1886 res = ast_set_read_format(peer, chanf);
1888 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1894 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1896 struct ast_frame null = { AST_FRAME_NULL, };
1897 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1898 clone->name, original->name);
1899 if (original->masq) {
1900 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
1901 original->masq->name, original->name);
1905 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
1906 clone->name, clone->masqr->name);
1909 original->masq = clone;
1910 clone->masqr = original;
1911 /* XXX can't really hold the lock here, but at the same time, it' s
1912 not really safe not to XXX */
1913 ast_queue_frame(original, &null, 0);
1914 ast_queue_frame(clone, &null, 0);
1915 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
1919 void ast_change_name(struct ast_channel *chan, char *newname)
1922 strncpy(tmp, chan->name, 256);
1923 strncpy(chan->name, newname, sizeof(chan->name) - 1);
1924 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
1927 static int ast_do_masquerade(struct ast_channel *original)
1932 struct ast_var_t *varptr;
1933 struct ast_frame *cur, *prev;
1934 struct ast_channel_pvt *p;
1935 struct ast_channel *clone = original->masq;
1936 int rformat = original->readformat;
1937 int wformat = original->writeformat;
1944 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1945 clone->name, clone->_state, original->name, original->_state);
1947 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
1948 the clone channel into the original channel. Start by killing off the original
1949 channel's backend. I'm not sure we're going to keep this function, because
1950 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1952 /* We need the clone's lock, too */
1953 ast_mutex_lock(&clone->lock);
1955 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
1957 /* Having remembered the original read/write formats, we turn off any translation on either
1959 free_translation(clone);
1960 free_translation(original);
1963 /* Unlink the masquerade */
1964 original->masq = NULL;
1965 clone->masqr = NULL;
1967 /* Save the original name */
1968 strncpy(orig, original->name, sizeof(orig) - 1);
1969 /* Save the new name */
1970 strncpy(newn, clone->name, sizeof(newn) - 1);
1971 /* Create the masq name */
1972 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1974 /* Copy the name from the clone channel */
1975 strncpy(original->name, newn, sizeof(original->name)-1);
1977 /* Mangle the name of the clone channel */
1978 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1980 /* Notify any managers of the change, first the masq then the other */
1981 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1982 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1986 original->pvt = clone->pvt;
1989 /* Save any pending frames on both sides. Start by counting
1990 * how many we're going to need... */
1992 cur = clone->pvt->readq;
1999 /* If we had any, prepend them to the ones already in the queue, and
2000 * load up the alertpipe */
2002 prev->next = original->pvt->readq;
2003 original->pvt->readq = clone->pvt->readq;
2004 clone->pvt->readq = NULL;
2005 if (original->pvt->alertpipe[1] > -1) {
2007 write(original->pvt->alertpipe[1], &x, sizeof(x));
2010 clone->_softhangup = AST_SOFTHANGUP_DEV;
2013 if (clone->pvt->fixup){
2014 res = clone->pvt->fixup(original, clone);
2016 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2019 /* Start by disconnecting the original's physical side */
2020 if (clone->pvt->hangup)
2021 res = clone->pvt->hangup(clone);
2023 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2024 ast_mutex_unlock(&clone->lock);
2028 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2029 /* Mangle the name of the clone channel */
2030 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2031 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
2033 /* Keep the same language. */
2034 /* Update the type. */
2035 original->type = clone->type;
2037 for (x=0;x<AST_MAX_FDS;x++) {
2038 original->fds[x] = clone->fds[x];
2040 /* Append variables from clone channel into original channel */
2041 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2042 varptr = original->varshead.first;
2044 while(varptr->entries.next) {
2045 varptr = varptr->entries.next;
2047 varptr->entries.next = clone->varshead.first;
2049 original->varshead.first = clone->varshead.first;
2051 clone->varshead.first = NULL;
2052 /* Presense of ADSI capable CPE follows clone */
2053 original->adsicpe = clone->adsicpe;
2054 /* Bridge remains the same */
2055 /* CDR fields remain the same */
2056 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2057 /* Application and data remain the same */
2058 /* Clone exception becomes real one, as with fdno */
2059 original->exception = clone->exception;
2060 original->fdno = clone->fdno;
2061 /* Schedule context remains the same */
2062 /* Stream stuff stays the same */
2063 /* Keep the original state. The fixup code will need to work with it most likely */
2065 /* dnid and callerid change to become the new, HOWEVER, we also link the original's
2066 fields back into the defunct 'clone' so that they will be freed when
2067 ast_frfree is eventually called */
2068 tmp = original->dnid;
2069 original->dnid = clone->dnid;
2072 tmp = original->callerid;
2073 original->callerid = clone->callerid;
2074 clone->callerid = tmp;
2076 /* Restore original timing file descriptor */
2077 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2079 /* Our native formats are different now */
2080 original->nativeformats = clone->nativeformats;
2082 /* And of course, so does our current state. Note we need not
2083 call ast_setstate since the event manager doesn't really consider
2085 original->_state = clone->_state;
2087 /* Context, extension, priority, app data, jump table, remain the same */
2088 /* pvt switches. pbx stays the same, as does next */
2090 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2091 a zombie so nothing tries to touch it. If it's already been marked as a
2092 zombie, then free it now (since it already is considered invalid). */
2093 if (clone->zombie) {
2094 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2095 ast_mutex_unlock(&clone->lock);
2096 ast_channel_free(clone);
2097 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2099 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2101 ast_mutex_unlock(&clone->lock);
2103 /* Set the write format */
2104 ast_set_write_format(original, wformat);
2106 /* Set the read format */
2107 ast_set_read_format(original, rformat);
2109 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2111 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2112 can fix up everything as best as possible */
2113 if (original->pvt->fixup) {
2114 res = original->pvt->fixup(clone, original);
2116 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2117 original->type, original->name);
2121 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2122 original->type, original->name);
2123 /* Signal any blocker */
2124 if (original->blocking)
2125 pthread_kill(original->blocker, SIGURG);
2126 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2127 original->name, original->_state);
2131 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
2134 free(chan->callerid);
2135 if (anitoo && chan->ani)
2138 chan->callerid = strdup(callerid);
2140 chan->ani = strdup(callerid);
2142 chan->callerid = NULL;
2147 ast_cdr_setcid(chan->cdr, chan);
2148 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2152 chan->name, chan->callerid ?
2153 chan->callerid : "<Unknown>",
2157 int ast_setstate(struct ast_channel *chan, int state)
2159 if (chan->_state != state) {
2160 int oldstate = chan->_state;
2161 chan->_state = state;
2162 if (oldstate == AST_STATE_DOWN) {
2163 ast_device_state_changed(chan->name);
2164 manager_event(EVENT_FLAG_CALL, "Newchannel",
2169 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2171 manager_event(EVENT_FLAG_CALL, "Newstate",
2176 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2182 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2184 /* Copy voice back and forth between the two channels. Give the peer
2185 the ability to transfer calls with '#<extension' syntax. */
2186 struct ast_channel *cs[3];
2188 struct ast_frame *f;
2189 struct ast_channel *who = NULL;
2193 /* Stop if we're a zombie or need a soft hangup */
2194 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1))
2197 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2198 c0->name, c0->bridge->name);
2202 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2203 c1->name, c1->bridge->name);
2207 /* Keep track of bridge */
2213 manager_event(EVENT_FLAG_CALL, "Link",
2216 c0->name, c1->name);
2218 for (/* ever */;;) {
2219 /* Stop if we're a zombie or need a soft hangup */
2220 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1)) {
2224 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");
2227 if (c0->pvt->bridge &&
2228 (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2229 /* Looks like they share a bridge code */
2230 if (option_verbose > 2)
2231 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2232 if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2235 manager_event(EVENT_FLAG_CALL, "Unlink",
2238 c0->name, c1->name);
2239 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2242 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
2243 my not wanting to bridge */
2244 if ((res != -2) && (res != -3))
2245 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2246 if (res != -3) nativefailed++;
2250 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
2251 !(c0->generator || c1->generator)) {
2252 if (ast_channel_make_compatible(c0, c1)) {
2253 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2254 manager_event(EVENT_FLAG_CALL, "Unlink",
2257 c0->name, c1->name);
2261 who = ast_waitfor_n(cs, 2, &to);
2263 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2271 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2275 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2279 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL frame on channel %s\n",who->name);
2282 if ((f->frametype == AST_FRAME_VOICE) ||
2283 (f->frametype == AST_FRAME_TEXT) ||
2284 (f->frametype == AST_FRAME_VIDEO) ||
2285 (f->frametype == AST_FRAME_IMAGE) ||
2286 (f->frametype == AST_FRAME_DTMF)) {
2287 if ((f->frametype == AST_FRAME_DTMF) &&
2288 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2290 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2293 /* Take out of conference mode */
2295 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2301 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2305 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2312 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2314 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2318 /* Don't copy packets if there is a generator on either one, since they're
2319 not supposed to be listening anyway */
2328 /* Swap who gets priority */
2335 manager_event(EVENT_FLAG_CALL, "Unlink",
2338 c0->name, c1->name);
2339 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2343 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2346 if (chan->pvt->setoption) {
2347 res = chan->pvt->setoption(chan, option, data, datalen);
2355 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2356 intermediate packets. XXX */
2357 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2363 struct tonepair_def {
2370 struct tonepair_state {
2378 unsigned char offset[AST_FRIENDLY_OFFSET];
2382 static void tonepair_release(struct ast_channel *chan, void *params)
2384 struct tonepair_state *ts = params;
2386 ast_set_write_format(chan, ts->origwfmt);
2391 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2393 struct tonepair_state *ts;
2394 struct tonepair_def *td = params;
2395 ts = malloc(sizeof(struct tonepair_state));
2398 memset(ts, 0, sizeof(struct tonepair_state));
2399 ts->origwfmt = chan->writeformat;
2400 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2401 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2402 tonepair_release(NULL, ts);
2405 ts->freq1 = td->freq1;
2406 ts->freq2 = td->freq2;
2407 ts->duration = td->duration;
2410 /* Let interrupts interrupt :) */
2411 chan->writeinterrupt = 1;
2415 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2417 struct tonepair_state *ts = data;
2420 /* we need to prepare a frame with 16 * timelen samples as we're
2421 * generating SLIN audio
2425 if (len > sizeof(ts->data) / 2 - 1) {
2426 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2429 memset(&ts->f, 0, sizeof(ts->f));
2430 for (x=0;x<len/2;x++) {
2431 ts->data[x] = ts->vol * (
2432 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2433 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2436 ts->f.frametype = AST_FRAME_VOICE;
2437 ts->f.subclass = AST_FORMAT_SLINEAR;
2438 ts->f.datalen = len;
2439 ts->f.samples = samples;
2440 ts->f.offset = AST_FRIENDLY_OFFSET;
2441 ts->f.data = ts->data;
2442 ast_write(chan, &ts->f);
2444 if (ts->duration > 0) {
2445 if (ts->pos >= ts->duration * 8)
2451 static struct ast_generator tonepair = {
2452 alloc: tonepair_alloc,
2453 release: tonepair_release,
2454 generate: tonepair_generator,
2457 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2459 struct tonepair_def d = { 0, };
2462 d.duration = duration;
2467 if (ast_activate_generator(chan, &tonepair, &d))
2472 void ast_tonepair_stop(struct ast_channel *chan)
2474 ast_deactivate_generator(chan);
2477 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2479 struct ast_frame *f;
2481 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2484 /* Give us some wiggle room */
2485 while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {