2 * Asterisk -- A telephony toolkit for Linux.
6 * Copyright (C) 1999-2004, 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/channel_pvt.h>
29 #include <asterisk/logger.h>
30 #include <asterisk/say.h>
31 #include <asterisk/file.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/translate.h>
34 #include <asterisk/manager.h>
35 #include <asterisk/chanvars.h>
36 #include <asterisk/linkedlists.h>
37 #include <asterisk/indications.h>
38 #include <asterisk/monitor.h>
39 #include <asterisk/causes.h>
40 #include <asterisk/utils.h>
41 #include <asterisk/lock.h>
42 #include <asterisk/app.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 */
73 struct ast_channel * (*requester)(const char *type, int format, void *data, int *cause);
74 int (*devicestate)(void *data);
75 struct chanlist *next;
77 struct ast_channel *channels = NULL;
79 /* Protect the channel list (highly unlikely that two things would change
80 it at the same time, but still! */
82 AST_MUTEX_DEFINE_STATIC(chlock);
84 static int show_channeltypes(int fd, int argc, char *argv[])
86 #define FORMAT "%-7.7s %-50.50s\n"
87 struct chanlist *cl = backends;
88 ast_cli(fd, FORMAT, "Type", "Description");
89 ast_cli(fd, FORMAT, "------", "-----------");
90 if (ast_mutex_lock(&chlock)) {
91 ast_log(LOG_WARNING, "Unable to lock channel list\n");
95 ast_cli(fd, FORMAT, cl->type, cl->description);
98 ast_mutex_unlock(&chlock);
99 return RESULT_SUCCESS;
103 static char show_channeltypes_usage[] =
104 "Usage: show channeltypes\n"
105 " Shows available channel types registred in your Asterisk server.";
107 static struct ast_cli_entry cli_show_channeltypes =
108 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
110 int ast_check_hangup(struct ast_channel *chan)
114 /* if soft hangup flag, return true */
115 if (chan->_softhangup) return 1;
116 /* if no private structure, return true */
117 if (!chan->pvt->pvt) return 1;
118 /* if no hangup scheduled, just return here */
119 if (!chan->whentohangup) return 0;
120 time(&myt); /* get current time */
121 /* return, if not yet */
122 if (chan->whentohangup > myt) return 0;
123 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
127 static int ast_check_hangup_locked(struct ast_channel *chan)
130 ast_mutex_lock(&chan->lock);
131 res = ast_check_hangup(chan);
132 ast_mutex_unlock(&chan->lock);
136 void ast_begin_shutdown(int hangup)
138 struct ast_channel *c;
141 ast_mutex_lock(&chlock);
144 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
147 ast_mutex_unlock(&chlock);
151 int ast_active_channels(void)
153 struct ast_channel *c;
155 ast_mutex_lock(&chlock);
161 ast_mutex_unlock(&chlock);
165 void ast_cancel_shutdown(void)
170 int ast_shutting_down(void)
172 return shutting_down;
175 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
181 chan->whentohangup = myt + offset;
183 chan->whentohangup = 0;
187 int ast_channel_register(const char *type, const char *description, int capabilities,
188 struct ast_channel *(*requester)(const char *type, int format, void *data, int *cause))
190 return ast_channel_register_ex(type, description, capabilities, requester, NULL);
193 int ast_channel_register_ex(const char *type, const char *description, int capabilities,
194 struct ast_channel *(*requester)(const char *type, int format, void *data, int *cause),
195 int (*devicestate)(void *data))
197 struct chanlist *chan, *last=NULL;
198 if (ast_mutex_lock(&chlock)) {
199 ast_log(LOG_WARNING, "Unable to lock channel list\n");
204 if (!strcasecmp(type, chan->type)) {
205 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
206 ast_mutex_unlock(&chlock);
212 chan = malloc(sizeof(struct chanlist));
214 ast_log(LOG_WARNING, "Out of memory\n");
215 ast_mutex_unlock(&chlock);
218 strncpy(chan->type, type, sizeof(chan->type)-1);
219 strncpy(chan->description, description, sizeof(chan->description)-1);
220 chan->capabilities = capabilities;
221 chan->requester = requester;
222 chan->devicestate = devicestate;
229 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
230 else if (option_verbose > 1)
231 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
232 ast_mutex_unlock(&chlock);
236 char *ast_state2str(int state)
238 /* XXX Not reentrant XXX */
239 static char localtmp[256];
243 case AST_STATE_RESERVED:
245 case AST_STATE_OFFHOOK:
247 case AST_STATE_DIALING:
251 case AST_STATE_RINGING:
258 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
264 int ast_best_codec(int fmts)
266 /* This just our opinion, expressed in code. We are asked to choose
267 the best codec to use, given no information */
271 /* Okay, ulaw is used by all telephony equipment, so start with it */
273 /* Unless of course, you're a silly European, so then prefer ALAW */
275 /* Okay, well, signed linear is easy to translate into other stuff */
277 /* G.726 is standard ADPCM */
279 /* ADPCM has great sound quality and is still pretty easy to translate */
281 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
282 translate and sounds pretty good */
284 /* iLBC is not too bad */
286 /* Speex is free, but computationally more expensive than GSM */
288 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
291 /* G.729a is faster than 723 and slightly less expensive */
293 /* Down to G.723.1 which is proprietary but at least designed for voice */
298 for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
301 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
305 struct ast_channel *ast_channel_alloc(int needqueue)
307 struct ast_channel *tmp;
308 struct ast_channel_pvt *pvt;
311 struct varshead *headp;
314 /* If shutting down, don't allocate any new channels */
317 ast_mutex_lock(&chlock);
318 tmp = malloc(sizeof(struct ast_channel));
320 memset(tmp, 0, sizeof(struct ast_channel));
321 pvt = malloc(sizeof(struct ast_channel_pvt));
323 memset(pvt, 0, sizeof(struct ast_channel_pvt));
324 tmp->sched = sched_context_create();
326 for (x=0;x<AST_MAX_FDS - 1;x++)
328 #ifdef ZAPTEL_OPTIMIZATIONS
329 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
330 if (tmp->timingfd > -1) {
331 /* Check if timing interface supports new
334 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
341 pipe(pvt->alertpipe)) {
342 ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
349 flags = fcntl(pvt->alertpipe[0], F_GETFL);
350 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
351 flags = fcntl(pvt->alertpipe[1], F_GETFL);
352 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
354 /* Make sure we've got it done right if they don't */
355 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
356 /* Always watch the alertpipe */
357 tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
358 /* And timing pipe */
359 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
360 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
363 tmp->_state = AST_STATE_DOWN;
367 tmp->fin = global_fin;
368 tmp->fout = global_fout;
369 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
370 headp=&tmp->varshead;
371 ast_mutex_init(&tmp->lock);
372 AST_LIST_HEAD_INIT(headp);
373 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
374 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
375 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
377 tmp->amaflags = ast_default_amaflags;
378 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
379 tmp->next = channels;
383 ast_log(LOG_WARNING, "Unable to create schedule context\n");
388 ast_log(LOG_WARNING, "Out of memory\n");
393 ast_log(LOG_WARNING, "Out of memory\n");
394 ast_mutex_unlock(&chlock);
398 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
401 struct ast_frame *prev, *cur;
404 /* Build us a copy and free the original one */
407 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
410 ast_mutex_lock(&chan->lock);
412 cur = chan->pvt->readq;
414 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
415 /* Don't bother actually queueing anything after a hangup */
417 ast_mutex_unlock(&chan->lock);
424 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
425 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
426 if (fin->frametype != AST_FRAME_VOICE) {
427 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
430 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
432 ast_mutex_unlock(&chan->lock);
439 chan->pvt->readq = f;
440 if (chan->pvt->alertpipe[1] > -1) {
441 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
442 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
443 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
444 #ifdef ZAPTEL_OPTIMIZATIONS
445 } else if (chan->timingfd > -1) {
446 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
448 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
449 pthread_kill(chan->blocker, SIGURG);
451 ast_mutex_unlock(&chan->lock);
455 int ast_queue_hangup(struct ast_channel *chan)
457 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
458 chan->_softhangup |= AST_SOFTHANGUP_DEV;
459 return ast_queue_frame(chan, &f);
462 int ast_queue_control(struct ast_channel *chan, int control)
464 struct ast_frame f = { AST_FRAME_CONTROL, };
465 f.subclass = control;
466 return ast_queue_frame(chan, &f);
469 int ast_channel_defer_dtmf(struct ast_channel *chan)
473 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
474 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
479 void ast_channel_undefer_dtmf(struct ast_channel *chan)
482 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
485 struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
487 /* Returns next channel (locked) */
488 struct ast_channel *l, *ret;
492 ast_mutex_lock(&chlock);
496 if (ast_mutex_trylock(&l->lock)) {
498 ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
500 ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
501 ast_mutex_unlock(&chlock);
510 ast_mutex_unlock(&chlock);
519 if (ast_mutex_trylock(&ret->lock)) {
521 ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
523 ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
524 ast_mutex_unlock(&chlock);
533 ast_mutex_unlock(&chlock);
538 struct ast_channel *ast_get_channel_by_name_locked(char *channame)
540 struct ast_channel *chan;
541 chan = ast_channel_walk_locked(NULL);
543 if (!strcasecmp(chan->name, channame))
545 ast_mutex_unlock(&chan->lock);
546 chan = ast_channel_walk_locked(chan);
551 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
552 int (*cond)(void*), void *data )
557 if( cond && ((*cond)(data) == 0 ) )
559 ms = ast_waitfor(chan, ms);
572 int ast_safe_sleep(struct ast_channel *chan, int ms)
576 ms = ast_waitfor(chan, ms);
589 static void free_cid(struct ast_callerid *cid)
600 free(cid->cid_rdnis);
603 void ast_channel_free(struct ast_channel *chan)
605 struct ast_channel *last=NULL, *cur;
607 struct ast_var_t *vardata;
608 struct ast_frame *f, *fp;
609 struct varshead *headp;
610 char name[AST_CHANNEL_NAME];
612 headp=&chan->varshead;
614 ast_mutex_lock(&chlock);
619 last->next = cur->next;
621 channels = cur->next;
628 ast_log(LOG_WARNING, "Unable to find channel in list\n");
630 /* Lock and unlock the channel just to be sure nobody
631 has it locked still */
632 ast_mutex_lock(&cur->lock);
633 ast_mutex_unlock(&cur->lock);
636 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
638 strncpy(name, chan->name, sizeof(name)-1);
640 /* Stop monitoring */
642 chan->monitor->stop( chan, 0 );
645 /* If there is native format music-on-hold state, free it */
646 if(chan->music_state)
647 ast_moh_cleanup(chan);
649 /* Free translatosr */
650 if (chan->pvt->readtrans)
651 ast_translator_free_path(chan->pvt->readtrans);
652 if (chan->pvt->writetrans)
653 ast_translator_free_path(chan->pvt->writetrans);
655 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
656 free_cid(&chan->cid);
657 ast_mutex_destroy(&chan->lock);
658 /* Close pipes if appropriate */
659 if ((fd = chan->pvt->alertpipe[0]) > -1)
661 if ((fd = chan->pvt->alertpipe[1]) > -1)
663 if ((fd = chan->timingfd) > -1)
665 f = chan->pvt->readq;
666 chan->pvt->readq = NULL;
673 /* loop over the variables list, freeing all data and deleting list items */
674 /* no need to lock the list, as the channel is already locked */
676 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
677 vardata = AST_LIST_REMOVE_HEAD(headp, entries);
678 /* printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata)); */
679 ast_var_delete(vardata);
686 ast_mutex_unlock(&chlock);
688 ast_device_state_changed(name);
691 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
694 struct ast_frame f = { AST_FRAME_NULL };
696 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
697 /* Inform channel driver that we need to be hung up, if it cares */
698 chan->_softhangup |= cause;
699 ast_queue_frame(chan, &f);
700 /* Interrupt any poll call or such */
701 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
702 pthread_kill(chan->blocker, SIGURG);
706 int ast_softhangup(struct ast_channel *chan, int cause)
709 ast_mutex_lock(&chan->lock);
710 res = ast_softhangup_nolock(chan, cause);
711 ast_mutex_unlock(&chan->lock);
715 static void free_translation(struct ast_channel *clone)
717 if (clone->pvt->writetrans)
718 ast_translator_free_path(clone->pvt->writetrans);
719 if (clone->pvt->readtrans)
720 ast_translator_free_path(clone->pvt->readtrans);
721 clone->pvt->writetrans = NULL;
722 clone->pvt->readtrans = NULL;
723 clone->pvt->rawwriteformat = clone->nativeformats;
724 clone->pvt->rawreadformat = clone->nativeformats;
727 int ast_hangup(struct ast_channel *chan)
730 /* Don't actually hang up a channel that will masquerade as someone else, or
731 if someone is going to masquerade as us */
732 ast_mutex_lock(&chan->lock);
734 if (ast_do_masquerade(chan))
735 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
739 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
740 ast_mutex_unlock(&chan->lock);
743 /* If this channel is one which will be masqueraded into something,
744 mark it as a zombie already, so we know to free it later */
746 ast_set_flag(chan, AST_FLAG_ZOMBIE);
747 ast_mutex_unlock(&chan->lock);
750 free_translation(chan);
752 ast_closestream(chan->stream);
754 ast_closestream(chan->vstream);
756 sched_context_destroy(chan->sched);
757 /* Clear any tone stuff remaining */
758 if (chan->generatordata)
759 chan->generator->release(chan, chan->generatordata);
760 chan->generatordata = NULL;
761 chan->generator = NULL;
763 /* End the CDR if it hasn't already */
764 ast_cdr_end(chan->cdr);
765 /* Post and Free the CDR */
766 ast_cdr_post(chan->cdr);
767 ast_cdr_free(chan->cdr);
769 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
770 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
771 "is blocked by thread %ld in procedure %s! Expect a failure\n",
772 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
775 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
777 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
778 if (chan->pvt->hangup)
779 res = chan->pvt->hangup(chan);
782 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
784 ast_mutex_unlock(&chan->lock);
785 manager_event(EVENT_FLAG_CALL, "Hangup",
789 chan->name, chan->uniqueid, chan->hangupcause);
790 ast_channel_free(chan);
794 void ast_channel_unregister(const char *type)
796 struct chanlist *chan, *last=NULL;
798 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
799 if (ast_mutex_lock(&chlock)) {
800 ast_log(LOG_WARNING, "Unable to lock channel list\n");
803 if (option_verbose > 1)
804 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", type);
808 if (!strcasecmp(chan->type, type)) {
810 last->next = chan->next;
812 backends = backends->next;
814 ast_mutex_unlock(&chlock);
820 ast_mutex_unlock(&chlock);
823 int ast_answer(struct ast_channel *chan)
826 ast_mutex_lock(&chan->lock);
827 /* Stop if we're a zombie or need a soft hangup */
828 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
829 ast_mutex_unlock(&chan->lock);
832 switch(chan->_state) {
833 case AST_STATE_RINGING:
835 if (chan->pvt->answer)
836 res = chan->pvt->answer(chan);
837 ast_setstate(chan, AST_STATE_UP);
839 ast_cdr_answer(chan->cdr);
840 ast_mutex_unlock(&chan->lock);
845 ast_cdr_answer(chan->cdr);
848 ast_mutex_unlock(&chan->lock);
854 void ast_deactivate_generator(struct ast_channel *chan)
856 ast_mutex_lock(&chan->lock);
857 if (chan->generatordata) {
858 if (chan->generator && chan->generator->release)
859 chan->generator->release(chan, chan->generatordata);
860 chan->generatordata = NULL;
861 chan->generator = NULL;
862 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
863 ast_settimeout(chan, 0, NULL, NULL);
865 ast_mutex_unlock(&chan->lock);
868 static int generator_force(void *data)
870 /* Called if generator doesn't have data */
873 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
874 struct ast_channel *chan = data;
875 tmp = chan->generatordata;
876 chan->generatordata = NULL;
877 generate = chan->generator->generate;
878 res = generate(chan, tmp, 0, 160);
879 chan->generatordata = tmp;
881 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
882 ast_deactivate_generator(chan);
887 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
890 ast_mutex_lock(&chan->lock);
891 if (chan->generatordata) {
892 if (chan->generator && chan->generator->release)
893 chan->generator->release(chan, chan->generatordata);
894 chan->generatordata = NULL;
897 if ((chan->generatordata = gen->alloc(chan, params))) {
898 ast_settimeout(chan, 160, generator_force, chan);
899 chan->generator = gen;
903 ast_mutex_unlock(&chan->lock);
907 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
909 /* Wait for x amount of time on a file descriptor to have input. */
910 struct timeval start, now;
917 pfds = alloca(sizeof(struct pollfd) * n);
919 ast_log(LOG_WARNING, "alloca failed! bad things will happen.\n");
923 gettimeofday(&start, NULL);
928 pfds[y].events = POLLIN | POLLPRI;
932 res = poll(pfds, y, *ms);
934 /* Simulate a timeout if we were interrupted */
944 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
957 gettimeofday(&now, NULL);
958 passed = (now.tv_sec - start.tv_sec) * 1000;
959 passed += (now.tv_usec - start.tv_usec) / 1000;
968 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
969 int *exception, int *outfd, int *ms)
971 /* Wait for x amount of time on a file descriptor to have input. */
972 struct timeval start, end;
979 long whentohangup = 0, havewhen = 0, diff;
980 struct ast_channel *winner = NULL;
982 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
984 ast_log(LOG_WARNING, "alloca failed! bad things will happen.\n");
994 /* Perform any pending masquerades */
996 ast_mutex_lock(&c[x]->lock);
997 if (c[x]->whentohangup) {
1000 diff = c[x]->whentohangup - now;
1001 if (!havewhen || (diff < whentohangup)) {
1003 whentohangup = diff;
1007 if (ast_do_masquerade(c[x])) {
1008 ast_log(LOG_WARNING, "Masquerade failed\n");
1010 ast_mutex_unlock(&c[x]->lock);
1014 ast_mutex_unlock(&c[x]->lock);
1020 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1021 rms = whentohangup * 1000;
1026 for (y=0;y<AST_MAX_FDS;y++) {
1027 if (c[x]->fds[y] > -1) {
1028 pfds[max].fd = c[x]->fds[y];
1029 pfds[max].events = POLLIN | POLLPRI;
1033 CHECK_BLOCKING(c[x]);
1035 for (x=0;x<nfds; x++) {
1037 pfds[max].fd = fds[x];
1038 pfds[max].events = POLLIN | POLLPRI;
1043 gettimeofday(&start, NULL);
1044 res = poll(pfds, max, rms);
1047 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1048 /* Simulate a timeout if we were interrupted */
1052 /* Just an interrupt */
1064 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1065 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1066 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1070 for (y=0;y<AST_MAX_FDS;y++) {
1071 if (c[x]->fds[y] > -1) {
1072 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1074 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1076 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1083 for (x=0;x<nfds;x++) {
1085 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1100 gettimeofday(&end, NULL);
1101 diff = (end.tv_sec - start.tv_sec) * 1000;
1102 diff += (end.tv_usec - start.tv_usec) / 1000;
1111 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1113 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1116 int ast_waitfor(struct ast_channel *c, int ms)
1118 struct ast_channel *chan;
1120 chan = ast_waitfor_n(&c, 1, &ms);
1130 char ast_waitfordigit(struct ast_channel *c, int ms)
1132 /* XXX Should I be merged with waitfordigit_full XXX */
1133 struct ast_frame *f;
1135 /* Stop if we're a zombie or need a soft hangup */
1136 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1138 /* Wait for a digit, no more than ms milliseconds total. */
1139 while(ms && !result) {
1140 ms = ast_waitfor(c, ms);
1141 if (ms < 0) /* Error */
1144 /* Read something */
1147 if (f->frametype == AST_FRAME_DTMF)
1148 result = f->subclass;
1157 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1160 #ifdef ZAPTEL_OPTIMIZATIONS
1161 if (c->timingfd > -1) {
1166 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1167 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1168 c->timingfunc = func;
1169 c->timingdata = data;
1174 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1176 struct ast_frame *f;
1177 struct ast_channel *rchan;
1180 /* Stop if we're a zombie or need a soft hangup */
1181 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1183 /* Wait for a digit, no more than ms milliseconds total. */
1185 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1186 if ((!rchan) && (outfd < 0) && (ms)) {
1187 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1189 } else if (outfd > -1) {
1190 /* The FD we were watching has something waiting */
1198 switch(f->frametype) {
1199 case AST_FRAME_DTMF:
1203 case AST_FRAME_CONTROL:
1204 switch(f->subclass) {
1205 case AST_CONTROL_HANGUP:
1208 case AST_CONTROL_RINGING:
1209 case AST_CONTROL_ANSWER:
1213 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1215 case AST_FRAME_VOICE:
1216 /* Write audio if appropriate */
1218 write(audiofd, f->data, f->datalen);
1224 return 0; // Time is up
1227 struct ast_frame *ast_read(struct ast_channel *chan)
1229 struct ast_frame *f = NULL;
1231 #ifdef ZAPTEL_OPTIMIZATIONS
1232 int (*func)(void *);
1236 static struct ast_frame null_frame =
1241 ast_mutex_lock(&chan->lock);
1243 if (ast_do_masquerade(chan)) {
1244 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1248 ast_mutex_unlock(&chan->lock);
1252 /* Stop if we're a zombie or need a soft hangup */
1253 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1254 if (chan->generator)
1255 ast_deactivate_generator(chan);
1256 ast_mutex_unlock(&chan->lock);
1260 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1261 /* We have DTMF that has been deferred. Return it now */
1262 chan->dtmff.frametype = AST_FRAME_DTMF;
1263 chan->dtmff.subclass = chan->dtmfq[0];
1264 /* Drop first digit */
1265 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1266 ast_mutex_unlock(&chan->lock);
1267 return &chan->dtmff;
1270 /* Read and ignore anything on the alertpipe, but read only
1271 one sizeof(blah) per frame that we send from it */
1272 if (chan->pvt->alertpipe[0] > -1) {
1273 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1275 #ifdef ZAPTEL_OPTIMIZATIONS
1276 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1277 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1279 /* IF we can't get event, assume it's an expired as-per the old interface */
1280 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1282 blah = ZT_EVENT_TIMER_EXPIRED;
1284 if (blah == ZT_EVENT_TIMER_PING) {
1286 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1288 if (!chan->pvt->readq || !chan->pvt->readq->next) {
1289 /* Acknowledge PONG unless we need it again */
1291 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1293 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1294 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1297 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1298 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1299 func = chan->timingfunc;
1300 data = chan->timingdata;
1301 ast_mutex_unlock(&chan->lock);
1304 ast_log(LOG_DEBUG, "Calling private function\n");
1309 ast_mutex_lock(&chan->lock);
1310 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1311 chan->timingdata = NULL;
1312 ast_mutex_unlock(&chan->lock);
1317 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1320 /* Check for pending read queue */
1321 if (chan->pvt->readq) {
1322 f = chan->pvt->readq;
1323 chan->pvt->readq = f->next;
1324 /* Interpret hangup and return NULL */
1325 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1330 chan->blocker = pthread_self();
1331 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1332 if (chan->pvt->exception)
1333 f = chan->pvt->exception(chan);
1335 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1338 /* Clear the exception flag */
1339 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1341 if (chan->pvt->read)
1342 f = chan->pvt->read(chan);
1344 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1348 if (f && (f->frametype == AST_FRAME_VOICE)) {
1349 if (!(f->subclass & chan->nativeformats)) {
1350 /* This frame can't be from the current native formats -- drop it on the
1352 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));
1356 if (chan->monitor && chan->monitor->read_stream ) {
1357 #ifndef MONITOR_CONSTANT_DELAY
1358 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1360 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1361 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1362 chan->insmpl += jump + 2 * f->samples;
1364 chan->insmpl+= f->samples;
1366 int jump = chan->outsmpl - chan->insmpl;
1367 if (jump - MONITOR_DELAY >= 0) {
1368 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1369 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1370 chan->insmpl += jump;
1372 chan->insmpl += f->samples;
1374 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1375 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1377 if (chan->pvt->readtrans) {
1378 f = ast_translate(chan->pvt->readtrans, f, 1);
1385 /* Make sure we always return NULL in the future */
1387 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1388 if (chan->generator)
1389 ast_deactivate_generator(chan);
1390 /* End the CDR if appropriate */
1392 ast_cdr_end(chan->cdr);
1393 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1394 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1395 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1397 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1399 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1400 if (chan->_state == AST_STATE_UP) {
1401 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1404 /* Answer the CDR */
1405 ast_setstate(chan, AST_STATE_UP);
1406 ast_cdr_answer(chan->cdr);
1409 /* Run any generator sitting on the line */
1410 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1411 /* Mask generator data temporarily and apply. If there is a timing function, it
1412 will be calling the generator instead */
1415 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1416 if (chan->timingfunc) {
1417 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1418 ast_settimeout(chan, 0, NULL, NULL);
1420 tmp = chan->generatordata;
1421 chan->generatordata = NULL;
1422 generate = chan->generator->generate;
1423 res = generate(chan, tmp, f->datalen, f->samples);
1424 chan->generatordata = tmp;
1426 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1427 ast_deactivate_generator(chan);
1429 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1430 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1431 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1432 ast_settimeout(chan, 160, generator_force, chan);
1435 if (chan->fin & 0x80000000)
1436 ast_frame_dump(chan->name, f, "<<");
1437 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1438 chan->fin &= 0x80000000;
1441 ast_mutex_unlock(&chan->lock);
1445 int ast_indicate(struct ast_channel *chan, int condition)
1448 /* Stop if we're a zombie or need a soft hangup */
1449 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1451 ast_mutex_lock(&chan->lock);
1452 if (chan->pvt->indicate)
1453 res = chan->pvt->indicate(chan, condition);
1454 ast_mutex_unlock(&chan->lock);
1455 if (!chan->pvt->indicate || res) {
1457 * Device does not support (that) indication, lets fake
1458 * it by doing our own tone generation. (PM2002)
1460 if (condition >= 0) {
1461 const struct tone_zone_sound *ts = NULL;
1462 switch (condition) {
1463 case AST_CONTROL_RINGING:
1464 ts = ast_get_indication_tone(chan->zone, "ring");
1466 case AST_CONTROL_BUSY:
1467 ts = ast_get_indication_tone(chan->zone, "busy");
1469 case AST_CONTROL_CONGESTION:
1470 ts = ast_get_indication_tone(chan->zone, "congestion");
1473 if (ts && ts->data[0]) {
1474 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1475 ast_playtones_start(chan,0,ts->data, 1);
1477 } else if (condition == AST_CONTROL_PROGRESS) {
1478 /* ast_playtones_stop(chan); */
1479 } else if (condition == AST_CONTROL_PROCEEDING) {
1480 /* Do nothing, really */
1483 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1487 else ast_playtones_stop(chan);
1492 int ast_recvchar(struct ast_channel *chan, int timeout)
1495 struct ast_frame *f;
1500 if (ast_check_hangup(chan)) return -1;
1501 res = ast_waitfor(chan,ourto);
1502 if (res <= 0) /* if timeout */
1508 if (f == NULL) return -1; /* if hangup */
1509 if ((f->frametype == AST_FRAME_CONTROL) &&
1510 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1511 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1513 c = *((char *)f->data); /* get the data */
1521 int ast_sendtext(struct ast_channel *chan, char *text)
1524 /* Stop if we're a zombie or need a soft hangup */
1525 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1527 CHECK_BLOCKING(chan);
1528 if (chan->pvt->send_text)
1529 res = chan->pvt->send_text(chan, text);
1530 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1534 static int do_senddigit(struct ast_channel *chan, char digit)
1538 if (chan->pvt->send_digit)
1539 res = chan->pvt->send_digit(chan, digit);
1540 if (!chan->pvt->send_digit || res) {
1542 * Device does not support DTMF tones, lets fake
1543 * it by doing our own generation. (PM2002)
1545 static const char* dtmf_tones[] = {
1546 "!941+1336/100,!0/100", /* 0 */
1547 "!697+1209/100,!0/100", /* 1 */
1548 "!697+1336/100,!0/100", /* 2 */
1549 "!697+1477/100,!0/100", /* 3 */
1550 "!770+1209/100,!0/100", /* 4 */
1551 "!770+1336/100,!0/100", /* 5 */
1552 "!770+1477/100,!0/100", /* 6 */
1553 "!852+1209/100,!0/100", /* 7 */
1554 "!852+1336/100,!0/100", /* 8 */
1555 "!852+1477/100,!0/100", /* 9 */
1556 "!697+1633/100,!0/100", /* A */
1557 "!770+1633/100,!0/100", /* B */
1558 "!852+1633/100,!0/100", /* C */
1559 "!941+1633/100,!0/100", /* D */
1560 "!941+1209/100,!0/100", /* * */
1561 "!941+1477/100,!0/100" }; /* # */
1562 if (digit >= '0' && digit <='9')
1563 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1564 else if (digit >= 'A' && digit <= 'D')
1565 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1566 else if (digit == '*')
1567 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1568 else if (digit == '#')
1569 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1572 ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1578 int ast_senddigit(struct ast_channel *chan, char digit)
1580 return do_senddigit(chan, digit);
1583 int ast_prod(struct ast_channel *chan)
1585 struct ast_frame a = { AST_FRAME_VOICE };
1587 /* Send an empty audio frame to get things moving */
1588 if (chan->_state != AST_STATE_UP) {
1589 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1590 a.subclass = chan->pvt->rawwriteformat;
1591 a.data = nothing + AST_FRIENDLY_OFFSET;
1593 if (ast_write(chan, &a))
1594 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1599 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1602 if (!chan->pvt->write_video)
1604 res = ast_write(chan, fr);
1610 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1613 struct ast_frame *f = NULL;
1614 /* Stop if we're a zombie or need a soft hangup */
1615 ast_mutex_lock(&chan->lock);
1616 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1617 ast_mutex_unlock(&chan->lock);
1620 /* Handle any pending masquerades */
1622 if (ast_do_masquerade(chan)) {
1623 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1624 ast_mutex_unlock(&chan->lock);
1629 ast_mutex_unlock(&chan->lock);
1632 if (chan->generatordata) {
1633 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1634 ast_deactivate_generator(chan);
1636 ast_mutex_unlock(&chan->lock);
1640 if (chan->fout & 0x80000000)
1641 ast_frame_dump(chan->name, fr, ">>");
1642 CHECK_BLOCKING(chan);
1643 switch(fr->frametype) {
1644 case AST_FRAME_CONTROL:
1645 /* XXX Interpret control frames XXX */
1646 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1648 case AST_FRAME_DTMF:
1649 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1650 ast_mutex_unlock(&chan->lock);
1651 res = do_senddigit(chan,fr->subclass);
1652 ast_mutex_lock(&chan->lock);
1653 CHECK_BLOCKING(chan);
1655 case AST_FRAME_TEXT:
1656 if (chan->pvt->send_text)
1657 res = chan->pvt->send_text(chan, (char *) fr->data);
1659 case AST_FRAME_VIDEO:
1660 /* XXX Handle translation of video codecs one day XXX */
1661 if (chan->pvt->write_video)
1662 res = chan->pvt->write_video(chan, fr);
1667 if (chan->pvt->write) {
1668 if (chan->pvt->writetrans) {
1669 f = ast_translate(chan->pvt->writetrans, fr, 0);
1673 res = chan->pvt->write(chan, f);
1674 if( chan->monitor &&
1675 chan->monitor->write_stream &&
1676 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1677 #ifndef MONITOR_CONSTANT_DELAY
1678 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1680 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1681 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1682 chan->outsmpl += jump + 2 * f->samples;
1684 chan->outsmpl += f->samples;
1686 int jump = chan->insmpl - chan->outsmpl;
1687 if (jump - MONITOR_DELAY >= 0) {
1688 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1689 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1690 chan->outsmpl += jump;
1692 chan->outsmpl += f->samples;
1694 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1695 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1703 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1704 /* Consider a write failure to force a soft hangup */
1706 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1708 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1709 chan->fout &= 0x80000000;
1714 ast_mutex_unlock(&chan->lock);
1718 int ast_set_write_format(struct ast_channel *chan, int fmts)
1724 ast_mutex_lock(&chan->lock);
1725 native = chan->nativeformats;
1728 res = ast_translator_best_choice(&native, &fmt);
1730 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1731 ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1732 ast_mutex_unlock(&chan->lock);
1736 /* Now we have a good choice for both. We'll write using our native format. */
1737 chan->pvt->rawwriteformat = native;
1738 /* User perspective is fmt */
1739 chan->writeformat = fmt;
1740 /* Free any write translation we have right now */
1741 if (chan->pvt->writetrans)
1742 ast_translator_free_path(chan->pvt->writetrans);
1743 /* Build a translation path from the user write format to the raw writing format */
1744 chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1746 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1747 ast_mutex_unlock(&chan->lock);
1751 int ast_set_read_format(struct ast_channel *chan, int fmts)
1757 ast_mutex_lock(&chan->lock);
1758 native = chan->nativeformats;
1760 /* Find a translation path from the native read format to one of the user's read formats */
1761 res = ast_translator_best_choice(&fmt, &native);
1763 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1764 ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1765 ast_mutex_unlock(&chan->lock);
1769 /* Now we have a good choice for both. We'll write using our native format. */
1770 chan->pvt->rawreadformat = native;
1771 /* User perspective is fmt */
1772 chan->readformat = fmt;
1773 /* Free any read translation we have right now */
1774 if (chan->pvt->readtrans)
1775 ast_translator_free_path(chan->pvt->readtrans);
1776 /* Build a translation path from the raw read format to the user reading format */
1777 chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1779 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n",
1780 chan->name, ast_getformatname(chan->readformat));
1781 ast_mutex_unlock(&chan->lock);
1785 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)
1789 struct ast_channel *chan;
1790 struct ast_frame *f;
1793 chan = ast_request(type, format, data, &cause);
1799 variable = ast_strdupa(oh->variable);
1803 /* FIXME replace this call with strsep NOT*/
1804 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1805 pbx_builtin_setvar( chan, var );
1807 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1808 if (oh->account && *oh->account)
1809 ast_cdr_setaccount(chan, oh->account);
1811 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1813 if (!ast_call(chan, data, 0)) {
1814 while(timeout && (chan->_state != AST_STATE_UP)) {
1815 res = ast_waitfor(chan, timeout);
1817 /* Something not cool, or timed out */
1820 /* If done, break out */
1827 state = AST_CONTROL_HANGUP;
1831 if (f->frametype == AST_FRAME_CONTROL) {
1832 if (f->subclass == AST_CONTROL_RINGING)
1833 state = AST_CONTROL_RINGING;
1834 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1835 state = f->subclass;
1838 } else if (f->subclass == AST_CONTROL_ANSWER) {
1839 state = f->subclass;
1842 } else if (f->subclass == AST_CONTROL_PROGRESS) {
1844 } else if (f->subclass == -1) {
1845 /* Ignore -- just stopping indications */
1847 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1853 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1855 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1857 case AST_CAUSE_BUSY:
1858 state = AST_CONTROL_BUSY;
1860 case AST_CAUSE_CONGESTION:
1861 state = AST_CONTROL_CONGESTION;
1868 if (oh->context && *oh->context)
1869 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1870 if (oh->exten && *oh->exten)
1871 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1872 chan->priority = oh->priority;
1874 if (chan->_state == AST_STATE_UP)
1875 state = AST_CONTROL_ANSWER;
1879 if (chan && res <= 0) {
1881 chan->cdr = ast_cdr_alloc();
1883 ast_cdr_init(chan->cdr, chan);
1887 snprintf(tmp, 256, "%s/%s", type, (char *)data);
1888 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1889 ast_cdr_update(chan);
1890 ast_cdr_start(chan->cdr);
1891 ast_cdr_end(chan->cdr);
1892 /* If the cause wasn't handled properly */
1893 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1894 ast_cdr_failed(chan->cdr);
1896 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1903 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1905 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1908 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1910 struct chanlist *chan;
1911 struct ast_channel *c = NULL;
1918 *cause = AST_CAUSE_NOTDEFINED;
1919 if (ast_mutex_lock(&chlock)) {
1920 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1925 if (!strcasecmp(type, chan->type)) {
1926 capabilities = chan->capabilities;
1928 res = ast_translator_best_choice(&fmt, &capabilities);
1930 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1931 ast_mutex_unlock(&chlock);
1934 ast_mutex_unlock(&chlock);
1935 if (chan->requester)
1936 c = chan->requester(type, capabilities, data, cause);
1938 if (c->_state == AST_STATE_DOWN) {
1939 manager_event(EVENT_FLAG_CALL, "Newchannel",
1943 "CallerIDName: %s\r\n"
1945 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);
1953 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1954 *cause = AST_CAUSE_NOSUCHDRIVER;
1956 ast_mutex_unlock(&chlock);
1960 int ast_parse_device_state(char *device)
1962 char name[AST_CHANNEL_NAME] = "";
1964 struct ast_channel *chan;
1966 chan = ast_channel_walk_locked(NULL);
1968 strncpy(name, chan->name, sizeof(name)-1);
1969 ast_mutex_unlock(&chan->lock);
1970 cut = strchr(name,'-');
1973 if (!strcmp(name, device))
1974 return AST_DEVICE_INUSE;
1975 chan = ast_channel_walk_locked(chan);
1977 return AST_DEVICE_UNKNOWN;
1980 int ast_device_state(char *device)
1982 char tech[AST_MAX_EXTENSION] = "";
1984 struct chanlist *chanls;
1987 strncpy(tech, device, sizeof(tech)-1);
1988 number = strchr(tech, '/');
1990 return AST_DEVICE_INVALID;
1995 if (ast_mutex_lock(&chlock)) {
1996 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2001 if (!strcasecmp(tech, chanls->type)) {
2002 ast_mutex_unlock(&chlock);
2003 if (!chanls->devicestate)
2004 return ast_parse_device_state(device);
2006 res = chanls->devicestate(number);
2007 if (res == AST_DEVICE_UNKNOWN)
2008 return ast_parse_device_state(device);
2013 chanls = chanls->next;
2015 ast_mutex_unlock(&chlock);
2016 return AST_DEVICE_INVALID;
2019 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2021 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2022 If the remote end does not answer within the timeout, then do NOT hang up, but
2025 /* Stop if we're a zombie or need a soft hangup */
2026 ast_mutex_lock(&chan->lock);
2027 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2028 if (chan->pvt->call)
2029 res = chan->pvt->call(chan, addr, timeout);
2030 ast_mutex_unlock(&chan->lock);
2034 int ast_transfer(struct ast_channel *chan, char *dest)
2036 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2037 If the remote end does not answer within the timeout, then do NOT hang up, but
2040 /* Stop if we're a zombie or need a soft hangup */
2041 ast_mutex_lock(&chan->lock);
2042 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2043 if (chan->pvt->transfer) {
2044 res = chan->pvt->transfer(chan, dest);
2050 ast_mutex_unlock(&chan->lock);
2054 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2059 /* XXX Merge with full version? XXX */
2060 /* Stop if we're a zombie or need a soft hangup */
2061 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2067 d = ast_waitstream(c, AST_DIGIT_ANY);
2071 d = ast_waitfordigit(c, to);
2073 d = ast_waitfordigit(c, to);
2081 if (!strchr(enders, d))
2083 if (strchr(enders, d) || (pos >= len)) {
2093 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2098 /* Stop if we're a zombie or need a soft hangup */
2099 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2105 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2109 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2111 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2123 if (!strchr(enders, d))
2125 if (strchr(enders, d) || (pos >= len)) {
2135 int ast_channel_supports_html(struct ast_channel *chan)
2137 if (chan->pvt->send_html)
2142 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
2144 if (chan->pvt->send_html)
2145 return chan->pvt->send_html(chan, subclass, data, datalen);
2149 int ast_channel_sendurl(struct ast_channel *chan, char *url)
2151 if (chan->pvt->send_html)
2152 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2156 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2161 ast_mutex_lock(&peer->lock);
2162 peerf = peer->nativeformats;
2163 ast_mutex_unlock(&peer->lock);
2164 ast_mutex_lock(&chan->lock);
2165 chanf = chan->nativeformats;
2166 ast_mutex_unlock(&chan->lock);
2167 res = ast_translator_best_choice(&peerf, &chanf);
2169 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
2172 /* Set read format on channel */
2173 res = ast_set_read_format(chan, peerf);
2175 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
2178 /* Set write format on peer channel */
2179 res = ast_set_write_format(peer, peerf);
2181 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
2184 /* Now we go the other way */
2185 peerf = peer->nativeformats;
2186 chanf = chan->nativeformats;
2187 res = ast_translator_best_choice(&chanf, &peerf);
2189 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
2192 /* Set writeformat on channel */
2193 res = ast_set_write_format(chan, chanf);
2195 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
2198 /* Set read format on peer channel */
2199 res = ast_set_read_format(peer, chanf);
2201 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
2207 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2209 struct ast_frame null = { AST_FRAME_NULL, };
2211 ast_mutex_lock(&original->lock);
2212 while(ast_mutex_trylock(&clone->lock)) {
2213 ast_mutex_unlock(&original->lock);
2215 ast_mutex_lock(&original->lock);
2217 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2218 clone->name, original->name);
2219 if (original->masq) {
2220 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2221 original->masq->name, original->name);
2222 } else if (clone->masqr) {
2223 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2224 clone->name, clone->masqr->name);
2226 original->masq = clone;
2227 clone->masqr = original;
2228 ast_queue_frame(original, &null);
2229 ast_queue_frame(clone, &null);
2230 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2233 ast_mutex_unlock(&clone->lock);
2234 ast_mutex_unlock(&original->lock);
2238 void ast_change_name(struct ast_channel *chan, char *newname)
2241 strncpy(tmp, chan->name, sizeof(tmp) - 1);
2242 strncpy(chan->name, newname, sizeof(chan->name) - 1);
2243 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2246 /* Clone channel variables from 'clone' channel into 'original' channel
2247 All variables except those related to app_groupcount are cloned
2248 Variables are actually _removed_ from 'clone' channel, presumably
2249 because it will subsequently be destroyed.
2250 Assumes locks will be in place on both channels when called.
2253 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2255 struct ast_var_t *varptr;
2257 /* we need to remove all app_groupcount related variables from the original
2258 channel before merging in the clone's variables; any groups assigned to the
2259 original channel should be released, only those assigned to the clone
2263 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2264 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2265 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2266 ast_var_delete(varptr);
2269 AST_LIST_TRAVERSE_SAFE_END;
2271 /* Append variables from clone channel into original channel */
2272 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2273 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2276 /* Assumes channel will be locked when called */
2277 int ast_do_masquerade(struct ast_channel *original)
2282 struct ast_frame *cur, *prev;
2283 struct ast_channel_pvt *p;
2284 struct ast_callerid tmpcid;
2285 struct ast_channel *clone = original->masq;
2286 int rformat = original->readformat;
2287 int wformat = original->writeformat;
2294 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2295 clone->name, clone->_state, original->name, original->_state);
2297 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2298 the clone channel into the original channel. Start by killing off the original
2299 channel's backend. I'm not sure we're going to keep this function, because
2300 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2302 /* We need the clone's lock, too */
2303 ast_mutex_lock(&clone->lock);
2305 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2307 /* Having remembered the original read/write formats, we turn off any translation on either
2309 free_translation(clone);
2310 free_translation(original);
2313 /* Unlink the masquerade */
2314 original->masq = NULL;
2315 clone->masqr = NULL;
2317 /* Save the original name */
2318 strncpy(orig, original->name, sizeof(orig) - 1);
2319 /* Save the new name */
2320 strncpy(newn, clone->name, sizeof(newn) - 1);
2321 /* Create the masq name */
2322 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2324 /* Copy the name from the clone channel */
2325 strncpy(original->name, newn, sizeof(original->name)-1);
2327 /* Mangle the name of the clone channel */
2328 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2330 /* Notify any managers of the change, first the masq then the other */
2331 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2332 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2336 original->pvt = clone->pvt;
2339 /* Save any pending frames on both sides. Start by counting
2340 * how many we're going to need... */
2342 cur = clone->pvt->readq;
2349 /* If we had any, prepend them to the ones already in the queue, and
2350 * load up the alertpipe */
2352 prev->next = original->pvt->readq;
2353 original->pvt->readq = clone->pvt->readq;
2354 clone->pvt->readq = NULL;
2355 if (original->pvt->alertpipe[1] > -1) {
2357 write(original->pvt->alertpipe[1], &x, sizeof(x));
2360 clone->_softhangup = AST_SOFTHANGUP_DEV;
2363 /* And of course, so does our current state. Note we need not
2364 call ast_setstate since the event manager doesn't really consider
2365 these separate. We do this early so that the clone has the proper
2366 state of the original channel. */
2367 origstate = original->_state;
2368 original->_state = clone->_state;
2369 clone->_state = origstate;
2371 if (clone->pvt->fixup){
2372 res = clone->pvt->fixup(original, clone);
2374 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2377 /* Start by disconnecting the original's physical side */
2378 if (clone->pvt->hangup)
2379 res = clone->pvt->hangup(clone);
2381 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2382 ast_mutex_unlock(&clone->lock);
2386 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2387 /* Mangle the name of the clone channel */
2388 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2389 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2391 /* Keep the same language. */
2392 /* Update the type. */
2393 original->type = clone->type;
2395 for (x=0;x<AST_MAX_FDS;x++) {
2396 original->fds[x] = clone->fds[x];
2398 clone_variables(original, clone);
2399 clone->varshead.first = NULL;
2400 /* Presense of ADSI capable CPE follows clone */
2401 original->adsicpe = clone->adsicpe;
2402 /* Bridge remains the same */
2403 /* CDR fields remain the same */
2404 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2405 /* Application and data remain the same */
2406 /* Clone exception becomes real one, as with fdno */
2407 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2408 original->fdno = clone->fdno;
2409 /* Schedule context remains the same */
2410 /* Stream stuff stays the same */
2411 /* Keep the original state. The fixup code will need to work with it most likely */
2413 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2415 tmpcid = original->cid;
2416 original->cid = clone->cid;
2417 clone->cid = tmpcid;
2419 /* Restore original timing file descriptor */
2420 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2422 /* Our native formats are different now */
2423 original->nativeformats = clone->nativeformats;
2425 /* Context, extension, priority, app data, jump table, remain the same */
2426 /* pvt switches. pbx stays the same, as does next */
2428 /* Set the write format */
2429 ast_set_write_format(original, wformat);
2431 /* Set the read format */
2432 ast_set_read_format(original, rformat);
2434 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2436 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2437 can fix up everything as best as possible */
2438 if (original->pvt->fixup) {
2439 res = original->pvt->fixup(clone, original);
2441 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2442 original->type, original->name);
2443 ast_mutex_unlock(&clone->lock);
2447 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2448 original->type, original->name);
2450 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2451 a zombie so nothing tries to touch it. If it's already been marked as a
2452 zombie, then free it now (since it already is considered invalid). */
2453 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2454 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2455 ast_mutex_unlock(&clone->lock);
2456 ast_channel_free(clone);
2457 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2459 struct ast_frame null_frame = { AST_FRAME_NULL, };
2460 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2461 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2462 ast_queue_frame(clone, &null_frame);
2463 ast_mutex_unlock(&clone->lock);
2466 /* Signal any blocker */
2467 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2468 pthread_kill(original->blocker, SIGURG);
2469 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2470 original->name, original->_state);
2474 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2477 if (chan->cid.cid_num)
2478 free(chan->cid.cid_num);
2479 if (ast_strlen_zero(callerid))
2480 chan->cid.cid_num = NULL;
2482 chan->cid.cid_num = strdup(callerid);
2485 if (chan->cid.cid_name)
2486 free(chan->cid.cid_name);
2487 if (ast_strlen_zero(calleridname))
2488 chan->cid.cid_name = NULL;
2490 chan->cid.cid_name = strdup(calleridname);
2493 if (chan->cid.cid_ani)
2494 free(chan->cid.cid_ani);
2495 if (ast_strlen_zero(ani))
2496 chan->cid.cid_ani = NULL;
2498 chan->cid.cid_ani = strdup(ani);
2501 ast_cdr_setcid(chan->cdr, chan);
2502 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2505 "CallerIDName: %s\r\n"
2507 chan->name, chan->cid.cid_num ?
2508 chan->cid.cid_num : "<Unknown>",
2509 chan->cid.cid_name ?
2510 chan->cid.cid_name : "<Unknown>",
2514 int ast_setstate(struct ast_channel *chan, int state)
2516 if (chan->_state != state) {
2517 int oldstate = chan->_state;
2518 chan->_state = state;
2519 if (oldstate == AST_STATE_DOWN) {
2520 ast_device_state_changed(chan->name);
2521 manager_event(EVENT_FLAG_CALL, "Newchannel",
2525 "CallerIDName: %s\r\n"
2527 chan->name, ast_state2str(chan->_state),
2528 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2529 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2532 manager_event(EVENT_FLAG_CALL, "Newstate",
2536 "CallerIDName: %s\r\n"
2538 chan->name, ast_state2str(chan->_state),
2539 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2540 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2547 static long tvdiff(struct timeval *now, struct timeval *then)
2549 return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2552 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2554 struct ast_channel *bridged;
2555 bridged = chan->_bridge;
2556 if (bridged && bridged->pvt->bridged_channel)
2557 bridged = bridged->pvt->bridged_channel(chan, bridged);
2561 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2563 int res=0, min=0, sec=0,check=0;
2565 check = ast_autoservice_start(peer);
2570 if (remain / 60 > 1) {
2578 if (!strcmp(sound,"timeleft")) {
2579 res = ast_streamfile(chan, "vm-youhave", chan->language);
2580 res = ast_waitstream(chan, "");
2582 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2583 res = ast_streamfile(chan, "queue-minutes", chan->language);
2584 res = ast_waitstream(chan, "");
2587 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2588 res = ast_streamfile(chan, "queue-seconds", chan->language);
2589 res = ast_waitstream(chan, "");
2592 res = ast_streamfile(chan, sound, chan->language);
2593 res = ast_waitstream(chan, "");
2596 check = ast_autoservice_stop(peer);
2599 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)
2601 /* Copy voice back and forth between the two channels. Give the peer
2602 the ability to transfer calls with '#<extension' syntax. */
2604 struct ast_channel *cs[3];
2606 struct ast_frame *f;
2607 struct ast_channel *who = NULL;
2611 int o0nativeformats;
2612 int o1nativeformats;
2613 struct timeval start_time,precise_now;
2614 long elapsed_ms=0, time_left_ms=0;
2615 int playit=0, playitagain=1, first_time=1;
2617 flags = (config->allowdisconnect_out||config->allowredirect_out ? AST_BRIDGE_DTMF_CHANNEL_0 : 0) + (config->allowdisconnect_in||config->allowredirect_in ? AST_BRIDGE_DTMF_CHANNEL_1 : 0);
2620 firstpass = config->firstpass;
2621 config->firstpass = 0;
2624 gettimeofday(&start_time,NULL);
2625 time_left_ms = config->timelimit;
2627 if (config->play_to_caller && config->start_sound && firstpass)
2628 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2629 if (config->play_to_callee && config->start_sound && firstpass)
2630 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2632 /* Stop if we're a zombie or need a soft hangup */
2633 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))
2636 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2637 c0->name, c0->_bridge->name);
2641 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2642 c1->name, c1->_bridge->name);
2646 /* Keep track of bridge */
2652 manager_event(EVENT_FLAG_CALL, "Link",
2656 "Uniqueid2: %s\r\n",
2657 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2658 o1nativeformats = c1->nativeformats;
2659 o0nativeformats = c0->nativeformats;
2660 for (/* ever */;;) {
2662 if (config->timelimit) {
2663 gettimeofday(&precise_now,NULL);
2664 elapsed_ms = tvdiff(&precise_now,&start_time);
2665 time_left_ms = config->timelimit - elapsed_ms;
2667 if (playitagain && (config->play_to_caller || config->play_to_callee) && (config->play_warning && time_left_ms <= config->play_warning)) {
2668 /* narrowing down to the end */
2669 if (config->warning_freq == 0) {
2673 } else if (first_time) {
2677 if ((time_left_ms % config->warning_freq) <= 50) {
2682 if (time_left_ms <= 0) {
2683 if (config->play_to_caller && config->end_sound)
2684 bridge_playfile(c0,c1,config->end_sound,0);
2685 if (config->play_to_callee && config->end_sound)
2686 bridge_playfile(c1,c0,config->end_sound,0);
2692 if (time_left_ms >= 5000 && playit) {
2693 if (config->play_to_caller && config->warning_sound && config->play_warning)
2694 bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
2695 if (config->play_to_callee && config->warning_sound && config->play_warning)
2696 bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
2701 /* Stop if we're a zombie or need a soft hangup */
2702 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)) {
2706 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");
2709 if (c0->pvt->bridge && config->timelimit==0 &&
2710 (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2711 /* Looks like they share a bridge code */
2712 if (option_verbose > 2)
2713 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2714 if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2717 manager_event(EVENT_FLAG_CALL, "Unlink",
2721 "Uniqueid2: %s\r\n",
2722 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2723 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2726 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
2727 my not wanting to bridge */
2728 if ((res != -2) && (res != -3))
2729 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2730 if (res != -3) nativefailed++;
2733 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
2734 !(c0->generator || c1->generator)) {
2735 if (ast_channel_make_compatible(c0, c1)) {
2736 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2737 manager_event(EVENT_FLAG_CALL, "Unlink",
2741 "Uniqueid2: %s\r\n",
2742 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2745 o0nativeformats = c0->nativeformats;
2746 o1nativeformats = c1->nativeformats;
2748 who = ast_waitfor_n(cs, 2, &to);
2750 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2758 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2762 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2766 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2769 if ((f->frametype == AST_FRAME_VOICE) ||
2770 (f->frametype == AST_FRAME_TEXT) ||
2771 (f->frametype == AST_FRAME_VIDEO) ||
2772 (f->frametype == AST_FRAME_IMAGE) ||
2773 (f->frametype == AST_FRAME_DTMF)) {
2774 if ((f->frametype == AST_FRAME_DTMF) &&
2775 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2777 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2780 /* Take out of conference mode */
2782 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2788 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2792 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2799 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2801 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2805 /* Don't copy packets if there is a generator on either one, since they're
2806 not supposed to be listening anyway */
2815 /* Swap who gets priority */
2822 manager_event(EVENT_FLAG_CALL, "Unlink",
2826 "Uniqueid2: %s\r\n",
2827 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2828 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2832 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2835 if (chan->pvt->setoption) {
2836 res = chan->pvt->setoption(chan, option, data, datalen);
2844 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2845 intermediate packets. XXX */
2846 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2852 struct tonepair_def {
2859 struct tonepair_state {
2867 unsigned char offset[AST_FRIENDLY_OFFSET];
2871 static void tonepair_release(struct ast_channel *chan, void *params)
2873 struct tonepair_state *ts = params;
2875 ast_set_write_format(chan, ts->origwfmt);
2880 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2882 struct tonepair_state *ts;
2883 struct tonepair_def *td = params;
2884 ts = malloc(sizeof(struct tonepair_state));
2887 memset(ts, 0, sizeof(struct tonepair_state));
2888 ts->origwfmt = chan->writeformat;
2889 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2890 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2891 tonepair_release(NULL, ts);
2894 ts->freq1 = td->freq1;
2895 ts->freq2 = td->freq2;
2896 ts->duration = td->duration;
2899 /* Let interrupts interrupt :) */
2900 ast_set_flag(chan, AST_FLAG_WRITE_INT);
2904 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2906 struct tonepair_state *ts = data;
2909 /* we need to prepare a frame with 16 * timelen samples as we're
2910 * generating SLIN audio
2914 if (len > sizeof(ts->data) / 2 - 1) {
2915 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2918 memset(&ts->f, 0, sizeof(ts->f));
2919 for (x=0;x<len/2;x++) {
2920 ts->data[x] = ts->vol * (
2921 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2922 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2925 ts->f.frametype = AST_FRAME_VOICE;
2926 ts->f.subclass = AST_FORMAT_SLINEAR;
2927 ts->f.datalen = len;
2928 ts->f.samples = samples;
2929 ts->f.offset = AST_FRIENDLY_OFFSET;
2930 ts->f.data = ts->data;
2931 ast_write(chan, &ts->f);
2933 if (ts->duration > 0) {
2934 if (ts->pos >= ts->duration * 8)
2940 static struct ast_generator tonepair = {
2941 alloc: tonepair_alloc,
2942 release: tonepair_release,
2943 generate: tonepair_generator,
2946 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2948 struct tonepair_def d = { 0, };
2951 d.duration = duration;
2956 if (ast_activate_generator(chan, &tonepair, &d))
2961 void ast_tonepair_stop(struct ast_channel *chan)
2963 ast_deactivate_generator(chan);
2966 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2968 struct ast_frame *f;
2970 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2973 /* Give us some wiggle room */
2974 while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2984 unsigned int ast_get_group(char *s)
2989 int start=0, finish=0,x;
2990 unsigned int group = 0;
2991 copy = ast_strdupa(s);
2993 ast_log(LOG_ERROR, "Out of memory\n");
2998 while((piece = strsep(&c, ","))) {
2999 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
3001 } else if (sscanf(piece, "%d", &start)) {
3005 ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'. Using '0'\n", s,piece);
3008 for (x=start;x<=finish;x++) {
3009 if ((x > 31) || (x < 0)) {
3010 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 31)\n", x);
3018 static int (*ast_moh_start_ptr)(struct ast_channel *, char *) = NULL;
3019 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
3020 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
3023 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, char *),
3024 void (*stop_ptr)(struct ast_channel *),
3025 void (*cleanup_ptr)(struct ast_channel *)
3028 ast_moh_start_ptr = start_ptr;
3029 ast_moh_stop_ptr = stop_ptr;
3030 ast_moh_cleanup_ptr = cleanup_ptr;
3033 void ast_uninstall_music_functions(void)
3035 ast_moh_start_ptr = NULL;
3036 ast_moh_stop_ptr = NULL;
3037 ast_moh_cleanup_ptr = NULL;
3040 /*! Turn on/off music on hold on a given channel */
3042 int ast_moh_start(struct ast_channel *chan, char *mclass)
3044 if(ast_moh_start_ptr)
3045 return ast_moh_start_ptr(chan, mclass);
3047 if (option_verbose > 2)
3048 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : "default");
3053 void ast_moh_stop(struct ast_channel *chan)
3055 if(ast_moh_stop_ptr)
3056 ast_moh_stop_ptr(chan);
3059 void ast_moh_cleanup(struct ast_channel *chan)
3061 if(ast_moh_cleanup_ptr)
3062 ast_moh_cleanup_ptr(chan);
3065 void ast_channels_init(void)
3067 ast_cli_register(&cli_show_channeltypes);