2 * Asterisk -- A telephony toolkit for Linux.
6 * Copyright (C) 1999 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
21 #include <math.h> /* For PI */
22 #include "asterisk/pbx.h"
23 #include "asterisk/frame.h"
24 #include "asterisk/sched.h"
25 #include "asterisk/options.h"
26 #include "asterisk/channel.h"
27 #include "asterisk/musiconhold.h"
28 #include "asterisk/logger.h"
29 #include "asterisk/say.h"
30 #include "asterisk/file.h"
31 #include "asterisk/cli.h"
32 #include "asterisk/translate.h"
33 #include "asterisk/manager.h"
34 #include "asterisk/chanvars.h"
35 #include "asterisk/linkedlists.h"
36 #include "asterisk/indications.h"
37 #include "asterisk/monitor.h"
38 #include "asterisk/causes.h"
39 #include "asterisk/utils.h"
40 #include "asterisk/lock.h"
41 #include "asterisk/app.h"
42 #include "asterisk/transcap.h"
43 #ifdef ZAPTEL_OPTIMIZATIONS
44 #include <sys/ioctl.h>
46 #include <linux/zaptel.h>
49 #endif /* __linux__ */
51 #error "You need newer zaptel! Please cvs update zaptel"
56 /* uncomment if you have problems with 'monitoring' synchronized files */
58 #define MONITOR_CONSTANT_DELAY
59 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
62 static int shutting_down = 0;
63 static int uniqueint = 0;
65 unsigned long global_fin = 0, global_fout = 0;
67 /* XXX Lock appropriately in more functions XXX */
70 const struct ast_channel_tech *tech;
71 struct chanlist *next;
73 struct ast_channel *channels = NULL;
75 /* Protect the channel list (highly unlikely that two things would change
76 it at the same time, but still! */
78 AST_MUTEX_DEFINE_STATIC(chlock);
80 static int show_channeltypes(int fd, int argc, char *argv[])
82 #define FORMAT "%-7.7s %-50.50s\n"
83 struct chanlist *cl = backends;
84 ast_cli(fd, FORMAT, "Type", "Description");
85 ast_cli(fd, FORMAT, "------", "-----------");
86 if (ast_mutex_lock(&chlock)) {
87 ast_log(LOG_WARNING, "Unable to lock channel list\n");
91 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description);
94 ast_mutex_unlock(&chlock);
95 return RESULT_SUCCESS;
99 static char show_channeltypes_usage[] =
100 "Usage: show channeltypes\n"
101 " Shows available channel types registered in your Asterisk server.\n";
103 static struct ast_cli_entry cli_show_channeltypes =
104 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
106 int ast_check_hangup(struct ast_channel *chan)
110 /* if soft hangup flag, return true */
111 if (chan->_softhangup) return 1;
112 /* if no technology private data, return true */
113 if (!chan->tech_pvt) return 1;
114 /* if no hangup scheduled, just return here */
115 if (!chan->whentohangup) return 0;
116 time(&myt); /* get current time */
117 /* return, if not yet */
118 if (chan->whentohangup > myt) return 0;
119 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
123 static int ast_check_hangup_locked(struct ast_channel *chan)
126 ast_mutex_lock(&chan->lock);
127 res = ast_check_hangup(chan);
128 ast_mutex_unlock(&chan->lock);
132 void ast_begin_shutdown(int hangup)
134 struct ast_channel *c;
137 ast_mutex_lock(&chlock);
140 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
143 ast_mutex_unlock(&chlock);
147 int ast_active_channels(void)
149 struct ast_channel *c;
151 ast_mutex_lock(&chlock);
157 ast_mutex_unlock(&chlock);
161 void ast_cancel_shutdown(void)
166 int ast_shutting_down(void)
168 return shutting_down;
171 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
177 chan->whentohangup = myt + offset;
179 chan->whentohangup = 0;
183 int ast_channel_register(const struct ast_channel_tech *tech)
185 struct chanlist *chan;
187 ast_mutex_lock(&chlock);
191 if (!strcasecmp(tech->type, chan->tech->type)) {
192 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
193 ast_mutex_unlock(&chlock);
199 chan = malloc(sizeof(*chan));
201 ast_log(LOG_WARNING, "Out of memory\n");
202 ast_mutex_unlock(&chlock);
206 chan->next = backends;
210 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
212 if (option_verbose > 1)
213 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
214 chan->tech->description);
216 ast_mutex_unlock(&chlock);
220 char *ast_state2str(int state)
222 /* XXX Not reentrant XXX */
223 static char localtmp[256];
227 case AST_STATE_RESERVED:
229 case AST_STATE_OFFHOOK:
231 case AST_STATE_DIALING:
235 case AST_STATE_RINGING:
242 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
247 char *ast_transfercapability2str(int transfercapability)
249 switch(transfercapability) {
250 case AST_TRANS_CAP_SPEECH:
252 case AST_TRANS_CAP_DIGITAL:
254 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
255 return "RESTRICTED_DIGITAL";
256 case AST_TRANS_CAP_3_1K_AUDIO:
258 case AST_TRANS_CAP_DIGITAL_W_TONES:
259 return "DIGITAL_W_TONES";
260 case AST_TRANS_CAP_VIDEO:
267 int ast_best_codec(int fmts)
269 /* This just our opinion, expressed in code. We are asked to choose
270 the best codec to use, given no information */
274 /* Okay, ulaw is used by all telephony equipment, so start with it */
276 /* Unless of course, you're a silly European, so then prefer ALAW */
278 /* Okay, well, signed linear is easy to translate into other stuff */
280 /* G.726 is standard ADPCM */
282 /* ADPCM has great sound quality and is still pretty easy to translate */
284 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
285 translate and sounds pretty good */
287 /* iLBC is not too bad */
289 /* Speex is free, but computationally more expensive than GSM */
291 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
294 /* G.729a is faster than 723 and slightly less expensive */
296 /* Down to G.723.1 which is proprietary but at least designed for voice */
301 for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
304 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
308 static const struct ast_channel_tech null_tech = {
310 .description = "Null channel (should not see this)",
313 struct ast_channel *ast_channel_alloc(int needqueue)
315 struct ast_channel *tmp;
318 struct varshead *headp;
321 /* If shutting down, don't allocate any new channels */
325 tmp = malloc(sizeof(struct ast_channel));
327 ast_log(LOG_WARNING, "Out of memory\n");
331 memset(tmp, 0, sizeof(struct ast_channel));
332 tmp->sched = sched_context_create();
334 ast_log(LOG_WARNING, "Unable to create schedule context\n");
339 for (x=0;x<AST_MAX_FDS - 1;x++)
342 #ifdef ZAPTEL_OPTIMIZATIONS
343 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
344 if (tmp->timingfd > -1) {
345 /* Check if timing interface supports new
348 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
356 if (pipe(tmp->alertpipe)) {
357 ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
361 flags = fcntl(tmp->alertpipe[0], F_GETFL);
362 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
363 flags = fcntl(tmp->alertpipe[1], F_GETFL);
364 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
367 /* Make sure we've got it done right if they don't */
368 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
370 /* Always watch the alertpipe */
371 tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
372 /* And timing pipe */
373 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
374 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
376 tmp->_state = AST_STATE_DOWN;
380 tmp->fin = global_fin;
381 tmp->fout = global_fout;
382 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
383 headp = &tmp->varshead;
384 ast_mutex_init(&tmp->lock);
385 AST_LIST_HEAD_INIT(headp);
386 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
387 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
388 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
390 tmp->amaflags = ast_default_amaflags;
391 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
393 tmp->tech = &null_tech;
395 ast_mutex_lock(&chlock);
396 tmp->next = channels;
399 ast_mutex_unlock(&chlock);
403 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
406 struct ast_frame *prev, *cur;
409 /* Build us a copy and free the original one */
412 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
415 ast_mutex_lock(&chan->lock);
419 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
420 /* Don't bother actually queueing anything after a hangup */
422 ast_mutex_unlock(&chan->lock);
429 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
430 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
431 if (fin->frametype != AST_FRAME_VOICE) {
432 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
435 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
437 ast_mutex_unlock(&chan->lock);
445 if (chan->alertpipe[1] > -1) {
446 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
447 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
448 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
449 #ifdef ZAPTEL_OPTIMIZATIONS
450 } else if (chan->timingfd > -1) {
451 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
453 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
454 pthread_kill(chan->blocker, SIGURG);
456 ast_mutex_unlock(&chan->lock);
460 int ast_queue_hangup(struct ast_channel *chan)
462 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
463 chan->_softhangup |= AST_SOFTHANGUP_DEV;
464 return ast_queue_frame(chan, &f);
467 int ast_queue_control(struct ast_channel *chan, int control)
469 struct ast_frame f = { AST_FRAME_CONTROL, };
470 f.subclass = control;
471 return ast_queue_frame(chan, &f);
474 int ast_channel_defer_dtmf(struct ast_channel *chan)
478 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
479 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
484 void ast_channel_undefer_dtmf(struct ast_channel *chan)
487 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
490 struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
492 /* Returns next channel (locked) */
493 struct ast_channel *l, *ret;
497 ast_mutex_lock(&chlock);
501 if (ast_mutex_trylock(&l->lock)) {
503 ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
505 ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
506 ast_mutex_unlock(&chlock);
515 ast_mutex_unlock(&chlock);
524 if (ast_mutex_trylock(&ret->lock)) {
526 ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
528 ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
529 ast_mutex_unlock(&chlock);
538 ast_mutex_unlock(&chlock);
543 struct ast_channel *ast_get_channel_by_name_locked(char *channame)
545 struct ast_channel *chan;
546 chan = ast_channel_walk_locked(NULL);
548 if (!strcasecmp(chan->name, channame))
550 ast_mutex_unlock(&chan->lock);
551 chan = ast_channel_walk_locked(chan);
556 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
557 int (*cond)(void*), void *data )
562 if( cond && ((*cond)(data) == 0 ) )
564 ms = ast_waitfor(chan, ms);
577 int ast_safe_sleep(struct ast_channel *chan, int ms)
581 ms = ast_waitfor(chan, ms);
594 static void free_cid(struct ast_callerid *cid)
605 free(cid->cid_rdnis);
608 void ast_channel_free(struct ast_channel *chan)
610 struct ast_channel *last=NULL, *cur;
612 struct ast_var_t *vardata;
613 struct ast_frame *f, *fp;
614 struct varshead *headp;
615 char name[AST_CHANNEL_NAME];
617 headp=&chan->varshead;
619 ast_mutex_lock(&chlock);
624 last->next = cur->next;
626 channels = cur->next;
633 ast_log(LOG_WARNING, "Unable to find channel in list\n");
635 /* Lock and unlock the channel just to be sure nobody
636 has it locked still */
637 ast_mutex_lock(&cur->lock);
638 ast_mutex_unlock(&cur->lock);
640 if (chan->tech_pvt) {
641 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
642 free(chan->tech_pvt);
645 strncpy(name, chan->name, sizeof(name)-1);
647 /* Stop monitoring */
649 chan->monitor->stop( chan, 0 );
652 /* If there is native format music-on-hold state, free it */
653 if(chan->music_state)
654 ast_moh_cleanup(chan);
656 /* Free translatosr */
658 ast_translator_free_path(chan->readtrans);
659 if (chan->writetrans)
660 ast_translator_free_path(chan->writetrans);
662 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
663 free_cid(&chan->cid);
664 ast_mutex_destroy(&chan->lock);
665 /* Close pipes if appropriate */
666 if ((fd = chan->alertpipe[0]) > -1)
668 if ((fd = chan->alertpipe[1]) > -1)
670 if ((fd = chan->timingfd) > -1)
680 /* loop over the variables list, freeing all data and deleting list items */
681 /* no need to lock the list, as the channel is already locked */
683 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
684 vardata = AST_LIST_REMOVE_HEAD(headp, entries);
685 /* printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata)); */
686 ast_var_delete(vardata);
690 ast_mutex_unlock(&chlock);
692 ast_device_state_changed(name);
695 static void ast_spy_detach(struct ast_channel *chan)
697 struct ast_channel_spy *chanspy;
701 for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
702 if (chanspy->status == CHANSPY_RUNNING) {
703 chanspy->status = CHANSPY_DONE;
707 /* signal all the spys to get lost and allow them time to unhook themselves
708 god help us if they don't......
710 while (chan->spiers && to >= 0) {
711 ast_safe_sleep(chan, sleepms);
718 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
721 struct ast_frame f = { AST_FRAME_NULL };
723 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
724 /* Inform channel driver that we need to be hung up, if it cares */
725 chan->_softhangup |= cause;
726 ast_queue_frame(chan, &f);
727 /* Interrupt any poll call or such */
728 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
729 pthread_kill(chan->blocker, SIGURG);
733 int ast_softhangup(struct ast_channel *chan, int cause)
736 ast_mutex_lock(&chan->lock);
737 res = ast_softhangup_nolock(chan, cause);
738 ast_mutex_unlock(&chan->lock);
742 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos)
744 struct ast_frame *tmpf = NULL;
747 ast_mutex_lock(&spy->lock);
748 for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
752 struct ast_frame *freef, *headf;
754 ast_log(LOG_ERROR, "Too Many frames queued at once, flushing cache.\n");
755 headf = spy->queue[pos];
756 /* deref the queue right away so it looks empty */
757 spy->queue[pos] = NULL;
759 /* free the wasted frames */
765 ast_mutex_unlock(&spy->lock);
770 tmpf->next = ast_frdup(f);
772 spy->queue[pos] = ast_frdup(f);
775 ast_mutex_unlock(&spy->lock);
778 static void free_translation(struct ast_channel *clone)
780 if (clone->writetrans)
781 ast_translator_free_path(clone->writetrans);
782 if (clone->readtrans)
783 ast_translator_free_path(clone->readtrans);
784 clone->writetrans = NULL;
785 clone->readtrans = NULL;
786 clone->rawwriteformat = clone->nativeformats;
787 clone->rawreadformat = clone->nativeformats;
790 int ast_hangup(struct ast_channel *chan)
793 /* Don't actually hang up a channel that will masquerade as someone else, or
794 if someone is going to masquerade as us */
795 ast_mutex_lock(&chan->lock);
797 /* get rid of spies */
798 ast_spy_detach(chan);
801 if (ast_do_masquerade(chan))
802 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
806 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
807 ast_mutex_unlock(&chan->lock);
810 /* If this channel is one which will be masqueraded into something,
811 mark it as a zombie already, so we know to free it later */
813 ast_set_flag(chan, AST_FLAG_ZOMBIE);
814 ast_mutex_unlock(&chan->lock);
817 free_translation(chan);
819 ast_closestream(chan->stream);
821 ast_closestream(chan->vstream);
823 sched_context_destroy(chan->sched);
824 /* Clear any tone stuff remaining */
825 if (chan->generatordata)
826 chan->generator->release(chan, chan->generatordata);
827 chan->generatordata = NULL;
828 chan->generator = NULL;
830 /* End the CDR if it hasn't already */
831 ast_cdr_end(chan->cdr);
832 /* Post and Free the CDR */
833 ast_cdr_post(chan->cdr);
834 ast_cdr_free(chan->cdr);
836 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
837 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
838 "is blocked by thread %ld in procedure %s! Expect a failure\n",
839 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
842 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
844 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
845 if (chan->tech->hangup)
846 res = chan->tech->hangup(chan);
849 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
851 ast_mutex_unlock(&chan->lock);
852 manager_event(EVENT_FLAG_CALL, "Hangup",
856 chan->name, chan->uniqueid, chan->hangupcause);
857 ast_channel_free(chan);
861 void ast_channel_unregister(const struct ast_channel_tech *tech)
863 struct chanlist *chan, *last=NULL;
866 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
868 ast_mutex_lock(&chlock);
872 if (chan->tech == tech) {
874 last->next = chan->next;
876 backends = backends->next;
878 ast_mutex_unlock(&chlock);
880 if (option_verbose > 1)
881 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
889 ast_mutex_unlock(&chlock);
892 int ast_answer(struct ast_channel *chan)
895 ast_mutex_lock(&chan->lock);
896 /* Stop if we're a zombie or need a soft hangup */
897 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
898 ast_mutex_unlock(&chan->lock);
901 switch(chan->_state) {
902 case AST_STATE_RINGING:
904 if (chan->tech->answer)
905 res = chan->tech->answer(chan);
906 ast_setstate(chan, AST_STATE_UP);
908 ast_cdr_answer(chan->cdr);
909 ast_mutex_unlock(&chan->lock);
914 ast_cdr_answer(chan->cdr);
917 ast_mutex_unlock(&chan->lock);
923 void ast_deactivate_generator(struct ast_channel *chan)
925 ast_mutex_lock(&chan->lock);
926 if (chan->generatordata) {
927 if (chan->generator && chan->generator->release)
928 chan->generator->release(chan, chan->generatordata);
929 chan->generatordata = NULL;
930 chan->generator = NULL;
931 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
932 ast_settimeout(chan, 0, NULL, NULL);
934 ast_mutex_unlock(&chan->lock);
937 static int generator_force(void *data)
939 /* Called if generator doesn't have data */
942 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
943 struct ast_channel *chan = data;
944 tmp = chan->generatordata;
945 chan->generatordata = NULL;
946 generate = chan->generator->generate;
947 res = generate(chan, tmp, 0, 160);
948 chan->generatordata = tmp;
950 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
951 ast_deactivate_generator(chan);
956 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
959 ast_mutex_lock(&chan->lock);
960 if (chan->generatordata) {
961 if (chan->generator && chan->generator->release)
962 chan->generator->release(chan, chan->generatordata);
963 chan->generatordata = NULL;
966 if ((chan->generatordata = gen->alloc(chan, params))) {
967 ast_settimeout(chan, 160, generator_force, chan);
968 chan->generator = gen;
972 ast_mutex_unlock(&chan->lock);
976 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
978 /* Wait for x amount of time on a file descriptor to have input. */
979 struct timeval start, now;
986 pfds = alloca(sizeof(struct pollfd) * n);
988 ast_log(LOG_ERROR, "Out of memory\n");
992 gettimeofday(&start, NULL);
997 pfds[y].events = POLLIN | POLLPRI;
1001 res = poll(pfds, y, *ms);
1003 /* Simulate a timeout if we were interrupted */
1013 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1026 gettimeofday(&now, NULL);
1027 passed = (now.tv_sec - start.tv_sec) * 1000;
1028 passed += (now.tv_usec - start.tv_usec) / 1000;
1037 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1038 int *exception, int *outfd, int *ms)
1040 /* Wait for x amount of time on a file descriptor to have input. */
1041 struct timeval start, end;
1042 struct pollfd *pfds;
1048 long whentohangup = 0, havewhen = 0, diff;
1049 struct ast_channel *winner = NULL;
1051 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1053 ast_log(LOG_ERROR, "Out of memory\n");
1063 /* Perform any pending masquerades */
1065 ast_mutex_lock(&c[x]->lock);
1066 if (c[x]->whentohangup) {
1069 diff = c[x]->whentohangup - now;
1070 if (!havewhen || (diff < whentohangup)) {
1072 whentohangup = diff;
1076 if (ast_do_masquerade(c[x])) {
1077 ast_log(LOG_WARNING, "Masquerade failed\n");
1079 ast_mutex_unlock(&c[x]->lock);
1083 ast_mutex_unlock(&c[x]->lock);
1089 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1090 rms = whentohangup * 1000;
1095 for (y=0;y<AST_MAX_FDS;y++) {
1096 if (c[x]->fds[y] > -1) {
1097 pfds[max].fd = c[x]->fds[y];
1098 pfds[max].events = POLLIN | POLLPRI;
1102 CHECK_BLOCKING(c[x]);
1104 for (x=0;x<nfds; x++) {
1106 pfds[max].fd = fds[x];
1107 pfds[max].events = POLLIN | POLLPRI;
1112 gettimeofday(&start, NULL);
1113 res = poll(pfds, max, rms);
1116 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1117 /* Simulate a timeout if we were interrupted */
1121 /* Just an interrupt */
1133 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1134 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1135 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1139 for (y=0;y<AST_MAX_FDS;y++) {
1140 if (c[x]->fds[y] > -1) {
1141 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1143 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1145 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1152 for (x=0;x<nfds;x++) {
1154 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1169 gettimeofday(&end, NULL);
1170 diff = (end.tv_sec - start.tv_sec) * 1000;
1171 diff += (end.tv_usec - start.tv_usec) / 1000;
1180 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1182 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1185 int ast_waitfor(struct ast_channel *c, int ms)
1187 struct ast_channel *chan;
1189 chan = ast_waitfor_n(&c, 1, &ms);
1199 char ast_waitfordigit(struct ast_channel *c, int ms)
1201 /* XXX Should I be merged with waitfordigit_full XXX */
1202 struct ast_frame *f;
1204 /* Stop if we're a zombie or need a soft hangup */
1205 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1207 /* Wait for a digit, no more than ms milliseconds total. */
1208 while(ms && !result) {
1209 ms = ast_waitfor(c, ms);
1210 if (ms < 0) /* Error */
1213 /* Read something */
1216 if (f->frametype == AST_FRAME_DTMF)
1217 result = f->subclass;
1226 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1229 #ifdef ZAPTEL_OPTIMIZATIONS
1230 if (c->timingfd > -1) {
1235 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1236 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1237 c->timingfunc = func;
1238 c->timingdata = data;
1243 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1245 struct ast_frame *f;
1246 struct ast_channel *rchan;
1249 /* Stop if we're a zombie or need a soft hangup */
1250 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1252 /* Wait for a digit, no more than ms milliseconds total. */
1254 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1255 if ((!rchan) && (outfd < 0) && (ms)) {
1258 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1260 } else if (outfd > -1) {
1261 /* The FD we were watching has something waiting */
1269 switch(f->frametype) {
1270 case AST_FRAME_DTMF:
1274 case AST_FRAME_CONTROL:
1275 switch(f->subclass) {
1276 case AST_CONTROL_HANGUP:
1279 case AST_CONTROL_RINGING:
1280 case AST_CONTROL_ANSWER:
1284 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1286 case AST_FRAME_VOICE:
1287 /* Write audio if appropriate */
1289 write(audiofd, f->data, f->datalen);
1295 return 0; /* Time is up */
1298 struct ast_frame *ast_read(struct ast_channel *chan)
1300 struct ast_frame *f = NULL;
1303 #ifdef ZAPTEL_OPTIMIZATIONS
1304 int (*func)(void *);
1308 static struct ast_frame null_frame =
1313 ast_mutex_lock(&chan->lock);
1315 if (ast_do_masquerade(chan)) {
1316 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1320 ast_mutex_unlock(&chan->lock);
1324 /* Stop if we're a zombie or need a soft hangup */
1325 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1326 if (chan->generator)
1327 ast_deactivate_generator(chan);
1328 ast_mutex_unlock(&chan->lock);
1331 prestate = chan->_state;
1333 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1334 /* We have DTMF that has been deferred. Return it now */
1335 chan->dtmff.frametype = AST_FRAME_DTMF;
1336 chan->dtmff.subclass = chan->dtmfq[0];
1337 /* Drop first digit */
1338 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1339 ast_mutex_unlock(&chan->lock);
1340 return &chan->dtmff;
1343 /* Read and ignore anything on the alertpipe, but read only
1344 one sizeof(blah) per frame that we send from it */
1345 if (chan->alertpipe[0] > -1) {
1346 read(chan->alertpipe[0], &blah, sizeof(blah));
1348 #ifdef ZAPTEL_OPTIMIZATIONS
1349 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1350 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1352 /* IF we can't get event, assume it's an expired as-per the old interface */
1353 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1355 blah = ZT_EVENT_TIMER_EXPIRED;
1357 if (blah == ZT_EVENT_TIMER_PING) {
1359 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1361 if (!chan->readq || !chan->readq->next) {
1362 /* Acknowledge PONG unless we need it again */
1364 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1366 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1367 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1370 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1371 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1372 func = chan->timingfunc;
1373 data = chan->timingdata;
1374 ast_mutex_unlock(&chan->lock);
1377 ast_log(LOG_DEBUG, "Calling private function\n");
1382 ast_mutex_lock(&chan->lock);
1383 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1384 chan->timingdata = NULL;
1385 ast_mutex_unlock(&chan->lock);
1390 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1393 /* Check for pending read queue */
1396 chan->readq = f->next;
1397 /* Interpret hangup and return NULL */
1398 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1403 chan->blocker = pthread_self();
1404 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1405 if (chan->tech->exception)
1406 f = chan->tech->exception(chan);
1408 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1411 /* Clear the exception flag */
1412 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1414 if (chan->tech->read)
1415 f = chan->tech->read(chan);
1417 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1421 if (f && (f->frametype == AST_FRAME_VOICE)) {
1422 if (!(f->subclass & chan->nativeformats)) {
1423 /* This frame can't be from the current native formats -- drop it on the
1425 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));
1430 struct ast_channel_spy *spying;
1431 for (spying = chan->spiers; spying; spying=spying->next) {
1432 ast_queue_spy_frame(spying, f, 0);
1435 if (chan->monitor && chan->monitor->read_stream ) {
1436 #ifndef MONITOR_CONSTANT_DELAY
1437 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1439 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1440 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1441 chan->insmpl += jump + 2 * f->samples;
1443 chan->insmpl+= f->samples;
1445 int jump = chan->outsmpl - chan->insmpl;
1446 if (jump - MONITOR_DELAY >= 0) {
1447 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1448 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1449 chan->insmpl += jump;
1451 chan->insmpl += f->samples;
1453 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1454 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1456 if (chan->readtrans) {
1457 f = ast_translate(chan->readtrans, f, 1);
1464 /* Make sure we always return NULL in the future */
1466 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1467 if (chan->generator)
1468 ast_deactivate_generator(chan);
1469 /* End the CDR if appropriate */
1471 ast_cdr_end(chan->cdr);
1472 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1473 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1474 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1476 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1478 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1479 if (prestate == AST_STATE_UP) {
1480 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1483 /* Answer the CDR */
1484 ast_setstate(chan, AST_STATE_UP);
1485 ast_cdr_answer(chan->cdr);
1488 /* Run any generator sitting on the line */
1489 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1490 /* Mask generator data temporarily and apply. If there is a timing function, it
1491 will be calling the generator instead */
1494 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1495 if (chan->timingfunc) {
1496 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1497 ast_settimeout(chan, 0, NULL, NULL);
1499 tmp = chan->generatordata;
1500 chan->generatordata = NULL;
1501 generate = chan->generator->generate;
1502 res = generate(chan, tmp, f->datalen, f->samples);
1503 chan->generatordata = tmp;
1505 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1506 ast_deactivate_generator(chan);
1508 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1509 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1510 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1511 ast_settimeout(chan, 160, generator_force, chan);
1514 if (chan->fin & 0x80000000)
1515 ast_frame_dump(chan->name, f, "<<");
1516 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1517 chan->fin &= 0x80000000;
1520 ast_mutex_unlock(&chan->lock);
1524 int ast_indicate(struct ast_channel *chan, int condition)
1527 /* Stop if we're a zombie or need a soft hangup */
1528 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1530 ast_mutex_lock(&chan->lock);
1531 if (chan->tech->indicate)
1532 res = chan->tech->indicate(chan, condition);
1533 ast_mutex_unlock(&chan->lock);
1534 if (!chan->tech->indicate || res) {
1536 * Device does not support (that) indication, lets fake
1537 * it by doing our own tone generation. (PM2002)
1539 if (condition >= 0) {
1540 const struct tone_zone_sound *ts = NULL;
1541 switch (condition) {
1542 case AST_CONTROL_RINGING:
1543 ts = ast_get_indication_tone(chan->zone, "ring");
1545 case AST_CONTROL_BUSY:
1546 ts = ast_get_indication_tone(chan->zone, "busy");
1548 case AST_CONTROL_CONGESTION:
1549 ts = ast_get_indication_tone(chan->zone, "congestion");
1552 if (ts && ts->data[0]) {
1553 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1554 ast_playtones_start(chan,0,ts->data, 1);
1556 } else if (condition == AST_CONTROL_PROGRESS) {
1557 /* ast_playtones_stop(chan); */
1558 } else if (condition == AST_CONTROL_PROCEEDING) {
1559 /* Do nothing, really */
1560 } else if (condition == AST_CONTROL_HOLD) {
1561 /* Do nothing.... */
1562 } else if (condition == AST_CONTROL_UNHOLD) {
1563 /* Do nothing.... */
1566 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1570 else ast_playtones_stop(chan);
1575 int ast_recvchar(struct ast_channel *chan, int timeout)
1578 struct ast_frame *f;
1583 if (ast_check_hangup(chan)) return -1;
1584 res = ast_waitfor(chan,ourto);
1585 if (res <= 0) /* if timeout */
1591 if (f == NULL) return -1; /* if hangup */
1592 if ((f->frametype == AST_FRAME_CONTROL) &&
1593 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1594 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1596 c = *((char *)f->data); /* get the data */
1604 int ast_sendtext(struct ast_channel *chan, char *text)
1607 /* Stop if we're a zombie or need a soft hangup */
1608 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1610 CHECK_BLOCKING(chan);
1611 if (chan->tech->send_text)
1612 res = chan->tech->send_text(chan, text);
1613 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1617 static int do_senddigit(struct ast_channel *chan, char digit)
1621 if (chan->tech->send_digit)
1622 res = chan->tech->send_digit(chan, digit);
1623 if (!chan->tech->send_digit || res) {
1625 * Device does not support DTMF tones, lets fake
1626 * it by doing our own generation. (PM2002)
1628 static const char* dtmf_tones[] = {
1629 "!941+1336/100,!0/100", /* 0 */
1630 "!697+1209/100,!0/100", /* 1 */
1631 "!697+1336/100,!0/100", /* 2 */
1632 "!697+1477/100,!0/100", /* 3 */
1633 "!770+1209/100,!0/100", /* 4 */
1634 "!770+1336/100,!0/100", /* 5 */
1635 "!770+1477/100,!0/100", /* 6 */
1636 "!852+1209/100,!0/100", /* 7 */
1637 "!852+1336/100,!0/100", /* 8 */
1638 "!852+1477/100,!0/100", /* 9 */
1639 "!697+1633/100,!0/100", /* A */
1640 "!770+1633/100,!0/100", /* B */
1641 "!852+1633/100,!0/100", /* C */
1642 "!941+1633/100,!0/100", /* D */
1643 "!941+1209/100,!0/100", /* * */
1644 "!941+1477/100,!0/100" }; /* # */
1645 if (digit >= '0' && digit <='9')
1646 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1647 else if (digit >= 'A' && digit <= 'D')
1648 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1649 else if (digit == '*')
1650 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1651 else if (digit == '#')
1652 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1655 ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1661 int ast_senddigit(struct ast_channel *chan, char digit)
1663 return do_senddigit(chan, digit);
1666 int ast_prod(struct ast_channel *chan)
1668 struct ast_frame a = { AST_FRAME_VOICE };
1670 /* Send an empty audio frame to get things moving */
1671 if (chan->_state != AST_STATE_UP) {
1672 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1673 a.subclass = chan->rawwriteformat;
1674 a.data = nothing + AST_FRIENDLY_OFFSET;
1676 if (ast_write(chan, &a))
1677 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1682 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1685 if (!chan->tech->write_video)
1687 res = ast_write(chan, fr);
1693 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1696 struct ast_frame *f = NULL;
1697 /* Stop if we're a zombie or need a soft hangup */
1698 ast_mutex_lock(&chan->lock);
1699 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1700 ast_mutex_unlock(&chan->lock);
1703 /* Handle any pending masquerades */
1705 if (ast_do_masquerade(chan)) {
1706 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1707 ast_mutex_unlock(&chan->lock);
1712 ast_mutex_unlock(&chan->lock);
1715 if (chan->generatordata) {
1716 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1717 ast_deactivate_generator(chan);
1719 ast_mutex_unlock(&chan->lock);
1723 if (chan->fout & 0x80000000)
1724 ast_frame_dump(chan->name, fr, ">>");
1725 CHECK_BLOCKING(chan);
1726 switch(fr->frametype) {
1727 case AST_FRAME_CONTROL:
1728 /* XXX Interpret control frames XXX */
1729 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1731 case AST_FRAME_DTMF:
1732 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1733 ast_mutex_unlock(&chan->lock);
1734 res = do_senddigit(chan,fr->subclass);
1735 ast_mutex_lock(&chan->lock);
1736 CHECK_BLOCKING(chan);
1738 case AST_FRAME_TEXT:
1739 if (chan->tech->send_text)
1740 res = chan->tech->send_text(chan, (char *) fr->data);
1744 case AST_FRAME_HTML:
1745 if (chan->tech->send_html)
1746 res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1750 case AST_FRAME_VIDEO:
1751 /* XXX Handle translation of video codecs one day XXX */
1752 if (chan->tech->write_video)
1753 res = chan->tech->write_video(chan, fr);
1758 if (chan->tech->write) {
1759 if (chan->writetrans) {
1760 f = ast_translate(chan->writetrans, fr, 0);
1764 res = chan->tech->write(chan, f);
1766 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
1767 struct ast_channel_spy *spying;
1768 for (spying = chan->spiers; spying; spying=spying->next) {
1769 ast_queue_spy_frame(spying, f, 1);
1773 if( chan->monitor &&
1774 chan->monitor->write_stream &&
1775 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1776 #ifndef MONITOR_CONSTANT_DELAY
1777 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1779 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1780 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1781 chan->outsmpl += jump + 2 * f->samples;
1783 chan->outsmpl += f->samples;
1785 int jump = chan->insmpl - chan->outsmpl;
1786 if (jump - MONITOR_DELAY >= 0) {
1787 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1788 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1789 chan->outsmpl += jump;
1791 chan->outsmpl += f->samples;
1793 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1794 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1802 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1803 /* Consider a write failure to force a soft hangup */
1805 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1807 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1808 chan->fout &= 0x80000000;
1813 ast_mutex_unlock(&chan->lock);
1817 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
1818 struct ast_trans_pvt **trans, const int direction)
1823 native = chan->nativeformats;
1824 /* Find a translation path from the native format to one of the desired formats */
1827 res = ast_translator_best_choice(&fmt, &native);
1830 res = ast_translator_best_choice(&native, &fmt);
1833 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1834 ast_getformatname(native), ast_getformatname(fmt));
1838 /* Now we have a good choice for both. */
1839 ast_mutex_lock(&chan->lock);
1840 *rawformat = native;
1841 /* User perspective is fmt */
1843 /* Free any read translation we have right now */
1845 ast_translator_free_path(*trans);
1846 /* Build a translation path from the raw format to the desired format */
1849 *trans = ast_translator_build_path(*format, *rawformat);
1852 *trans = ast_translator_build_path(*rawformat, *format);
1853 ast_mutex_unlock(&chan->lock);
1855 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
1856 direction ? "write" : "read", ast_getformatname(fmt));
1860 int ast_set_read_format(struct ast_channel *chan, int fmt)
1862 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
1863 &chan->readtrans, 0);
1866 int ast_set_write_format(struct ast_channel *chan, int fmt)
1868 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
1869 &chan->writetrans, 1);
1872 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
1876 struct ast_channel *chan;
1877 struct ast_frame *f;
1880 chan = ast_request(type, format, data, &cause);
1886 variable = ast_strdupa(oh->variable);
1890 /* FIXME replace this call with strsep NOT*/
1891 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1892 pbx_builtin_setvar( chan, var );
1894 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1895 if (oh->account && *oh->account)
1896 ast_cdr_setaccount(chan, oh->account);
1898 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1900 if (!ast_call(chan, data, 0)) {
1901 while(timeout && (chan->_state != AST_STATE_UP)) {
1902 res = ast_waitfor(chan, timeout);
1904 /* Something not cool, or timed out */
1907 /* If done, break out */
1914 state = AST_CONTROL_HANGUP;
1918 if (f->frametype == AST_FRAME_CONTROL) {
1919 if (f->subclass == AST_CONTROL_RINGING)
1920 state = AST_CONTROL_RINGING;
1921 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1922 state = f->subclass;
1925 } else if (f->subclass == AST_CONTROL_ANSWER) {
1926 state = f->subclass;
1929 } else if (f->subclass == AST_CONTROL_PROGRESS) {
1931 } else if (f->subclass == -1) {
1932 /* Ignore -- just stopping indications */
1934 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1940 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1942 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1944 case AST_CAUSE_BUSY:
1945 state = AST_CONTROL_BUSY;
1947 case AST_CAUSE_CONGESTION:
1948 state = AST_CONTROL_CONGESTION;
1955 if (oh->context && *oh->context)
1956 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1957 if (oh->exten && *oh->exten)
1958 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1959 chan->priority = oh->priority;
1961 if (chan->_state == AST_STATE_UP)
1962 state = AST_CONTROL_ANSWER;
1966 if (chan && res <= 0) {
1968 chan->cdr = ast_cdr_alloc();
1970 ast_cdr_init(chan->cdr, chan);
1974 snprintf(tmp, 256, "%s/%s", type, (char *)data);
1975 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1976 ast_cdr_update(chan);
1977 ast_cdr_start(chan->cdr);
1978 ast_cdr_end(chan->cdr);
1979 /* If the cause wasn't handled properly */
1980 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1981 ast_cdr_failed(chan->cdr);
1983 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1990 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1992 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1995 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1997 struct chanlist *chan;
1998 struct ast_channel *c = NULL;
2005 *cause = AST_CAUSE_NOTDEFINED;
2006 if (ast_mutex_lock(&chlock)) {
2007 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2012 if (!strcasecmp(type, chan->tech->type)) {
2013 capabilities = chan->tech->capabilities;
2015 res = ast_translator_best_choice(&fmt, &capabilities);
2017 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2018 ast_mutex_unlock(&chlock);
2021 ast_mutex_unlock(&chlock);
2022 if (chan->tech->requester)
2023 c = chan->tech->requester(type, capabilities, data, cause);
2025 if (c->_state == AST_STATE_DOWN) {
2026 manager_event(EVENT_FLAG_CALL, "Newchannel",
2030 "CallerIDName: %s\r\n"
2032 c->name, ast_state2str(c->_state), c->cid.cid_num ? c->cid.cid_num : "<unknown>", c->cid.cid_name ? c->cid.cid_name : "<unknown>",c->uniqueid);
2040 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2041 *cause = AST_CAUSE_NOSUCHDRIVER;
2043 ast_mutex_unlock(&chlock);
2047 int ast_parse_device_state(char *device)
2049 char name[AST_CHANNEL_NAME] = "";
2051 struct ast_channel *chan;
2053 chan = ast_channel_walk_locked(NULL);
2055 strncpy(name, chan->name, sizeof(name)-1);
2056 ast_mutex_unlock(&chan->lock);
2057 cut = strchr(name,'-');
2060 if (!strcmp(name, device))
2061 return AST_DEVICE_INUSE;
2062 chan = ast_channel_walk_locked(chan);
2064 return AST_DEVICE_UNKNOWN;
2067 int ast_device_state(char *device)
2069 char tech[AST_MAX_EXTENSION] = "";
2071 struct chanlist *chanls;
2074 strncpy(tech, device, sizeof(tech)-1);
2075 number = strchr(tech, '/');
2077 return AST_DEVICE_INVALID;
2082 if (ast_mutex_lock(&chlock)) {
2083 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2088 if (!strcasecmp(tech, chanls->tech->type)) {
2089 ast_mutex_unlock(&chlock);
2090 if (!chanls->tech->devicestate)
2091 return ast_parse_device_state(device);
2093 res = chanls->tech->devicestate(number);
2094 if (res == AST_DEVICE_UNKNOWN)
2095 return ast_parse_device_state(device);
2100 chanls = chanls->next;
2102 ast_mutex_unlock(&chlock);
2103 return AST_DEVICE_INVALID;
2106 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2108 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2109 If the remote end does not answer within the timeout, then do NOT hang up, but
2112 /* Stop if we're a zombie or need a soft hangup */
2113 ast_mutex_lock(&chan->lock);
2114 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2115 if (chan->tech->call)
2116 res = chan->tech->call(chan, addr, timeout);
2117 ast_mutex_unlock(&chan->lock);
2121 int ast_transfer(struct ast_channel *chan, char *dest)
2123 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2124 If the remote end does not answer within the timeout, then do NOT hang up, but
2127 /* Stop if we're a zombie or need a soft hangup */
2128 ast_mutex_lock(&chan->lock);
2129 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2130 if (chan->tech->transfer) {
2131 res = chan->tech->transfer(chan, dest);
2137 ast_mutex_unlock(&chan->lock);
2141 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2146 /* XXX Merge with full version? XXX */
2147 /* Stop if we're a zombie or need a soft hangup */
2148 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2154 d = ast_waitstream(c, AST_DIGIT_ANY);
2158 d = ast_waitfordigit(c, to);
2160 d = ast_waitfordigit(c, to);
2168 if (!strchr(enders, d))
2170 if (strchr(enders, d) || (pos >= len)) {
2180 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2185 /* Stop if we're a zombie or need a soft hangup */
2186 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2192 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2196 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2198 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2210 if (!strchr(enders, d))
2212 if (strchr(enders, d) || (pos >= len)) {
2222 int ast_channel_supports_html(struct ast_channel *chan)
2224 if (chan->tech->send_html)
2229 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2231 if (chan->tech->send_html)
2232 return chan->tech->send_html(chan, subclass, data, datalen);
2236 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2238 if (chan->tech->send_html)
2239 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2243 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2248 /* Set up translation from the chan to the peer */
2249 src = chan->nativeformats;
2250 dst = peer->nativeformats;
2251 if (ast_translator_best_choice(&dst, &src) < 0) {
2252 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2255 /* if the best path is not 'pass through', then
2256 transcoding is needed; if desired, force transcode path
2257 to use SLINEAR between channels */
2258 if ((src != dst) && option_transcode_slin)
2259 dst = AST_FORMAT_SLINEAR;
2260 if (ast_set_read_format(chan, dst) < 0) {
2261 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2264 if (ast_set_write_format(peer, dst) < 0) {
2265 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2269 /* Set up translation from the peer to the chan */
2270 src = peer->nativeformats;
2271 dst = chan->nativeformats;
2272 if (ast_translator_best_choice(&dst, &src) < 0) {
2273 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2276 /* if the best path is not 'pass through', then
2277 transcoding is needed; if desired, force transcode path
2278 to use SLINEAR between channels */
2279 if ((src != dst) && option_transcode_slin)
2280 dst = AST_FORMAT_SLINEAR;
2281 if (ast_set_read_format(peer, dst) < 0) {
2282 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2285 if (ast_set_write_format(chan, dst) < 0) {
2286 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2292 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2294 struct ast_frame null = { AST_FRAME_NULL, };
2296 if (original == clone) {
2297 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2300 ast_mutex_lock(&original->lock);
2301 while(ast_mutex_trylock(&clone->lock)) {
2302 ast_mutex_unlock(&original->lock);
2304 ast_mutex_lock(&original->lock);
2306 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2307 clone->name, original->name);
2308 if (original->masq) {
2309 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2310 original->masq->name, original->name);
2311 } else if (clone->masqr) {
2312 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2313 clone->name, clone->masqr->name);
2315 original->masq = clone;
2316 clone->masqr = original;
2317 ast_queue_frame(original, &null);
2318 ast_queue_frame(clone, &null);
2319 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2322 ast_mutex_unlock(&clone->lock);
2323 ast_mutex_unlock(&original->lock);
2327 void ast_change_name(struct ast_channel *chan, char *newname)
2330 strncpy(tmp, chan->name, sizeof(tmp) - 1);
2331 strncpy(chan->name, newname, sizeof(chan->name) - 1);
2332 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2335 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2337 struct ast_var_t *current, *newvar;
2340 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2343 varname = ast_var_full_name(current);
2347 if (varname[0] == '_') {
2349 if (varname[1] == '_')
2355 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2357 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2359 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2363 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2365 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2367 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2372 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2378 /* Clone channel variables from 'clone' channel into 'original' channel
2379 All variables except those related to app_groupcount are cloned
2380 Variables are actually _removed_ from 'clone' channel, presumably
2381 because it will subsequently be destroyed.
2382 Assumes locks will be in place on both channels when called.
2385 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2387 struct ast_var_t *varptr;
2389 /* we need to remove all app_groupcount related variables from the original
2390 channel before merging in the clone's variables; any groups assigned to the
2391 original channel should be released, only those assigned to the clone
2395 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2396 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2397 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2398 ast_var_delete(varptr);
2401 AST_LIST_TRAVERSE_SAFE_END;
2403 /* Append variables from clone channel into original channel */
2404 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2405 if (AST_LIST_FIRST(&clone->varshead))
2406 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2409 /* Assumes channel will be locked when called */
2410 int ast_do_masquerade(struct ast_channel *original)
2415 struct ast_frame *cur, *prev;
2416 const struct ast_channel_tech *t;
2418 struct ast_callerid tmpcid;
2419 struct ast_channel *clone = original->masq;
2420 int rformat = original->readformat;
2421 int wformat = original->writeformat;
2428 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2429 clone->name, clone->_state, original->name, original->_state);
2431 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2432 the clone channel into the original channel. Start by killing off the original
2433 channel's backend. I'm not sure we're going to keep this function, because
2434 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2436 /* We need the clone's lock, too */
2437 ast_mutex_lock(&clone->lock);
2439 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2441 /* Having remembered the original read/write formats, we turn off any translation on either
2443 free_translation(clone);
2444 free_translation(original);
2447 /* Unlink the masquerade */
2448 original->masq = NULL;
2449 clone->masqr = NULL;
2451 /* Save the original name */
2452 strncpy(orig, original->name, sizeof(orig) - 1);
2453 /* Save the new name */
2454 strncpy(newn, clone->name, sizeof(newn) - 1);
2455 /* Create the masq name */
2456 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2458 /* Copy the name from the clone channel */
2459 strncpy(original->name, newn, sizeof(original->name)-1);
2461 /* Mangle the name of the clone channel */
2462 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2464 /* Notify any managers of the change, first the masq then the other */
2465 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2466 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2468 /* Swap the technlogies */
2470 original->tech = clone->tech;
2473 t_pvt = original->tech_pvt;
2474 original->tech_pvt = clone->tech_pvt;
2475 clone->tech_pvt = t_pvt;
2477 /* Swap the readq's */
2478 cur = original->readq;
2479 original->readq = clone->readq;
2482 /* Swap the alertpipes */
2483 for (i = 0; i < 2; i++) {
2484 x = original->alertpipe[i];
2485 original->alertpipe[i] = clone->alertpipe[i];
2486 clone->alertpipe[i] = x;
2489 /* Swap the raw formats */
2490 x = original->rawreadformat;
2491 original->rawreadformat = clone->rawreadformat;
2492 clone->rawreadformat = x;
2493 x = original->rawwriteformat;
2494 original->rawwriteformat = clone->rawwriteformat;
2495 clone->rawwriteformat = x;
2497 /* Save any pending frames on both sides. Start by counting
2498 * how many we're going to need... */
2507 /* If we had any, prepend them to the ones already in the queue, and
2508 * load up the alertpipe */
2510 prev->next = original->readq;
2511 original->readq = clone->readq;
2512 clone->readq = NULL;
2513 if (original->alertpipe[1] > -1) {
2515 write(original->alertpipe[1], &x, sizeof(x));
2518 clone->_softhangup = AST_SOFTHANGUP_DEV;
2521 /* And of course, so does our current state. Note we need not
2522 call ast_setstate since the event manager doesn't really consider
2523 these separate. We do this early so that the clone has the proper
2524 state of the original channel. */
2525 origstate = original->_state;
2526 original->_state = clone->_state;
2527 clone->_state = origstate;
2529 if (clone->tech->fixup){
2530 res = clone->tech->fixup(original, clone);
2532 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2535 /* Start by disconnecting the original's physical side */
2536 if (clone->tech->hangup)
2537 res = clone->tech->hangup(clone);
2539 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2540 ast_mutex_unlock(&clone->lock);
2544 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2545 /* Mangle the name of the clone channel */
2546 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2547 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2549 /* Update the type. */
2550 original->type = clone->type;
2552 /* Keep the same language. */
2553 strncpy(original->language, clone->language, sizeof(original->language));
2555 for (x=0;x<AST_MAX_FDS;x++) {
2556 original->fds[x] = clone->fds[x];
2558 clone_variables(original, clone);
2559 clone->varshead.first = NULL;
2560 /* Presense of ADSI capable CPE follows clone */
2561 original->adsicpe = clone->adsicpe;
2562 /* Bridge remains the same */
2563 /* CDR fields remain the same */
2564 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2565 /* Application and data remain the same */
2566 /* Clone exception becomes real one, as with fdno */
2567 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2568 original->fdno = clone->fdno;
2569 /* Schedule context remains the same */
2570 /* Stream stuff stays the same */
2571 /* Keep the original state. The fixup code will need to work with it most likely */
2573 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2575 tmpcid = original->cid;
2576 original->cid = clone->cid;
2577 clone->cid = tmpcid;
2579 /* Restore original timing file descriptor */
2580 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2582 /* Our native formats are different now */
2583 original->nativeformats = clone->nativeformats;
2585 /* Context, extension, priority, app data, jump table, remain the same */
2586 /* pvt switches. pbx stays the same, as does next */
2588 /* Set the write format */
2589 ast_set_write_format(original, wformat);
2591 /* Set the read format */
2592 ast_set_read_format(original, rformat);
2594 /* Copy the music class */
2595 strncpy(original->musicclass, clone->musicclass, sizeof(original->musicclass) - 1);
2597 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2599 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2600 can fix up everything as best as possible */
2601 if (original->tech->fixup) {
2602 res = original->tech->fixup(clone, original);
2604 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2605 original->type, original->name);
2606 ast_mutex_unlock(&clone->lock);
2610 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2611 original->type, original->name);
2613 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2614 a zombie so nothing tries to touch it. If it's already been marked as a
2615 zombie, then free it now (since it already is considered invalid). */
2616 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2617 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2618 ast_mutex_unlock(&clone->lock);
2619 ast_channel_free(clone);
2620 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2622 struct ast_frame null_frame = { AST_FRAME_NULL, };
2623 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2624 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2625 ast_queue_frame(clone, &null_frame);
2626 ast_mutex_unlock(&clone->lock);
2629 /* Signal any blocker */
2630 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2631 pthread_kill(original->blocker, SIGURG);
2632 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2633 original->name, original->_state);
2637 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2640 if (chan->cid.cid_num)
2641 free(chan->cid.cid_num);
2642 if (ast_strlen_zero(callerid))
2643 chan->cid.cid_num = NULL;
2645 chan->cid.cid_num = strdup(callerid);
2648 if (chan->cid.cid_name)
2649 free(chan->cid.cid_name);
2650 if (ast_strlen_zero(calleridname))
2651 chan->cid.cid_name = NULL;
2653 chan->cid.cid_name = strdup(calleridname);
2656 if (chan->cid.cid_ani)
2657 free(chan->cid.cid_ani);
2658 if (ast_strlen_zero(ani))
2659 chan->cid.cid_ani = NULL;
2661 chan->cid.cid_ani = strdup(ani);
2664 ast_cdr_setcid(chan->cdr, chan);
2665 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2668 "CallerIDName: %s\r\n"
2670 chan->name, chan->cid.cid_num ?
2671 chan->cid.cid_num : "<Unknown>",
2672 chan->cid.cid_name ?
2673 chan->cid.cid_name : "<Unknown>",
2677 int ast_setstate(struct ast_channel *chan, int state)
2679 if (chan->_state != state) {
2680 int oldstate = chan->_state;
2681 chan->_state = state;
2682 if (oldstate == AST_STATE_DOWN) {
2683 ast_device_state_changed(chan->name);
2684 manager_event(EVENT_FLAG_CALL, "Newchannel",
2688 "CallerIDName: %s\r\n"
2690 chan->name, ast_state2str(chan->_state),
2691 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2692 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2695 manager_event(EVENT_FLAG_CALL, "Newstate",
2699 "CallerIDName: %s\r\n"
2701 chan->name, ast_state2str(chan->_state),
2702 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2703 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2710 static long tvdiff(struct timeval *now, struct timeval *then)
2713 return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2715 return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;
2719 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2721 struct ast_channel *bridged;
2722 bridged = chan->_bridge;
2723 if (bridged && bridged->tech->bridged_channel)
2724 bridged = bridged->tech->bridged_channel(chan, bridged);
2728 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2730 int res=0, min=0, sec=0,check=0;
2732 check = ast_autoservice_start(peer);
2737 if (remain / 60 > 1) {
2745 if (!strcmp(sound,"timeleft")) {
2746 res = ast_streamfile(chan, "vm-youhave", chan->language);
2747 res = ast_waitstream(chan, "");
2749 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2750 res = ast_streamfile(chan, "queue-minutes", chan->language);
2751 res = ast_waitstream(chan, "");
2754 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2755 res = ast_streamfile(chan, "queue-seconds", chan->language);
2756 res = ast_waitstream(chan, "");
2759 res = ast_streamfile(chan, sound, chan->language);
2760 res = ast_waitstream(chan, "");
2763 check = ast_autoservice_stop(peer);
2766 static int ast_generic_bridge(int *playitagain, int *playit, struct timeval *start_time, struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
2768 /* Copy voice back and forth between the two channels. Give the peer
2769 the ability to transfer calls with '#<extension' syntax. */
2770 struct ast_channel *cs[3];
2772 struct ast_frame *f;
2773 struct ast_channel *who = NULL;
2776 int o0nativeformats;
2777 int o1nativeformats;
2778 struct timeval precise_now;
2779 long elapsed_ms=0, time_left_ms=0;
2785 o0nativeformats = c0->nativeformats;
2786 o1nativeformats = c1->nativeformats;
2789 if ((c0->pvt != pvt0) || (c1->pvt != pvt1) ||
2790 (o0nativeformats != c0->nativeformats) ||
2791 (o1nativeformats != c1->nativeformats)) {
2792 /* Check for Masquerade, codec changes, etc */
2797 if (config->timelimit) {
2798 /* If there is a time limit, return now */
2799 gettimeofday(&precise_now,NULL);
2800 elapsed_ms = tvdiff(&precise_now,start_time);
2801 time_left_ms = config->timelimit - elapsed_ms;
2803 if (*playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) {
2807 if (time_left_ms <= 0) {
2811 if (time_left_ms >= 5000 && *playit) {
2818 who = ast_waitfor_n(cs, 2, &to);
2820 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2821 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2822 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2823 c0->_softhangup = 0;
2824 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2825 c1->_softhangup = 0;
2838 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2842 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2843 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2844 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2849 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2853 if ((f->frametype == AST_FRAME_VOICE) ||
2854 (f->frametype == AST_FRAME_TEXT) ||
2855 (f->frametype == AST_FRAME_VIDEO) ||
2856 (f->frametype == AST_FRAME_IMAGE) ||
2857 (f->frametype == AST_FRAME_HTML) ||
2858 (f->frametype == AST_FRAME_DTMF)) {
2860 if ((f->frametype == AST_FRAME_DTMF) &&
2861 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2863 if ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2866 /* Take out of conference mode */
2868 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2874 if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2878 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2885 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2887 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2891 /* Don't copy packets if there is a generator on either one, since they're
2892 not supposed to be listening anyway */
2901 /* Swap who gets priority */
2909 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
2911 /* Copy voice back and forth between the two channels. Give the peer
2912 the ability to transfer calls with '#<extension' syntax. */
2913 struct ast_channel *cs[3];
2914 struct ast_channel *who = NULL;
2918 int o0nativeformats;
2919 int o1nativeformats;
2920 struct timeval start_time,precise_now;
2921 long elapsed_ms=0, time_left_ms=0;
2922 int playit=0, playitagain=1, first_time=1;
2925 firstpass = config->firstpass;
2926 config->firstpass = 0;
2929 gettimeofday(&start_time,NULL);
2930 time_left_ms = config->timelimit;
2932 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2933 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2934 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2935 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2937 /* Stop if we're a zombie or need a soft hangup */
2938 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
2941 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2942 c0->name, c0->_bridge->name);
2946 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2947 c1->name, c1->_bridge->name);
2951 /* Keep track of bridge */
2957 manager_event(EVENT_FLAG_CALL, "Link",
2961 "Uniqueid2: %s\r\n",
2962 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2963 o1nativeformats = c1->nativeformats;
2964 o0nativeformats = c0->nativeformats;
2965 for (/* ever */;;) {
2967 if (config->timelimit) {
2968 gettimeofday(&precise_now,NULL);
2969 elapsed_ms = tvdiff(&precise_now,&start_time);
2970 time_left_ms = config->timelimit - elapsed_ms;
2972 if (playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) {
2973 /* narrowing down to the end */
2974 if (config->warning_freq == 0) {
2978 } else if (first_time) {
2982 if ((time_left_ms % config->warning_freq) <= 50) {
2987 if (time_left_ms <= 0) {
2988 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2989 bridge_playfile(c0,c1,config->end_sound,0);
2990 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2991 bridge_playfile(c1,c0,config->end_sound,0);
2997 if (time_left_ms >= 5000 && playit) {
2998 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2999 bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
3000 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3001 bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
3007 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3008 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3009 c0->_softhangup = 0;
3010 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3011 c1->_softhangup = 0;
3014 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3018 /* Stop if we're a zombie or need a soft hangup */
3019 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3023 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,ast_test_flag(c0, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c0)?"Yes":"No",ast_test_flag(c1, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c1)?"Yes":"No");
3026 if (c0->tech->bridge && config->timelimit==0 &&
3027 (c0->tech->bridge == c1->tech->bridge) && !nativefailed && !c0->monitor && !c1->monitor && !c0->spiers && !c1->spiers) {
3028 /* Looks like they share a bridge code */
3029 if (option_verbose > 2)
3030 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
3031 ast_set_flag(c0, AST_FLAG_NBRIDGE);
3032 ast_set_flag(c1, AST_FLAG_NBRIDGE);
3033 if (!(res = c0->tech->bridge(c0, c1, config->flags, fo, rc))) {
3036 manager_event(EVENT_FLAG_CALL, "Unlink",
3040 "Uniqueid2: %s\r\n",
3041 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3042 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
3043 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3044 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3045 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3053 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3054 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3057 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
3058 my not wanting to bridge */
3059 if ((res != -2) && (res != -3))
3060 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
3061 if (res != -3) nativefailed++;
3064 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3065 !(c0->generator || c1->generator)) {
3066 if (ast_channel_make_compatible(c0, c1)) {
3067 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3068 manager_event(EVENT_FLAG_CALL, "Unlink",
3072 "Uniqueid2: %s\r\n",
3073 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3076 o0nativeformats = c0->nativeformats;
3077 o1nativeformats = c1->nativeformats;
3079 res = ast_generic_bridge(&playitagain, &playit, &start_time, c0, c1, config, fo, rc);
3085 manager_event(EVENT_FLAG_CALL, "Unlink",
3089 "Uniqueid2: %s\r\n",