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 if (chan->generator && chan->generator->release)
737 chan->generator->release(chan, chan->generatordata);
738 chan->generatordata = NULL;
739 chan->generator = NULL;
740 chan->writeinterrupt = 0;
744 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
746 if (chan->generatordata) {
747 if (chan->generator && chan->generator->release)
748 chan->generator->release(chan, chan->generatordata);
749 chan->generatordata = NULL;
752 if ((chan->generatordata = gen->alloc(chan, params))) {
753 chan->generator = gen;
760 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
762 /* Wait for x amount of time on a file descriptor to have input. */
769 tv.tv_sec = *ms / 1000;
770 tv.tv_usec = (*ms % 1000) * 1000;
775 FD_SET(fds[x], &rfds);
776 FD_SET(fds[x], &efds);
782 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
784 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
787 /* Simulate a timeout if we were interrupted */
796 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
798 *exception = FD_ISSET(fds[x], &efds);
802 *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
806 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
807 int *exception, int *outfd, int *ms)
809 /* Wait for x amount of time on a file descriptor to have input. */
814 struct ast_channel *winner = NULL;
820 /* Perform any pending masquerades */
822 ast_mutex_lock(&c[x]->lock);
824 if (ast_do_masquerade(c[x])) {
825 ast_log(LOG_WARNING, "Masquerade failed\n");
827 ast_mutex_unlock(&c[x]->lock);
831 ast_mutex_unlock(&c[x]->lock);
834 tv.tv_sec = *ms / 1000;
835 tv.tv_usec = (*ms % 1000) * 1000;
840 for (y=0;y<AST_MAX_FDS;y++) {
841 if (c[x]->fds[y] > -1) {
842 FD_SET(c[x]->fds[y], &rfds);
843 FD_SET(c[x]->fds[y], &efds);
844 if (c[x]->fds[y] > max)
848 CHECK_BLOCKING(c[x]);
850 for (x=0;x<nfds; x++) {
851 FD_SET(fds[x], &rfds);
852 FD_SET(fds[x], &efds);
857 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
859 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
864 /* Simulate a timeout if we were interrupted */
868 /* Just an interrupt */
878 for (y=0;y<AST_MAX_FDS;y++) {
879 if (c[x]->fds[y] > -1) {
880 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
881 /* Set exception flag if appropriate */
882 if (FD_ISSET(c[x]->fds[y], &efds))
890 for (x=0;x<nfds;x++) {
891 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
894 if (FD_ISSET(fds[x], &efds) && exception)
899 *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
903 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
905 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
908 int ast_waitfor(struct ast_channel *c, int ms)
910 struct ast_channel *chan;
912 chan = ast_waitfor_n(&c, 1, &ms);
922 char ast_waitfordigit(struct ast_channel *c, int ms)
924 /* XXX Should I be merged with waitfordigit_full XXX */
927 /* Stop if we're a zombie or need a soft hangup */
928 if (c->zombie || ast_check_hangup(c))
930 /* Wait for a digit, no more than ms milliseconds total. */
931 while(ms && !result) {
932 ms = ast_waitfor(c, ms);
933 if (ms < 0) /* Error */
939 if (f->frametype == AST_FRAME_DTMF)
940 result = f->subclass;
949 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
952 #ifdef ZAPTEL_OPTIMIZATIONS
953 if (c->timingfd > -1) {
958 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
959 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
960 c->timingfunc = func;
961 c->timingdata = data;
966 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audio, int ctrl)
970 struct ast_channel *rchan;
972 /* Stop if we're a zombie or need a soft hangup */
973 if (c->zombie || ast_check_hangup(c))
975 /* Wait for a digit, no more than ms milliseconds total. */
976 while(ms && !result) {
977 rchan = ast_waitfor_nandfds(&c, 1, &audio, (audio > -1) ? 1 : 0, NULL, &outfd, &ms);
978 if ((!rchan) && (outfd < 0) && (ms)) /* Error */
980 else if (outfd > -1) {
986 if (f->frametype == AST_FRAME_DTMF)
987 result = f->subclass;
996 struct ast_frame *ast_read(struct ast_channel *chan)
998 struct ast_frame *f = NULL;
1000 #ifdef ZAPTEL_OPTIMIZATIONS
1001 int (*func)(void *);
1004 static struct ast_frame null_frame =
1009 ast_mutex_lock(&chan->lock);
1011 if (ast_do_masquerade(chan)) {
1012 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1016 ast_mutex_unlock(&chan->lock);
1020 /* Stop if we're a zombie or need a soft hangup */
1021 if (chan->zombie || ast_check_hangup(chan)) {
1022 if (chan->generator)
1023 ast_deactivate_generator(chan);
1024 ast_mutex_unlock(&chan->lock);
1028 if (!chan->deferdtmf && strlen(chan->dtmfq)) {
1029 /* We have DTMF that has been deferred. Return it now */
1030 chan->dtmff.frametype = AST_FRAME_DTMF;
1031 chan->dtmff.subclass = chan->dtmfq[0];
1032 /* Drop first digit */
1033 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1034 ast_mutex_unlock(&chan->lock);
1035 return &chan->dtmff;
1038 /* Read and ignore anything on the alertpipe, but read only
1039 one sizeof(blah) per frame that we send from it */
1040 if (chan->pvt->alertpipe[0] > -1) {
1041 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1043 #ifdef ZAPTEL_OPTIMIZATIONS
1044 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && chan->exception) {
1045 chan->exception = 0;
1047 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1048 func = chan->timingfunc;
1049 data = chan->timingdata;
1050 ast_mutex_unlock(&chan->lock);
1053 ast_log(LOG_DEBUG, "Calling private function\n");
1058 ast_mutex_lock(&chan->lock);
1059 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1060 chan->timingdata = NULL;
1061 ast_mutex_unlock(&chan->lock);
1067 /* Check for pending read queue */
1068 if (chan->pvt->readq) {
1069 f = chan->pvt->readq;
1070 chan->pvt->readq = f->next;
1071 /* Interpret hangup and return NULL */
1072 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1077 chan->blocker = pthread_self();
1078 if (chan->exception) {
1079 if (chan->pvt->exception)
1080 f = chan->pvt->exception(chan);
1082 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1085 /* Clear the exception flag */
1086 chan->exception = 0;
1088 if (chan->pvt->read)
1089 f = chan->pvt->read(chan);
1091 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1095 if (f && (f->frametype == AST_FRAME_VOICE)) {
1096 if (!(f->subclass & chan->nativeformats)) {
1097 /* This frame can't be from the current native formats -- drop it on the
1099 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));
1103 if (chan->monitor && chan->monitor->read_stream ) {
1104 #ifndef MONITOR_CONSTANT_DELAY
1105 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1107 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1108 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1109 chan->insmpl += jump + 2 * f->samples;
1111 chan->insmpl+= f->samples;
1113 int jump = chan->outsmpl - chan->insmpl;
1114 if (jump - MONITOR_DELAY >= 0) {
1115 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1116 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1117 chan->insmpl += jump;
1119 chan->insmpl += f->samples;
1121 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1122 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1124 if (chan->pvt->readtrans) {
1125 f = ast_translate(chan->pvt->readtrans, f, 1);
1132 /* Make sure we always return NULL in the future */
1134 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1135 if (chan->generator)
1136 ast_deactivate_generator(chan);
1137 /* End the CDR if appropriate */
1139 ast_cdr_end(chan->cdr);
1140 } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
1141 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1142 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1144 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1146 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1147 /* Answer the CDR */
1148 ast_setstate(chan, AST_STATE_UP);
1149 ast_cdr_answer(chan->cdr);
1151 ast_mutex_unlock(&chan->lock);
1153 /* Run any generator sitting on the line */
1154 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1155 /* Mask generator data temporarily */
1158 tmp = chan->generatordata;
1159 chan->generatordata = NULL;
1160 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1161 chan->generatordata = tmp;
1163 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1164 ast_deactivate_generator(chan);
1167 if (chan->fin & 0x80000000)
1168 ast_frame_dump(chan->name, f, "<<");
1169 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1170 chan->fin &= 0x80000000;
1176 int ast_indicate(struct ast_channel *chan, int condition)
1179 /* Stop if we're a zombie or need a soft hangup */
1180 if (chan->zombie || ast_check_hangup(chan))
1182 ast_mutex_lock(&chan->lock);
1183 if (chan->pvt->indicate)
1184 res = chan->pvt->indicate(chan, condition);
1185 ast_mutex_unlock(&chan->lock);
1186 if (!chan->pvt->indicate || res) {
1188 * Device does not support (that) indication, lets fake
1189 * it by doing our own tone generation. (PM2002)
1191 if (condition >= 0) {
1192 const struct tone_zone_sound *ts = NULL;
1193 switch (condition) {
1194 case AST_CONTROL_RINGING:
1195 ts = ast_get_indication_tone(chan->zone, "ring");
1197 case AST_CONTROL_BUSY:
1198 ts = ast_get_indication_tone(chan->zone, "busy");
1200 case AST_CONTROL_CONGESTION:
1201 ts = ast_get_indication_tone(chan->zone, "congestion");
1204 if (ts && ts->data[0]) {
1205 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1206 ast_playtones_start(chan,0,ts->data, 1);
1208 } else if (condition == AST_CONTROL_PROGRESS) {
1209 /* ast_playtones_stop(chan); */
1212 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1216 else ast_playtones_stop(chan);
1221 int ast_recvchar(struct ast_channel *chan, int timeout)
1224 struct ast_frame *f;
1229 if (ast_check_hangup(chan)) return -1;
1230 res = ast_waitfor(chan,ourto);
1231 if (res <= 0) /* if timeout */
1237 if (f == NULL) return -1; /* if hangup */
1238 if ((f->frametype == AST_FRAME_CONTROL) &&
1239 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1240 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1242 c = *((char *)f->data); /* get the data */
1250 int ast_sendtext(struct ast_channel *chan, char *text)
1253 /* Stop if we're a zombie or need a soft hangup */
1254 if (chan->zombie || ast_check_hangup(chan))
1256 CHECK_BLOCKING(chan);
1257 if (chan->pvt->send_text)
1258 res = chan->pvt->send_text(chan, text);
1263 static int do_senddigit(struct ast_channel *chan, char digit)
1267 if (chan->pvt->send_digit)
1268 res = chan->pvt->send_digit(chan, digit);
1269 if (!chan->pvt->send_digit || res) {
1271 * Device does not support DTMF tones, lets fake
1272 * it by doing our own generation. (PM2002)
1274 static const char* dtmf_tones[] = {
1275 "!941+1336/50,!0/50", /* 0 */
1276 "!697+1209/50,!0/50", /* 1 */
1277 "!697+1336/50,!0/50", /* 2 */
1278 "!697+1477/50,!0/50", /* 3 */
1279 "!770+1209/50,!0/50", /* 4 */
1280 "!770+1336/50,!0/50", /* 5 */
1281 "!770+1477/50,!0/50", /* 6 */
1282 "!852+1209/50,!0/50", /* 7 */
1283 "!852+1336/50,!0/50", /* 8 */
1284 "!852+1477/50,!0/50", /* 9 */
1285 "!697+1633/50,!0/50", /* A */
1286 "!770+1633/50,!0/50", /* B */
1287 "!852+1633/50,!0/50", /* C */
1288 "!941+1633/50,!0/50", /* D */
1289 "!941+1209/50,!0/50", /* * */
1290 "!941+1477/50,!0/50" }; /* # */
1291 if (digit >= '0' && digit <='9')
1292 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1293 else if (digit >= 'A' && digit <= 'D')
1294 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1295 else if (digit == '*')
1296 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1297 else if (digit == '#')
1298 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1301 ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1308 int ast_prod(struct ast_channel *chan)
1310 struct ast_frame a = { AST_FRAME_VOICE };
1312 /* Send an empty audio frame to get things moving */
1313 if (chan->_state != AST_STATE_UP) {
1314 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1315 a.subclass = chan->pvt->rawwriteformat;
1316 a.data = nothing + AST_FRIENDLY_OFFSET;
1317 if (ast_write(chan, &a))
1318 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1323 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1326 if (!chan->pvt->write_video)
1328 res = ast_write(chan, fr);
1334 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1337 struct ast_frame *f = NULL;
1338 /* Stop if we're a zombie or need a soft hangup */
1339 ast_mutex_lock(&chan->lock);
1340 if (chan->zombie || ast_check_hangup(chan)) {
1341 ast_mutex_unlock(&chan->lock);
1344 /* Handle any pending masquerades */
1346 if (ast_do_masquerade(chan)) {
1347 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1348 ast_mutex_unlock(&chan->lock);
1353 ast_mutex_unlock(&chan->lock);
1356 if (chan->generatordata) {
1357 if (chan->writeinterrupt)
1358 ast_deactivate_generator(chan);
1360 ast_mutex_unlock(&chan->lock);
1364 if (chan->fout & 0x80000000)
1365 ast_frame_dump(chan->name, fr, ">>");
1366 CHECK_BLOCKING(chan);
1367 switch(fr->frametype) {
1368 case AST_FRAME_CONTROL:
1369 /* XXX Interpret control frames XXX */
1370 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1372 case AST_FRAME_DTMF:
1374 ast_mutex_unlock(&chan->lock);
1375 res = do_senddigit(chan,fr->subclass);
1376 ast_mutex_lock(&chan->lock);
1377 CHECK_BLOCKING(chan);
1379 case AST_FRAME_TEXT:
1380 if (chan->pvt->send_text)
1381 res = chan->pvt->send_text(chan, (char *) fr->data);
1383 case AST_FRAME_VIDEO:
1384 /* XXX Handle translation of video codecs one day XXX */
1385 if (chan->pvt->write_video)
1386 res = chan->pvt->write_video(chan, fr);
1391 if (chan->pvt->write) {
1392 if (chan->pvt->writetrans) {
1393 f = ast_translate(chan->pvt->writetrans, fr, 0);
1397 res = chan->pvt->write(chan, f);
1398 if( chan->monitor &&
1399 chan->monitor->write_stream &&
1400 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1401 #ifndef MONITOR_CONSTANT_DELAY
1402 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1404 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1405 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1406 chan->outsmpl += jump + 2 * f->samples;
1408 chan->outsmpl += f->samples;
1410 int jump = chan->insmpl - chan->outsmpl;
1411 if (jump - MONITOR_DELAY >= 0) {
1412 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1413 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1414 chan->outsmpl += jump;
1416 chan->outsmpl += f->samples;
1418 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1419 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1428 /* Consider a write failure to force a soft hangup */
1430 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1432 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1433 chan->fout &= 0x80000000;
1438 ast_mutex_unlock(&chan->lock);
1442 int ast_set_write_format(struct ast_channel *chan, int fmts)
1448 native = chan->nativeformats;
1451 res = ast_translator_best_choice(&native, &fmt);
1453 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1454 ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1458 /* Now we have a good choice for both. We'll write using our native format. */
1459 chan->pvt->rawwriteformat = native;
1460 /* User perspective is fmt */
1461 chan->writeformat = fmt;
1462 /* Free any write translation we have right now */
1463 if (chan->pvt->writetrans)
1464 ast_translator_free_path(chan->pvt->writetrans);
1465 /* Build a translation path from the user write format to the raw writing format */
1466 chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1468 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1472 int ast_set_read_format(struct ast_channel *chan, int fmts)
1478 native = chan->nativeformats;
1480 /* Find a translation path from the native read format to one of the user's read formats */
1481 res = ast_translator_best_choice(&fmt, &native);
1483 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1484 ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1488 /* Now we have a good choice for both. We'll write using our native format. */
1489 chan->pvt->rawreadformat = native;
1490 /* User perspective is fmt */
1491 chan->readformat = fmt;
1492 /* Free any read translation we have right now */
1493 if (chan->pvt->readtrans)
1494 ast_translator_free_path(chan->pvt->readtrans);
1495 /* Build a translation path from the raw read format to the user reading format */
1496 chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1498 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n",
1499 chan->name, ast_getformatname(chan->readformat));
1503 struct ast_channel *__ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid, struct outgoing_helper *oh)
1506 struct ast_channel *chan;
1507 struct ast_frame *f;
1509 chan = ast_request(type, format, data);
1515 /* FIXME replace this call with strsep NOT*/
1516 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1517 pbx_builtin_setvar( chan, var );
1519 if (oh->callerid && *oh->callerid)
1520 ast_set_callerid(chan, oh->callerid, 1);
1521 if (oh->account && *oh->account)
1522 ast_cdr_setaccount(chan, oh->account);
1524 if (callerid && strlen(callerid))
1525 ast_set_callerid(chan, callerid, 1);
1527 if (!ast_call(chan, data, 0)) {
1528 while(timeout && (chan->_state != AST_STATE_UP)) {
1529 res = ast_waitfor(chan, timeout);
1531 /* Something not cool, or timed out */
1534 /* If done, break out */
1541 state = AST_CONTROL_HANGUP;
1545 if (f->frametype == AST_FRAME_CONTROL) {
1546 if (f->subclass == AST_CONTROL_RINGING)
1547 state = AST_CONTROL_RINGING;
1548 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1549 state = f->subclass;
1552 } else if (f->subclass == AST_CONTROL_ANSWER) {
1553 state = f->subclass;
1557 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1563 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1565 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1569 if (oh->context && *oh->context)
1570 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1571 if (oh->exten && *oh->exten)
1572 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1573 chan->priority = oh->priority;
1575 if (chan->_state == AST_STATE_UP)
1576 state = AST_CONTROL_ANSWER;
1580 if (chan && res <= 0) {
1582 chan->cdr = ast_cdr_alloc();
1584 ast_cdr_init(chan->cdr, chan);
1588 sprintf(tmp, "%s/%s",type,(char *)data);
1589 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1590 ast_cdr_update(chan);
1591 ast_cdr_start(chan->cdr);
1592 ast_cdr_end(chan->cdr);
1593 /* If the cause wasn't handled properly */
1594 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1595 ast_cdr_failed(chan->cdr);
1597 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1604 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1606 return __ast_request_and_dial(type, format, data, timeout, outstate, callerid, NULL);
1609 struct ast_channel *ast_request(char *type, int format, void *data)
1611 struct chanlist *chan;
1612 struct ast_channel *c = NULL;
1616 if (ast_mutex_lock(&chlock)) {
1617 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1622 if (!strcasecmp(type, chan->type)) {
1623 capabilities = chan->capabilities;
1625 res = ast_translator_best_choice(&fmt, &capabilities);
1627 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1628 ast_mutex_unlock(&chlock);
1631 ast_mutex_unlock(&chlock);
1632 if (chan->requester)
1633 c = chan->requester(type, capabilities, data);
1635 if (c->_state == AST_STATE_DOWN) {
1636 manager_event(EVENT_FLAG_CALL, "Newchannel",
1641 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>", c->uniqueid);
1649 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1650 ast_mutex_unlock(&chlock);
1654 int ast_parse_device_state(char *device)
1656 char name[AST_CHANNEL_NAME] = "";
1658 struct ast_channel *chan;
1660 chan = ast_channel_walk(NULL);
1662 strncpy(name, chan->name, sizeof(name)-1);
1663 cut = strchr(name,'-');
1666 if (!strcmp(name, device))
1667 return AST_DEVICE_INUSE;
1668 chan = ast_channel_walk(chan);
1670 return AST_DEVICE_UNKNOWN;
1673 int ast_device_state(char *device)
1675 char tech[AST_MAX_EXTENSION] = "";
1677 struct chanlist *chanls;
1680 strncpy(tech, device, sizeof(tech)-1);
1681 number = strchr(tech, '/');
1683 return AST_DEVICE_INVALID;
1688 if (ast_mutex_lock(&chlock)) {
1689 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1694 if (!strcasecmp(tech, chanls->type)) {
1695 ast_mutex_unlock(&chlock);
1696 if (!chanls->devicestate)
1697 return ast_parse_device_state(device);
1699 res = chanls->devicestate(number);
1700 if (res == AST_DEVICE_UNKNOWN)
1701 return ast_parse_device_state(device);
1706 chanls = chanls->next;
1708 ast_mutex_unlock(&chlock);
1709 return AST_DEVICE_INVALID;
1712 int ast_call(struct ast_channel *chan, char *addr, int timeout)
1714 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
1715 If the remote end does not answer within the timeout, then do NOT hang up, but
1718 /* Stop if we're a zombie or need a soft hangup */
1719 ast_mutex_lock(&chan->lock);
1720 if (!chan->zombie && !ast_check_hangup(chan))
1721 if (chan->pvt->call)
1722 res = chan->pvt->call(chan, addr, timeout);
1723 ast_mutex_unlock(&chan->lock);
1727 int ast_transfer(struct ast_channel *chan, char *dest)
1729 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
1730 If the remote end does not answer within the timeout, then do NOT hang up, but
1733 /* Stop if we're a zombie or need a soft hangup */
1734 ast_mutex_lock(&chan->lock);
1735 if (!chan->zombie && !ast_check_hangup(chan)) {
1736 if (chan->pvt->transfer) {
1737 res = chan->pvt->transfer(chan, dest);
1743 ast_mutex_unlock(&chan->lock);
1747 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1752 /* XXX Merge with full version? XXX */
1753 /* Stop if we're a zombie or need a soft hangup */
1754 if (c->zombie || ast_check_hangup(c))
1760 d = ast_waitstream(c, AST_DIGIT_ANY);
1764 d = ast_waitfordigit(c, to);
1766 d = ast_waitfordigit(c, to);
1774 if (!strchr(enders, d))
1776 if (strchr(enders, d) || (pos >= len)) {
1786 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1791 /* Stop if we're a zombie or need a soft hangup */
1792 if (c->zombie || ast_check_hangup(c))
1798 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1802 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1804 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1816 if (!strchr(enders, d))
1818 if (strchr(enders, d) || (pos >= len)) {
1828 int ast_channel_supports_html(struct ast_channel *chan)
1830 if (chan->pvt->send_html)
1835 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1837 if (chan->pvt->send_html)
1838 return chan->pvt->send_html(chan, subclass, data, datalen);
1842 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1844 if (chan->pvt->send_html)
1845 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1849 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1854 peerf = peer->nativeformats;
1855 chanf = chan->nativeformats;
1856 res = ast_translator_best_choice(&peerf, &chanf);
1858 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1861 /* Set read format on channel */
1862 res = ast_set_read_format(chan, peerf);
1864 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1867 /* Set write format on peer channel */
1868 res = ast_set_write_format(peer, peerf);
1870 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1873 /* Now we go the other way */
1874 peerf = peer->nativeformats;
1875 chanf = chan->nativeformats;
1876 res = ast_translator_best_choice(&chanf, &peerf);
1878 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1881 /* Set writeformat on channel */
1882 res = ast_set_write_format(chan, chanf);
1884 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1887 /* Set read format on peer channel */
1888 res = ast_set_read_format(peer, chanf);
1890 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1896 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1898 struct ast_frame null = { AST_FRAME_NULL, };
1899 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1900 clone->name, original->name);
1901 if (original->masq) {
1902 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
1903 original->masq->name, original->name);
1907 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
1908 clone->name, clone->masqr->name);
1911 original->masq = clone;
1912 clone->masqr = original;
1913 /* XXX can't really hold the lock here, but at the same time, it' s
1914 not really safe not to XXX */
1915 ast_queue_frame(original, &null, 0);
1916 ast_queue_frame(clone, &null, 0);
1917 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
1921 void ast_change_name(struct ast_channel *chan, char *newname)
1924 strncpy(tmp, chan->name, 256);
1925 strncpy(chan->name, newname, sizeof(chan->name) - 1);
1926 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
1929 static int ast_do_masquerade(struct ast_channel *original)
1934 struct ast_var_t *varptr;
1935 struct ast_frame *cur, *prev;
1936 struct ast_channel_pvt *p;
1937 struct ast_channel *clone = original->masq;
1938 int rformat = original->readformat;
1939 int wformat = original->writeformat;
1946 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1947 clone->name, clone->_state, original->name, original->_state);
1949 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
1950 the clone channel into the original channel. Start by killing off the original
1951 channel's backend. I'm not sure we're going to keep this function, because
1952 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1954 /* We need the clone's lock, too */
1955 ast_mutex_lock(&clone->lock);
1957 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
1959 /* Having remembered the original read/write formats, we turn off any translation on either
1961 free_translation(clone);
1962 free_translation(original);
1965 /* Unlink the masquerade */
1966 original->masq = NULL;
1967 clone->masqr = NULL;
1969 /* Save the original name */
1970 strncpy(orig, original->name, sizeof(orig) - 1);
1971 /* Save the new name */
1972 strncpy(newn, clone->name, sizeof(newn) - 1);
1973 /* Create the masq name */
1974 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1976 /* Copy the name from the clone channel */
1977 strncpy(original->name, newn, sizeof(original->name)-1);
1979 /* Mangle the name of the clone channel */
1980 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1982 /* Notify any managers of the change, first the masq then the other */
1983 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1984 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1988 original->pvt = clone->pvt;
1991 /* Save any pending frames on both sides. Start by counting
1992 * how many we're going to need... */
1994 cur = clone->pvt->readq;
2001 /* If we had any, prepend them to the ones already in the queue, and
2002 * load up the alertpipe */
2004 prev->next = original->pvt->readq;
2005 original->pvt->readq = clone->pvt->readq;
2006 clone->pvt->readq = NULL;
2007 if (original->pvt->alertpipe[1] > -1) {
2009 write(original->pvt->alertpipe[1], &x, sizeof(x));
2012 clone->_softhangup = AST_SOFTHANGUP_DEV;
2015 if (clone->pvt->fixup){
2016 res = clone->pvt->fixup(original, clone);
2018 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2021 /* Start by disconnecting the original's physical side */
2022 if (clone->pvt->hangup)
2023 res = clone->pvt->hangup(clone);
2025 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2026 ast_mutex_unlock(&clone->lock);
2030 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2031 /* Mangle the name of the clone channel */
2032 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2033 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
2035 /* Keep the same language. */
2036 /* Update the type. */
2037 original->type = clone->type;
2039 for (x=0;x<AST_MAX_FDS;x++) {
2040 original->fds[x] = clone->fds[x];
2042 /* Append variables from clone channel into original channel */
2043 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2044 varptr = original->varshead.first;
2046 while(varptr->entries.next) {
2047 varptr = varptr->entries.next;
2049 varptr->entries.next = clone->varshead.first;
2051 original->varshead.first = clone->varshead.first;
2053 clone->varshead.first = NULL;
2054 /* Presense of ADSI capable CPE follows clone */
2055 original->adsicpe = clone->adsicpe;
2056 /* Bridge remains the same */
2057 /* CDR fields remain the same */
2058 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2059 /* Application and data remain the same */
2060 /* Clone exception becomes real one, as with fdno */
2061 original->exception = clone->exception;
2062 original->fdno = clone->fdno;
2063 /* Schedule context remains the same */
2064 /* Stream stuff stays the same */
2065 /* Keep the original state. The fixup code will need to work with it most likely */
2067 /* dnid and callerid change to become the new, HOWEVER, we also link the original's
2068 fields back into the defunct 'clone' so that they will be freed when
2069 ast_frfree is eventually called */
2070 tmp = original->dnid;
2071 original->dnid = clone->dnid;
2074 tmp = original->callerid;
2075 original->callerid = clone->callerid;
2076 clone->callerid = tmp;
2078 /* Restore original timing file descriptor */
2079 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2081 /* Our native formats are different now */
2082 original->nativeformats = clone->nativeformats;
2084 /* And of course, so does our current state. Note we need not
2085 call ast_setstate since the event manager doesn't really consider
2087 original->_state = clone->_state;
2089 /* Context, extension, priority, app data, jump table, remain the same */
2090 /* pvt switches. pbx stays the same, as does next */
2092 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2093 a zombie so nothing tries to touch it. If it's already been marked as a
2094 zombie, then free it now (since it already is considered invalid). */
2095 if (clone->zombie) {
2096 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2097 ast_mutex_unlock(&clone->lock);
2098 ast_channel_free(clone);
2099 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2101 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2103 ast_mutex_unlock(&clone->lock);
2105 /* Set the write format */
2106 ast_set_write_format(original, wformat);
2108 /* Set the read format */
2109 ast_set_read_format(original, rformat);
2111 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2113 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2114 can fix up everything as best as possible */
2115 if (original->pvt->fixup) {
2116 res = original->pvt->fixup(clone, original);
2118 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2119 original->type, original->name);
2123 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2124 original->type, original->name);
2125 /* Signal any blocker */
2126 if (original->blocking)
2127 pthread_kill(original->blocker, SIGURG);
2128 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2129 original->name, original->_state);
2133 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
2136 free(chan->callerid);
2137 if (anitoo && chan->ani)
2140 chan->callerid = strdup(callerid);
2142 chan->ani = strdup(callerid);
2144 chan->callerid = NULL;
2149 ast_cdr_setcid(chan->cdr, chan);
2150 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2154 chan->name, chan->callerid ?
2155 chan->callerid : "<Unknown>",
2159 int ast_setstate(struct ast_channel *chan, int state)
2161 if (chan->_state != state) {
2162 int oldstate = chan->_state;
2163 chan->_state = state;
2164 if (oldstate == AST_STATE_DOWN) {
2165 ast_device_state_changed(chan->name);
2166 manager_event(EVENT_FLAG_CALL, "Newchannel",
2171 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2173 manager_event(EVENT_FLAG_CALL, "Newstate",
2178 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2184 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2186 /* Copy voice back and forth between the two channels. Give the peer
2187 the ability to transfer calls with '#<extension' syntax. */
2188 struct ast_channel *cs[3];
2190 struct ast_frame *f;
2191 struct ast_channel *who = NULL;
2195 /* Stop if we're a zombie or need a soft hangup */
2196 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1))
2199 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2200 c0->name, c0->bridge->name);
2204 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2205 c1->name, c1->bridge->name);
2209 /* Keep track of bridge */
2215 manager_event(EVENT_FLAG_CALL, "Link",
2218 c0->name, c1->name);
2220 for (/* ever */;;) {
2221 /* Stop if we're a zombie or need a soft hangup */
2222 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1)) {
2226 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");
2229 if (c0->pvt->bridge &&
2230 (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2231 /* Looks like they share a bridge code */
2232 if (option_verbose > 2)
2233 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2234 if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2237 manager_event(EVENT_FLAG_CALL, "Unlink",
2240 c0->name, c1->name);
2241 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2244 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
2245 my not wanting to bridge */
2246 if ((res != -2) && (res != -3))
2247 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2248 if (res != -3) nativefailed++;
2252 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
2253 !(c0->generator || c1->generator)) {
2254 if (ast_channel_make_compatible(c0, c1)) {
2255 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2256 manager_event(EVENT_FLAG_CALL, "Unlink",
2259 c0->name, c1->name);
2263 who = ast_waitfor_n(cs, 2, &to);
2265 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2273 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2277 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2281 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL frame on channel %s\n",who->name);
2284 if ((f->frametype == AST_FRAME_VOICE) ||
2285 (f->frametype == AST_FRAME_TEXT) ||
2286 (f->frametype == AST_FRAME_VIDEO) ||
2287 (f->frametype == AST_FRAME_IMAGE) ||
2288 (f->frametype == AST_FRAME_DTMF)) {
2289 if ((f->frametype == AST_FRAME_DTMF) &&
2290 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2292 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2295 /* Take out of conference mode */
2297 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2303 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2307 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2314 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2316 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2320 /* Don't copy packets if there is a generator on either one, since they're
2321 not supposed to be listening anyway */
2330 /* Swap who gets priority */
2337 manager_event(EVENT_FLAG_CALL, "Unlink",
2340 c0->name, c1->name);
2341 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2345 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2348 if (chan->pvt->setoption) {
2349 res = chan->pvt->setoption(chan, option, data, datalen);
2357 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2358 intermediate packets. XXX */
2359 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2365 struct tonepair_def {
2372 struct tonepair_state {
2380 unsigned char offset[AST_FRIENDLY_OFFSET];
2384 static void tonepair_release(struct ast_channel *chan, void *params)
2386 struct tonepair_state *ts = params;
2388 ast_set_write_format(chan, ts->origwfmt);
2393 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2395 struct tonepair_state *ts;
2396 struct tonepair_def *td = params;
2397 ts = malloc(sizeof(struct tonepair_state));
2400 memset(ts, 0, sizeof(struct tonepair_state));
2401 ts->origwfmt = chan->writeformat;
2402 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2403 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2404 tonepair_release(NULL, ts);
2407 ts->freq1 = td->freq1;
2408 ts->freq2 = td->freq2;
2409 ts->duration = td->duration;
2412 /* Let interrupts interrupt :) */
2413 chan->writeinterrupt = 1;
2417 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2419 struct tonepair_state *ts = data;
2422 /* we need to prepare a frame with 16 * timelen samples as we're
2423 * generating SLIN audio
2427 if (len > sizeof(ts->data) / 2 - 1) {
2428 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2431 memset(&ts->f, 0, sizeof(ts->f));
2432 for (x=0;x<len/2;x++) {
2433 ts->data[x] = ts->vol * (
2434 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2435 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2438 ts->f.frametype = AST_FRAME_VOICE;
2439 ts->f.subclass = AST_FORMAT_SLINEAR;
2440 ts->f.datalen = len;
2441 ts->f.samples = samples;
2442 ts->f.offset = AST_FRIENDLY_OFFSET;
2443 ts->f.data = ts->data;
2444 ast_write(chan, &ts->f);
2446 if (ts->duration > 0) {
2447 if (ts->pos >= ts->duration * 8)
2453 static struct ast_generator tonepair = {
2454 alloc: tonepair_alloc,
2455 release: tonepair_release,
2456 generate: tonepair_generator,
2459 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2461 struct tonepair_def d = { 0, };
2464 d.duration = duration;
2469 if (ast_activate_generator(chan, &tonepair, &d))
2474 void ast_tonepair_stop(struct ast_channel *chan)
2476 ast_deactivate_generator(chan);
2479 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2481 struct ast_frame *f;
2483 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2486 /* Give us some wiggle room */
2487 while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {