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/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 #ifdef ZAPTEL_OPTIMIZATIONS
42 #include <sys/ioctl.h>
44 #include <linux/zaptel.h>
47 #endif /* __linux__ */
49 #error "You need newer zaptel! Please cvs update zaptel"
53 /* uncomment if you have problems with 'monitoring' synchronized files */
55 #define MONITOR_CONSTANT_DELAY
56 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
59 static int shutting_down = 0;
60 static int uniqueint = 0;
62 unsigned long global_fin = 0, global_fout = 0;
64 /* XXX Lock appropriately in more functions XXX */
70 struct ast_channel * (*requester)(const char *type, int format, void *data, int *cause);
71 int (*devicestate)(void *data);
72 struct chanlist *next;
74 struct ast_channel *channels = NULL;
76 /* Protect the channel list (highly unlikely that two things would change
77 it at the same time, but still! */
79 AST_MUTEX_DEFINE_STATIC(chlock);
81 int ast_check_hangup(struct ast_channel *chan)
85 /* if soft hangup flag, return true */
86 if (chan->_softhangup) return 1;
87 /* if no private structure, return true */
88 if (!chan->pvt->pvt) return 1;
89 /* if no hangup scheduled, just return here */
90 if (!chan->whentohangup) return 0;
91 time(&myt); /* get current time */
92 /* return, if not yet */
93 if (chan->whentohangup > myt) return 0;
94 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
98 static int ast_check_hangup_locked(struct ast_channel *chan)
101 ast_mutex_lock(&chan->lock);
102 res = ast_check_hangup(chan);
103 ast_mutex_unlock(&chan->lock);
107 void ast_begin_shutdown(int hangup)
109 struct ast_channel *c;
112 ast_mutex_lock(&chlock);
115 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
118 ast_mutex_unlock(&chlock);
122 int ast_active_channels(void)
124 struct ast_channel *c;
126 ast_mutex_lock(&chlock);
132 ast_mutex_unlock(&chlock);
136 void ast_cancel_shutdown(void)
141 int ast_shutting_down(void)
143 return shutting_down;
146 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
152 chan->whentohangup = myt + offset;
154 chan->whentohangup = 0;
158 int ast_channel_register(const char *type, const char *description, int capabilities,
159 struct ast_channel *(*requester)(const char *type, int format, void *data, int *cause))
161 return ast_channel_register_ex(type, description, capabilities, requester, NULL);
164 int ast_channel_register_ex(const char *type, const char *description, int capabilities,
165 struct ast_channel *(*requester)(const char *type, int format, void *data, int *cause),
166 int (*devicestate)(void *data))
168 struct chanlist *chan, *last=NULL;
169 if (ast_mutex_lock(&chlock)) {
170 ast_log(LOG_WARNING, "Unable to lock channel list\n");
175 if (!strcasecmp(type, chan->type)) {
176 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
177 ast_mutex_unlock(&chlock);
183 chan = malloc(sizeof(struct chanlist));
185 ast_log(LOG_WARNING, "Out of memory\n");
186 ast_mutex_unlock(&chlock);
189 strncpy(chan->type, type, sizeof(chan->type)-1);
190 strncpy(chan->description, description, sizeof(chan->description)-1);
191 chan->capabilities = capabilities;
192 chan->requester = requester;
193 chan->devicestate = devicestate;
200 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
201 else if (option_verbose > 1)
202 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
203 ast_mutex_unlock(&chlock);
207 char *ast_state2str(int state)
209 /* XXX Not reentrant XXX */
210 static char localtmp[256];
214 case AST_STATE_RESERVED:
216 case AST_STATE_OFFHOOK:
218 case AST_STATE_DIALING:
222 case AST_STATE_RINGING:
229 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
235 int ast_best_codec(int fmts)
237 /* This just our opinion, expressed in code. We are asked to choose
238 the best codec to use, given no information */
242 /* Okay, ulaw is used by all telephony equipment, so start with it */
244 /* Unless of course, you're a silly European, so then prefer ALAW */
246 /* Okay, well, signed linear is easy to translate into other stuff */
248 /* G.726 is standard ADPCM */
250 /* ADPCM has great sound quality and is still pretty easy to translate */
252 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
253 translate and sounds pretty good */
255 /* iLBC is not too bad */
257 /* Speex is free, but computationally more expensive than GSM */
259 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
262 /* G.729a is faster than 723 and slightly less expensive */
264 /* Down to G.723.1 which is proprietary but at least designed for voice */
269 for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
272 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
276 struct ast_channel *ast_channel_alloc(int needqueue)
278 struct ast_channel *tmp;
279 struct ast_channel_pvt *pvt;
282 struct varshead *headp;
285 /* If shutting down, don't allocate any new channels */
288 ast_mutex_lock(&chlock);
289 tmp = malloc(sizeof(struct ast_channel));
291 memset(tmp, 0, sizeof(struct ast_channel));
292 pvt = malloc(sizeof(struct ast_channel_pvt));
294 memset(pvt, 0, sizeof(struct ast_channel_pvt));
295 tmp->sched = sched_context_create();
297 for (x=0;x<AST_MAX_FDS - 1;x++)
299 #ifdef ZAPTEL_OPTIMIZATIONS
300 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
301 if (tmp->timingfd > -1) {
302 /* Check if timing interface supports new
305 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
312 pipe(pvt->alertpipe)) {
313 ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
320 flags = fcntl(pvt->alertpipe[0], F_GETFL);
321 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
322 flags = fcntl(pvt->alertpipe[1], F_GETFL);
323 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
325 /* Make sure we've got it done right if they don't */
326 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
327 /* Always watch the alertpipe */
328 tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
329 /* And timing pipe */
330 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
331 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
334 tmp->_state = AST_STATE_DOWN;
338 tmp->fin = global_fin;
339 tmp->fout = global_fout;
340 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
341 headp=&tmp->varshead;
342 ast_mutex_init(&tmp->lock);
343 AST_LIST_HEAD_INIT(headp);
344 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
345 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
346 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
348 tmp->amaflags = ast_default_amaflags;
349 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
350 tmp->next = channels;
354 ast_log(LOG_WARNING, "Unable to create schedule context\n");
359 ast_log(LOG_WARNING, "Out of memory\n");
364 ast_log(LOG_WARNING, "Out of memory\n");
365 ast_mutex_unlock(&chlock);
369 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
372 struct ast_frame *prev, *cur;
375 /* Build us a copy and free the original one */
378 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
381 ast_mutex_lock(&chan->lock);
383 cur = chan->pvt->readq;
385 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
386 /* Don't bother actually queueing anything after a hangup */
388 ast_mutex_unlock(&chan->lock);
395 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
396 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
397 if (fin->frametype != AST_FRAME_VOICE) {
398 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
401 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
403 ast_mutex_unlock(&chan->lock);
410 chan->pvt->readq = f;
411 if (chan->pvt->alertpipe[1] > -1) {
412 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
413 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
414 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
415 #ifdef ZAPTEL_OPTIMIZATIONS
416 } else if (chan->timingfd > -1) {
417 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
419 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
420 pthread_kill(chan->blocker, SIGURG);
422 ast_mutex_unlock(&chan->lock);
426 int ast_queue_hangup(struct ast_channel *chan)
428 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
429 chan->_softhangup |= AST_SOFTHANGUP_DEV;
430 return ast_queue_frame(chan, &f);
433 int ast_queue_control(struct ast_channel *chan, int control)
435 struct ast_frame f = { AST_FRAME_CONTROL, };
436 f.subclass = control;
437 return ast_queue_frame(chan, &f);
440 int ast_channel_defer_dtmf(struct ast_channel *chan)
444 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
445 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
450 void ast_channel_undefer_dtmf(struct ast_channel *chan)
453 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
456 struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
458 /* Returns next channel (locked) */
459 struct ast_channel *l, *ret;
463 ast_mutex_lock(&chlock);
467 if (ast_mutex_trylock(&l->lock)) {
469 ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
471 ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
472 ast_mutex_unlock(&chlock);
481 ast_mutex_unlock(&chlock);
490 if (ast_mutex_trylock(&ret->lock)) {
492 ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
494 ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
495 ast_mutex_unlock(&chlock);
504 ast_mutex_unlock(&chlock);
509 struct ast_channel *ast_get_channel_by_name_locked(char *channame)
511 struct ast_channel *chan;
512 chan = ast_channel_walk_locked(NULL);
514 if (!strcasecmp(chan->name, channame))
516 ast_mutex_unlock(&chan->lock);
517 chan = ast_channel_walk_locked(chan);
522 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
523 int (*cond)(void*), void *data )
528 if( cond && ((*cond)(data) == 0 ) )
530 ms = ast_waitfor(chan, ms);
543 int ast_safe_sleep(struct ast_channel *chan, int ms)
547 ms = ast_waitfor(chan, ms);
560 static void free_cid(struct ast_callerid *cid)
571 free(cid->cid_rdnis);
574 void ast_channel_free(struct ast_channel *chan)
576 struct ast_channel *last=NULL, *cur;
578 struct ast_var_t *vardata;
579 struct ast_frame *f, *fp;
580 struct varshead *headp;
581 char name[AST_CHANNEL_NAME];
583 headp=&chan->varshead;
585 ast_mutex_lock(&chlock);
590 last->next = cur->next;
592 channels = cur->next;
599 ast_log(LOG_WARNING, "Unable to find channel in list\n");
601 /* Lock and unlock the channel just to be sure nobody
602 has it locked still */
603 ast_mutex_lock(&cur->lock);
604 ast_mutex_unlock(&cur->lock);
607 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
609 strncpy(name, chan->name, sizeof(name)-1);
611 /* Stop monitoring */
613 chan->monitor->stop( chan, 0 );
616 /* Free translatosr */
617 if (chan->pvt->readtrans)
618 ast_translator_free_path(chan->pvt->readtrans);
619 if (chan->pvt->writetrans)
620 ast_translator_free_path(chan->pvt->writetrans);
622 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
623 free_cid(&chan->cid);
624 ast_mutex_destroy(&chan->lock);
625 /* Close pipes if appropriate */
626 if ((fd = chan->pvt->alertpipe[0]) > -1)
628 if ((fd = chan->pvt->alertpipe[1]) > -1)
630 if ((fd = chan->timingfd) > -1)
632 f = chan->pvt->readq;
633 chan->pvt->readq = NULL;
640 /* loop over the variables list, freeing all data and deleting list items */
641 /* no need to lock the list, as the channel is already locked */
643 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
644 vardata = AST_LIST_FIRST(headp);
645 AST_LIST_REMOVE_HEAD(headp, entries);
646 /* printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata)); */
647 ast_var_delete(vardata);
654 ast_mutex_unlock(&chlock);
656 ast_device_state_changed(name);
659 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
662 struct ast_frame f = { AST_FRAME_NULL };
664 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
665 /* Inform channel driver that we need to be hung up, if it cares */
666 chan->_softhangup |= cause;
667 ast_queue_frame(chan, &f);
668 /* Interrupt any poll call or such */
669 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
670 pthread_kill(chan->blocker, SIGURG);
674 int ast_softhangup(struct ast_channel *chan, int cause)
677 ast_mutex_lock(&chan->lock);
678 res = ast_softhangup_nolock(chan, cause);
679 ast_mutex_unlock(&chan->lock);
683 static void free_translation(struct ast_channel *clone)
685 if (clone->pvt->writetrans)
686 ast_translator_free_path(clone->pvt->writetrans);
687 if (clone->pvt->readtrans)
688 ast_translator_free_path(clone->pvt->readtrans);
689 clone->pvt->writetrans = NULL;
690 clone->pvt->readtrans = NULL;
691 clone->pvt->rawwriteformat = clone->nativeformats;
692 clone->pvt->rawreadformat = clone->nativeformats;
695 int ast_hangup(struct ast_channel *chan)
698 /* Don't actually hang up a channel that will masquerade as someone else, or
699 if someone is going to masquerade as us */
700 ast_mutex_lock(&chan->lock);
702 if (ast_do_masquerade(chan))
703 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
707 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
708 ast_mutex_unlock(&chan->lock);
711 /* If this channel is one which will be masqueraded into something,
712 mark it as a zombie already, so we know to free it later */
714 ast_set_flag(chan, AST_FLAG_ZOMBIE);
715 ast_mutex_unlock(&chan->lock);
718 free_translation(chan);
720 ast_closestream(chan->stream);
722 ast_closestream(chan->vstream);
724 sched_context_destroy(chan->sched);
725 /* Clear any tone stuff remaining */
726 if (chan->generatordata)
727 chan->generator->release(chan, chan->generatordata);
728 chan->generatordata = NULL;
729 chan->generator = NULL;
731 /* End the CDR if it hasn't already */
732 ast_cdr_end(chan->cdr);
733 /* Post and Free the CDR */
734 ast_cdr_post(chan->cdr);
735 ast_cdr_free(chan->cdr);
737 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
738 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
739 "is blocked by thread %ld in procedure %s! Expect a failure\n",
740 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
743 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
745 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
746 if (chan->pvt->hangup)
747 res = chan->pvt->hangup(chan);
750 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
752 ast_mutex_unlock(&chan->lock);
753 manager_event(EVENT_FLAG_CALL, "Hangup",
757 chan->name, chan->uniqueid, chan->hangupcause);
758 ast_channel_free(chan);
762 void ast_channel_unregister(const char *type)
764 struct chanlist *chan, *last=NULL;
766 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
767 if (ast_mutex_lock(&chlock)) {
768 ast_log(LOG_WARNING, "Unable to lock channel list\n");
771 if (option_verbose > 1)
772 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", type);
776 if (!strcasecmp(chan->type, type)) {
778 last->next = chan->next;
780 backends = backends->next;
782 ast_mutex_unlock(&chlock);
788 ast_mutex_unlock(&chlock);
791 int ast_answer(struct ast_channel *chan)
794 ast_mutex_lock(&chan->lock);
795 /* Stop if we're a zombie or need a soft hangup */
796 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
797 ast_mutex_unlock(&chan->lock);
800 switch(chan->_state) {
801 case AST_STATE_RINGING:
803 if (chan->pvt->answer)
804 res = chan->pvt->answer(chan);
805 ast_setstate(chan, AST_STATE_UP);
807 ast_cdr_answer(chan->cdr);
808 ast_mutex_unlock(&chan->lock);
813 ast_cdr_answer(chan->cdr);
816 ast_mutex_unlock(&chan->lock);
822 void ast_deactivate_generator(struct ast_channel *chan)
824 ast_mutex_lock(&chan->lock);
825 if (chan->generatordata) {
826 if (chan->generator && chan->generator->release)
827 chan->generator->release(chan, chan->generatordata);
828 chan->generatordata = NULL;
829 chan->generator = NULL;
830 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
831 ast_settimeout(chan, 0, NULL, NULL);
833 ast_mutex_unlock(&chan->lock);
836 static int generator_force(void *data)
838 /* Called if generator doesn't have data */
841 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
842 struct ast_channel *chan = data;
843 tmp = chan->generatordata;
844 chan->generatordata = NULL;
845 generate = chan->generator->generate;
846 res = generate(chan, tmp, 0, 160);
847 chan->generatordata = tmp;
849 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
850 ast_deactivate_generator(chan);
855 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
858 ast_mutex_lock(&chan->lock);
859 if (chan->generatordata) {
860 if (chan->generator && chan->generator->release)
861 chan->generator->release(chan, chan->generatordata);
862 chan->generatordata = NULL;
865 if ((chan->generatordata = gen->alloc(chan, params))) {
866 ast_settimeout(chan, 160, generator_force, chan);
867 chan->generator = gen;
871 ast_mutex_unlock(&chan->lock);
875 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
877 /* Wait for x amount of time on a file descriptor to have input. */
878 struct timeval start, now;
885 pfds = alloca(sizeof(struct pollfd) * n);
887 ast_log(LOG_WARNING, "alloca failed! bad things will happen.\n");
891 gettimeofday(&start, NULL);
896 pfds[y].events = POLLIN | POLLPRI;
900 res = poll(pfds, y, *ms);
902 /* Simulate a timeout if we were interrupted */
912 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
925 gettimeofday(&now, NULL);
926 passed = (now.tv_sec - start.tv_sec) * 1000;
927 passed += (now.tv_usec - start.tv_usec) / 1000;
936 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
937 int *exception, int *outfd, int *ms)
939 /* Wait for x amount of time on a file descriptor to have input. */
940 struct timeval start, end;
947 long whentohangup = 0, havewhen = 0, diff;
948 struct ast_channel *winner = NULL;
950 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
952 ast_log(LOG_WARNING, "alloca failed! bad things will happen.\n");
962 /* Perform any pending masquerades */
964 ast_mutex_lock(&c[x]->lock);
965 if (c[x]->whentohangup) {
968 diff = c[x]->whentohangup - now;
969 if (!havewhen || (diff < whentohangup)) {
975 if (ast_do_masquerade(c[x])) {
976 ast_log(LOG_WARNING, "Masquerade failed\n");
978 ast_mutex_unlock(&c[x]->lock);
982 ast_mutex_unlock(&c[x]->lock);
988 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
989 rms = whentohangup * 1000;
994 for (y=0;y<AST_MAX_FDS;y++) {
995 if (c[x]->fds[y] > -1) {
996 pfds[max].fd = c[x]->fds[y];
997 pfds[max].events = POLLIN | POLLPRI;
1001 CHECK_BLOCKING(c[x]);
1003 for (x=0;x<nfds; x++) {
1005 pfds[max].fd = fds[x];
1006 pfds[max].events = POLLIN | POLLPRI;
1011 gettimeofday(&start, NULL);
1012 res = poll(pfds, max, rms);
1015 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1016 /* Simulate a timeout if we were interrupted */
1020 /* Just an interrupt */
1032 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1033 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1034 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1038 for (y=0;y<AST_MAX_FDS;y++) {
1039 if (c[x]->fds[y] > -1) {
1040 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1042 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1044 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1051 for (x=0;x<nfds;x++) {
1053 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1068 gettimeofday(&end, NULL);
1069 diff = (end.tv_sec - start.tv_sec) * 1000;
1070 diff += (end.tv_usec - start.tv_usec) / 1000;
1079 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1081 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1084 int ast_waitfor(struct ast_channel *c, int ms)
1086 struct ast_channel *chan;
1088 chan = ast_waitfor_n(&c, 1, &ms);
1098 char ast_waitfordigit(struct ast_channel *c, int ms)
1100 /* XXX Should I be merged with waitfordigit_full XXX */
1101 struct ast_frame *f;
1103 /* Stop if we're a zombie or need a soft hangup */
1104 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1106 /* Wait for a digit, no more than ms milliseconds total. */
1107 while(ms && !result) {
1108 ms = ast_waitfor(c, ms);
1109 if (ms < 0) /* Error */
1112 /* Read something */
1115 if (f->frametype == AST_FRAME_DTMF)
1116 result = f->subclass;
1125 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1128 #ifdef ZAPTEL_OPTIMIZATIONS
1129 if (c->timingfd > -1) {
1134 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1135 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1136 c->timingfunc = func;
1137 c->timingdata = data;
1142 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1144 struct ast_frame *f;
1145 struct ast_channel *rchan;
1148 /* Stop if we're a zombie or need a soft hangup */
1149 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1151 /* Wait for a digit, no more than ms milliseconds total. */
1153 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1154 if ((!rchan) && (outfd < 0) && (ms)) {
1155 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1157 } else if (outfd > -1) {
1158 /* The FD we were watching has something waiting */
1166 switch(f->frametype) {
1167 case AST_FRAME_DTMF:
1171 case AST_FRAME_CONTROL:
1172 switch(f->subclass) {
1173 case AST_CONTROL_HANGUP:
1176 case AST_CONTROL_RINGING:
1177 case AST_CONTROL_ANSWER:
1181 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1183 case AST_FRAME_VOICE:
1184 /* Write audio if appropriate */
1186 write(audiofd, f->data, f->datalen);
1192 return 0; // Time is up
1195 struct ast_frame *ast_read(struct ast_channel *chan)
1197 struct ast_frame *f = NULL;
1199 #ifdef ZAPTEL_OPTIMIZATIONS
1200 int (*func)(void *);
1204 static struct ast_frame null_frame =
1209 ast_mutex_lock(&chan->lock);
1211 if (ast_do_masquerade(chan)) {
1212 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1216 ast_mutex_unlock(&chan->lock);
1220 /* Stop if we're a zombie or need a soft hangup */
1221 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1222 if (chan->generator)
1223 ast_deactivate_generator(chan);
1224 ast_mutex_unlock(&chan->lock);
1228 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1229 /* We have DTMF that has been deferred. Return it now */
1230 chan->dtmff.frametype = AST_FRAME_DTMF;
1231 chan->dtmff.subclass = chan->dtmfq[0];
1232 /* Drop first digit */
1233 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1234 ast_mutex_unlock(&chan->lock);
1235 return &chan->dtmff;
1238 /* Read and ignore anything on the alertpipe, but read only
1239 one sizeof(blah) per frame that we send from it */
1240 if (chan->pvt->alertpipe[0] > -1) {
1241 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1243 #ifdef ZAPTEL_OPTIMIZATIONS
1244 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1245 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1247 /* IF we can't get event, assume it's an expired as-per the old interface */
1248 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1250 blah = ZT_EVENT_TIMER_EXPIRED;
1252 if (blah == ZT_EVENT_TIMER_PING) {
1254 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1256 if (!chan->pvt->readq || !chan->pvt->readq->next) {
1257 /* Acknowledge PONG unless we need it again */
1259 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1261 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1262 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1265 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1266 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1267 func = chan->timingfunc;
1268 data = chan->timingdata;
1269 ast_mutex_unlock(&chan->lock);
1272 ast_log(LOG_DEBUG, "Calling private function\n");
1277 ast_mutex_lock(&chan->lock);
1278 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1279 chan->timingdata = NULL;
1280 ast_mutex_unlock(&chan->lock);
1285 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1288 /* Check for pending read queue */
1289 if (chan->pvt->readq) {
1290 f = chan->pvt->readq;
1291 chan->pvt->readq = f->next;
1292 /* Interpret hangup and return NULL */
1293 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1298 chan->blocker = pthread_self();
1299 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1300 if (chan->pvt->exception)
1301 f = chan->pvt->exception(chan);
1303 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1306 /* Clear the exception flag */
1307 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1309 if (chan->pvt->read)
1310 f = chan->pvt->read(chan);
1312 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1316 if (f && (f->frametype == AST_FRAME_VOICE)) {
1317 if (!(f->subclass & chan->nativeformats)) {
1318 /* This frame can't be from the current native formats -- drop it on the
1320 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));
1324 if (chan->monitor && chan->monitor->read_stream ) {
1325 #ifndef MONITOR_CONSTANT_DELAY
1326 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1328 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1329 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1330 chan->insmpl += jump + 2 * f->samples;
1332 chan->insmpl+= f->samples;
1334 int jump = chan->outsmpl - chan->insmpl;
1335 if (jump - MONITOR_DELAY >= 0) {
1336 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1337 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1338 chan->insmpl += jump;
1340 chan->insmpl += f->samples;
1342 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1343 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1345 if (chan->pvt->readtrans) {
1346 f = ast_translate(chan->pvt->readtrans, f, 1);
1353 /* Make sure we always return NULL in the future */
1355 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1356 if (chan->generator)
1357 ast_deactivate_generator(chan);
1358 /* End the CDR if appropriate */
1360 ast_cdr_end(chan->cdr);
1361 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1362 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1363 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1365 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1367 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1368 if (chan->_state == AST_STATE_UP) {
1369 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1372 /* Answer the CDR */
1373 ast_setstate(chan, AST_STATE_UP);
1374 ast_cdr_answer(chan->cdr);
1377 /* Run any generator sitting on the line */
1378 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1379 /* Mask generator data temporarily and apply. If there is a timing function, it
1380 will be calling the generator instead */
1383 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1384 if (chan->timingfunc) {
1385 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1386 ast_settimeout(chan, 0, NULL, NULL);
1388 tmp = chan->generatordata;
1389 chan->generatordata = NULL;
1390 generate = chan->generator->generate;
1391 res = generate(chan, tmp, f->datalen, f->samples);
1392 chan->generatordata = tmp;
1394 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1395 ast_deactivate_generator(chan);
1397 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1398 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1399 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1400 ast_settimeout(chan, 160, generator_force, chan);
1403 if (chan->fin & 0x80000000)
1404 ast_frame_dump(chan->name, f, "<<");
1405 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1406 chan->fin &= 0x80000000;
1409 ast_mutex_unlock(&chan->lock);
1413 int ast_indicate(struct ast_channel *chan, int condition)
1416 /* Stop if we're a zombie or need a soft hangup */
1417 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1419 ast_mutex_lock(&chan->lock);
1420 if (chan->pvt->indicate)
1421 res = chan->pvt->indicate(chan, condition);
1422 ast_mutex_unlock(&chan->lock);
1423 if (!chan->pvt->indicate || res) {
1425 * Device does not support (that) indication, lets fake
1426 * it by doing our own tone generation. (PM2002)
1428 if (condition >= 0) {
1429 const struct tone_zone_sound *ts = NULL;
1430 switch (condition) {
1431 case AST_CONTROL_RINGING:
1432 ts = ast_get_indication_tone(chan->zone, "ring");
1434 case AST_CONTROL_BUSY:
1435 ts = ast_get_indication_tone(chan->zone, "busy");
1437 case AST_CONTROL_CONGESTION:
1438 ts = ast_get_indication_tone(chan->zone, "congestion");
1441 if (ts && ts->data[0]) {
1442 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1443 ast_playtones_start(chan,0,ts->data, 1);
1445 } else if (condition == AST_CONTROL_PROGRESS) {
1446 /* ast_playtones_stop(chan); */
1447 } else if (condition == AST_CONTROL_PROCEEDING) {
1448 /* Do nothing, really */
1451 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1455 else ast_playtones_stop(chan);
1460 int ast_recvchar(struct ast_channel *chan, int timeout)
1463 struct ast_frame *f;
1468 if (ast_check_hangup(chan)) return -1;
1469 res = ast_waitfor(chan,ourto);
1470 if (res <= 0) /* if timeout */
1476 if (f == NULL) return -1; /* if hangup */
1477 if ((f->frametype == AST_FRAME_CONTROL) &&
1478 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1479 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1481 c = *((char *)f->data); /* get the data */
1489 int ast_sendtext(struct ast_channel *chan, char *text)
1492 /* Stop if we're a zombie or need a soft hangup */
1493 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1495 CHECK_BLOCKING(chan);
1496 if (chan->pvt->send_text)
1497 res = chan->pvt->send_text(chan, text);
1498 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1502 static int do_senddigit(struct ast_channel *chan, char digit)
1506 if (chan->pvt->send_digit)
1507 res = chan->pvt->send_digit(chan, digit);
1508 if (!chan->pvt->send_digit || res) {
1510 * Device does not support DTMF tones, lets fake
1511 * it by doing our own generation. (PM2002)
1513 static const char* dtmf_tones[] = {
1514 "!941+1336/100,!0/100", /* 0 */
1515 "!697+1209/100,!0/100", /* 1 */
1516 "!697+1336/100,!0/100", /* 2 */
1517 "!697+1477/100,!0/100", /* 3 */
1518 "!770+1209/100,!0/100", /* 4 */
1519 "!770+1336/100,!0/100", /* 5 */
1520 "!770+1477/100,!0/100", /* 6 */
1521 "!852+1209/100,!0/100", /* 7 */
1522 "!852+1336/100,!0/100", /* 8 */
1523 "!852+1477/100,!0/100", /* 9 */
1524 "!697+1633/100,!0/100", /* A */
1525 "!770+1633/100,!0/100", /* B */
1526 "!852+1633/100,!0/100", /* C */
1527 "!941+1633/100,!0/100", /* D */
1528 "!941+1209/100,!0/100", /* * */
1529 "!941+1477/100,!0/100" }; /* # */
1530 if (digit >= '0' && digit <='9')
1531 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1532 else if (digit >= 'A' && digit <= 'D')
1533 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1534 else if (digit == '*')
1535 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1536 else if (digit == '#')
1537 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1540 ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1546 int ast_senddigit(struct ast_channel *chan, char digit)
1548 return do_senddigit(chan, digit);
1551 int ast_prod(struct ast_channel *chan)
1553 struct ast_frame a = { AST_FRAME_VOICE };
1555 /* Send an empty audio frame to get things moving */
1556 if (chan->_state != AST_STATE_UP) {
1557 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1558 a.subclass = chan->pvt->rawwriteformat;
1559 a.data = nothing + AST_FRIENDLY_OFFSET;
1561 if (ast_write(chan, &a))
1562 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1567 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1570 if (!chan->pvt->write_video)
1572 res = ast_write(chan, fr);
1578 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1581 struct ast_frame *f = NULL;
1582 /* Stop if we're a zombie or need a soft hangup */
1583 ast_mutex_lock(&chan->lock);
1584 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1585 ast_mutex_unlock(&chan->lock);
1588 /* Handle any pending masquerades */
1590 if (ast_do_masquerade(chan)) {
1591 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1592 ast_mutex_unlock(&chan->lock);
1597 ast_mutex_unlock(&chan->lock);
1600 if (chan->generatordata) {
1601 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1602 ast_deactivate_generator(chan);
1604 ast_mutex_unlock(&chan->lock);
1608 if (chan->fout & 0x80000000)
1609 ast_frame_dump(chan->name, fr, ">>");
1610 CHECK_BLOCKING(chan);
1611 switch(fr->frametype) {
1612 case AST_FRAME_CONTROL:
1613 /* XXX Interpret control frames XXX */
1614 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1616 case AST_FRAME_DTMF:
1617 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1618 ast_mutex_unlock(&chan->lock);
1619 res = do_senddigit(chan,fr->subclass);
1620 ast_mutex_lock(&chan->lock);
1621 CHECK_BLOCKING(chan);
1623 case AST_FRAME_TEXT:
1624 if (chan->pvt->send_text)
1625 res = chan->pvt->send_text(chan, (char *) fr->data);
1627 case AST_FRAME_VIDEO:
1628 /* XXX Handle translation of video codecs one day XXX */
1629 if (chan->pvt->write_video)
1630 res = chan->pvt->write_video(chan, fr);
1635 if (chan->pvt->write) {
1636 if (chan->pvt->writetrans) {
1637 f = ast_translate(chan->pvt->writetrans, fr, 0);
1641 res = chan->pvt->write(chan, f);
1642 if( chan->monitor &&
1643 chan->monitor->write_stream &&
1644 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1645 #ifndef MONITOR_CONSTANT_DELAY
1646 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1648 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1649 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1650 chan->outsmpl += jump + 2 * f->samples;
1652 chan->outsmpl += f->samples;
1654 int jump = chan->insmpl - chan->outsmpl;
1655 if (jump - MONITOR_DELAY >= 0) {
1656 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1657 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1658 chan->outsmpl += jump;
1660 chan->outsmpl += f->samples;
1662 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1663 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1671 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1672 /* Consider a write failure to force a soft hangup */
1674 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1676 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1677 chan->fout &= 0x80000000;
1682 ast_mutex_unlock(&chan->lock);
1686 int ast_set_write_format(struct ast_channel *chan, int fmts)
1692 ast_mutex_lock(&chan->lock);
1693 native = chan->nativeformats;
1696 res = ast_translator_best_choice(&native, &fmt);
1698 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1699 ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1700 ast_mutex_unlock(&chan->lock);
1704 /* Now we have a good choice for both. We'll write using our native format. */
1705 chan->pvt->rawwriteformat = native;
1706 /* User perspective is fmt */
1707 chan->writeformat = fmt;
1708 /* Free any write translation we have right now */
1709 if (chan->pvt->writetrans)
1710 ast_translator_free_path(chan->pvt->writetrans);
1711 /* Build a translation path from the user write format to the raw writing format */
1712 chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1714 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1715 ast_mutex_unlock(&chan->lock);
1719 int ast_set_read_format(struct ast_channel *chan, int fmts)
1725 ast_mutex_lock(&chan->lock);
1726 native = chan->nativeformats;
1728 /* Find a translation path from the native read format to one of the user's read formats */
1729 res = ast_translator_best_choice(&fmt, &native);
1731 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1732 ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1733 ast_mutex_unlock(&chan->lock);
1737 /* Now we have a good choice for both. We'll write using our native format. */
1738 chan->pvt->rawreadformat = native;
1739 /* User perspective is fmt */
1740 chan->readformat = fmt;
1741 /* Free any read translation we have right now */
1742 if (chan->pvt->readtrans)
1743 ast_translator_free_path(chan->pvt->readtrans);
1744 /* Build a translation path from the raw read format to the user reading format */
1745 chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1747 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n",
1748 chan->name, ast_getformatname(chan->readformat));
1749 ast_mutex_unlock(&chan->lock);
1753 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)
1757 struct ast_channel *chan;
1758 struct ast_frame *f;
1761 chan = ast_request(type, format, data, &cause);
1767 variable = ast_strdupa(oh->variable);
1771 /* FIXME replace this call with strsep NOT*/
1772 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1773 pbx_builtin_setvar( chan, var );
1775 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1776 if (oh->account && *oh->account)
1777 ast_cdr_setaccount(chan, oh->account);
1779 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1781 if (!ast_call(chan, data, 0)) {
1782 while(timeout && (chan->_state != AST_STATE_UP)) {
1783 res = ast_waitfor(chan, timeout);
1785 /* Something not cool, or timed out */
1788 /* If done, break out */
1795 state = AST_CONTROL_HANGUP;
1799 if (f->frametype == AST_FRAME_CONTROL) {
1800 if (f->subclass == AST_CONTROL_RINGING)
1801 state = AST_CONTROL_RINGING;
1802 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1803 state = f->subclass;
1806 } else if (f->subclass == AST_CONTROL_ANSWER) {
1807 state = f->subclass;
1810 } else if (f->subclass == AST_CONTROL_PROGRESS) {
1812 } else if (f->subclass == -1) {
1813 /* Ignore -- just stopping indications */
1815 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1821 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1823 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1825 case AST_CAUSE_BUSY:
1826 state = AST_CONTROL_BUSY;
1828 case AST_CAUSE_CONGESTION:
1829 state = AST_CONTROL_CONGESTION;
1836 if (oh->context && *oh->context)
1837 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1838 if (oh->exten && *oh->exten)
1839 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1840 chan->priority = oh->priority;
1842 if (chan->_state == AST_STATE_UP)
1843 state = AST_CONTROL_ANSWER;
1847 if (chan && res <= 0) {
1849 chan->cdr = ast_cdr_alloc();
1851 ast_cdr_init(chan->cdr, chan);
1855 snprintf(tmp, 256, "%s/%s", type, (char *)data);
1856 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1857 ast_cdr_update(chan);
1858 ast_cdr_start(chan->cdr);
1859 ast_cdr_end(chan->cdr);
1860 /* If the cause wasn't handled properly */
1861 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1862 ast_cdr_failed(chan->cdr);
1864 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1871 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1873 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1876 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1878 struct chanlist *chan;
1879 struct ast_channel *c = NULL;
1886 *cause = AST_CAUSE_NOTDEFINED;
1887 if (ast_mutex_lock(&chlock)) {
1888 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1893 if (!strcasecmp(type, chan->type)) {
1894 capabilities = chan->capabilities;
1896 res = ast_translator_best_choice(&fmt, &capabilities);
1898 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1899 ast_mutex_unlock(&chlock);
1902 ast_mutex_unlock(&chlock);
1903 if (chan->requester)
1904 c = chan->requester(type, capabilities, data, cause);
1906 if (c->_state == AST_STATE_DOWN) {
1907 manager_event(EVENT_FLAG_CALL, "Newchannel",
1911 "CallerIDName: %s\r\n"
1913 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);
1921 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1922 *cause = AST_CAUSE_NOSUCHDRIVER;
1924 ast_mutex_unlock(&chlock);
1928 int ast_parse_device_state(char *device)
1930 char name[AST_CHANNEL_NAME] = "";
1932 struct ast_channel *chan;
1934 chan = ast_channel_walk_locked(NULL);
1936 strncpy(name, chan->name, sizeof(name)-1);
1937 ast_mutex_unlock(&chan->lock);
1938 cut = strchr(name,'-');
1941 if (!strcmp(name, device))
1942 return AST_DEVICE_INUSE;
1943 chan = ast_channel_walk_locked(chan);
1945 return AST_DEVICE_UNKNOWN;
1948 int ast_device_state(char *device)
1950 char tech[AST_MAX_EXTENSION] = "";
1952 struct chanlist *chanls;
1955 strncpy(tech, device, sizeof(tech)-1);
1956 number = strchr(tech, '/');
1958 return AST_DEVICE_INVALID;
1963 if (ast_mutex_lock(&chlock)) {
1964 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1969 if (!strcasecmp(tech, chanls->type)) {
1970 ast_mutex_unlock(&chlock);
1971 if (!chanls->devicestate)
1972 return ast_parse_device_state(device);
1974 res = chanls->devicestate(number);
1975 if (res == AST_DEVICE_UNKNOWN)
1976 return ast_parse_device_state(device);
1981 chanls = chanls->next;
1983 ast_mutex_unlock(&chlock);
1984 return AST_DEVICE_INVALID;
1987 int ast_call(struct ast_channel *chan, char *addr, int timeout)
1989 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
1990 If the remote end does not answer within the timeout, then do NOT hang up, but
1993 /* Stop if we're a zombie or need a soft hangup */
1994 ast_mutex_lock(&chan->lock);
1995 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
1996 if (chan->pvt->call)
1997 res = chan->pvt->call(chan, addr, timeout);
1998 ast_mutex_unlock(&chan->lock);
2002 int ast_transfer(struct ast_channel *chan, char *dest)
2004 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2005 If the remote end does not answer within the timeout, then do NOT hang up, but
2008 /* Stop if we're a zombie or need a soft hangup */
2009 ast_mutex_lock(&chan->lock);
2010 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2011 if (chan->pvt->transfer) {
2012 res = chan->pvt->transfer(chan, dest);
2018 ast_mutex_unlock(&chan->lock);
2022 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2027 /* XXX Merge with full version? XXX */
2028 /* Stop if we're a zombie or need a soft hangup */
2029 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2035 d = ast_waitstream(c, AST_DIGIT_ANY);
2039 d = ast_waitfordigit(c, to);
2041 d = ast_waitfordigit(c, to);
2049 if (!strchr(enders, d))
2051 if (strchr(enders, d) || (pos >= len)) {
2061 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2066 /* Stop if we're a zombie or need a soft hangup */
2067 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2073 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2077 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2079 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2091 if (!strchr(enders, d))
2093 if (strchr(enders, d) || (pos >= len)) {
2103 int ast_channel_supports_html(struct ast_channel *chan)
2105 if (chan->pvt->send_html)
2110 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
2112 if (chan->pvt->send_html)
2113 return chan->pvt->send_html(chan, subclass, data, datalen);
2117 int ast_channel_sendurl(struct ast_channel *chan, char *url)
2119 if (chan->pvt->send_html)
2120 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2124 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2129 ast_mutex_lock(&peer->lock);
2130 peerf = peer->nativeformats;
2131 ast_mutex_unlock(&peer->lock);
2132 ast_mutex_lock(&chan->lock);
2133 chanf = chan->nativeformats;
2134 ast_mutex_unlock(&chan->lock);
2135 res = ast_translator_best_choice(&peerf, &chanf);
2137 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
2140 /* Set read format on channel */
2141 res = ast_set_read_format(chan, peerf);
2143 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
2146 /* Set write format on peer channel */
2147 res = ast_set_write_format(peer, peerf);
2149 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
2152 /* Now we go the other way */
2153 peerf = peer->nativeformats;
2154 chanf = chan->nativeformats;
2155 res = ast_translator_best_choice(&chanf, &peerf);
2157 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
2160 /* Set writeformat on channel */
2161 res = ast_set_write_format(chan, chanf);
2163 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
2166 /* Set read format on peer channel */
2167 res = ast_set_read_format(peer, chanf);
2169 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
2175 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2177 struct ast_frame null = { AST_FRAME_NULL, };
2179 ast_mutex_lock(&original->lock);
2180 while(ast_mutex_trylock(&clone->lock)) {
2181 ast_mutex_unlock(&original->lock);
2183 ast_mutex_lock(&original->lock);
2185 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2186 clone->name, original->name);
2187 if (original->masq) {
2188 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2189 original->masq->name, original->name);
2190 } else if (clone->masqr) {
2191 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2192 clone->name, clone->masqr->name);
2194 original->masq = clone;
2195 clone->masqr = original;
2196 ast_queue_frame(original, &null);
2197 ast_queue_frame(clone, &null);
2198 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2201 ast_mutex_unlock(&clone->lock);
2202 ast_mutex_unlock(&original->lock);
2206 void ast_change_name(struct ast_channel *chan, char *newname)
2209 strncpy(tmp, chan->name, sizeof(tmp) - 1);
2210 strncpy(chan->name, newname, sizeof(chan->name) - 1);
2211 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2214 int ast_do_masquerade(struct ast_channel *original)
2219 struct ast_var_t *varptr;
2220 struct ast_frame *cur, *prev;
2221 struct ast_channel_pvt *p;
2222 struct ast_callerid tmpcid;
2223 struct ast_channel *clone = original->masq;
2224 int rformat = original->readformat;
2225 int wformat = original->writeformat;
2232 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2233 clone->name, clone->_state, original->name, original->_state);
2235 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2236 the clone channel into the original channel. Start by killing off the original
2237 channel's backend. I'm not sure we're going to keep this function, because
2238 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2240 /* We need the clone's lock, too */
2241 ast_mutex_lock(&clone->lock);
2243 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2245 /* Having remembered the original read/write formats, we turn off any translation on either
2247 free_translation(clone);
2248 free_translation(original);
2251 /* Unlink the masquerade */
2252 original->masq = NULL;
2253 clone->masqr = NULL;
2255 /* Save the original name */
2256 strncpy(orig, original->name, sizeof(orig) - 1);
2257 /* Save the new name */
2258 strncpy(newn, clone->name, sizeof(newn) - 1);
2259 /* Create the masq name */
2260 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2262 /* Copy the name from the clone channel */
2263 strncpy(original->name, newn, sizeof(original->name)-1);
2265 /* Mangle the name of the clone channel */
2266 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2268 /* Notify any managers of the change, first the masq then the other */
2269 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2270 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2274 original->pvt = clone->pvt;
2277 /* Save any pending frames on both sides. Start by counting
2278 * how many we're going to need... */
2280 cur = clone->pvt->readq;
2287 /* If we had any, prepend them to the ones already in the queue, and
2288 * load up the alertpipe */
2290 prev->next = original->pvt->readq;
2291 original->pvt->readq = clone->pvt->readq;
2292 clone->pvt->readq = NULL;
2293 if (original->pvt->alertpipe[1] > -1) {
2295 write(original->pvt->alertpipe[1], &x, sizeof(x));
2298 clone->_softhangup = AST_SOFTHANGUP_DEV;
2301 /* And of course, so does our current state. Note we need not
2302 call ast_setstate since the event manager doesn't really consider
2303 these separate. We do this early so that the clone has the proper
2304 state of the original channel. */
2305 origstate = original->_state;
2306 original->_state = clone->_state;
2307 clone->_state = origstate;
2309 if (clone->pvt->fixup){
2310 res = clone->pvt->fixup(original, clone);
2312 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2315 /* Start by disconnecting the original's physical side */
2316 if (clone->pvt->hangup)
2317 res = clone->pvt->hangup(clone);
2319 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2320 ast_mutex_unlock(&clone->lock);
2324 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2325 /* Mangle the name of the clone channel */
2326 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2327 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2329 /* Keep the same language. */
2330 /* Update the type. */
2331 original->type = clone->type;
2333 for (x=0;x<AST_MAX_FDS;x++) {
2334 original->fds[x] = clone->fds[x];
2336 /* Append variables from clone channel into original channel */
2337 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2338 varptr = original->varshead.first;
2340 while(varptr->entries.next) {
2341 varptr = varptr->entries.next;
2343 varptr->entries.next = clone->varshead.first;
2345 original->varshead.first = clone->varshead.first;
2347 clone->varshead.first = NULL;
2348 /* Presense of ADSI capable CPE follows clone */
2349 original->adsicpe = clone->adsicpe;
2350 /* Bridge remains the same */
2351 /* CDR fields remain the same */
2352 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2353 /* Application and data remain the same */
2354 /* Clone exception becomes real one, as with fdno */
2355 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2356 original->fdno = clone->fdno;
2357 /* Schedule context remains the same */
2358 /* Stream stuff stays the same */
2359 /* Keep the original state. The fixup code will need to work with it most likely */
2361 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2363 tmpcid = original->cid;
2364 original->cid = clone->cid;
2365 clone->cid = tmpcid;
2367 /* Restore original timing file descriptor */
2368 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2370 /* Our native formats are different now */
2371 original->nativeformats = clone->nativeformats;
2373 /* Context, extension, priority, app data, jump table, remain the same */
2374 /* pvt switches. pbx stays the same, as does next */
2376 /* Set the write format */
2377 ast_set_write_format(original, wformat);
2379 /* Set the read format */
2380 ast_set_read_format(original, rformat);
2382 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2384 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2385 can fix up everything as best as possible */
2386 if (original->pvt->fixup) {
2387 res = original->pvt->fixup(clone, original);
2389 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2390 original->type, original->name);
2391 ast_mutex_unlock(&clone->lock);
2395 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2396 original->type, original->name);
2398 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2399 a zombie so nothing tries to touch it. If it's already been marked as a
2400 zombie, then free it now (since it already is considered invalid). */
2401 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2402 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2403 ast_mutex_unlock(&clone->lock);
2404 ast_channel_free(clone);
2405 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2407 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2408 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2409 ast_mutex_unlock(&clone->lock);
2412 /* Signal any blocker */
2413 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2414 pthread_kill(original->blocker, SIGURG);
2415 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2416 original->name, original->_state);
2420 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2423 if (chan->cid.cid_num)
2424 free(chan->cid.cid_num);
2425 if (ast_strlen_zero(callerid))
2426 chan->cid.cid_num = NULL;
2428 chan->cid.cid_num = strdup(callerid);
2431 if (chan->cid.cid_name)
2432 free(chan->cid.cid_name);
2433 if (ast_strlen_zero(calleridname))
2434 chan->cid.cid_name = NULL;
2436 chan->cid.cid_name = strdup(calleridname);
2439 if (chan->cid.cid_ani)
2440 free(chan->cid.cid_ani);
2441 if (ast_strlen_zero(ani))
2442 chan->cid.cid_ani = NULL;
2444 chan->cid.cid_ani = strdup(ani);
2447 ast_cdr_setcid(chan->cdr, chan);
2448 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2451 "CallerIDName: %s\r\n"
2453 chan->name, chan->cid.cid_num ?
2454 chan->cid.cid_num : "<Unknown>",
2455 chan->cid.cid_name ?
2456 chan->cid.cid_name : "<Unknown>",
2460 int ast_setstate(struct ast_channel *chan, int state)
2462 if (chan->_state != state) {
2463 int oldstate = chan->_state;
2464 chan->_state = state;
2465 if (oldstate == AST_STATE_DOWN) {
2466 ast_device_state_changed(chan->name);
2467 manager_event(EVENT_FLAG_CALL, "Newchannel",
2471 "CallerIDName: %s\r\n"
2473 chan->name, ast_state2str(chan->_state),
2474 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2475 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2478 manager_event(EVENT_FLAG_CALL, "Newstate",
2482 "CallerIDName: %s\r\n"
2484 chan->name, ast_state2str(chan->_state),
2485 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2486 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2493 static long tvdiff(struct timeval *now, struct timeval *then)
2495 return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2498 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2500 struct ast_channel *bridged;
2501 bridged = chan->_bridge;
2502 if (bridged && bridged->pvt->bridged_channel)
2503 bridged = bridged->pvt->bridged_channel(chan, bridged);
2507 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2509 int res=0, min=0, sec=0,check=0;
2511 check = ast_autoservice_start(peer);
2516 if (remain / 60 > 1) {
2524 if (!strcmp(sound,"timeleft")) {
2525 res = ast_streamfile(chan, "vm-youhave", chan->language);
2526 res = ast_waitstream(chan, "");
2528 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2529 res = ast_streamfile(chan, "queue-minutes", chan->language);
2530 res = ast_waitstream(chan, "");
2533 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2534 res = ast_streamfile(chan, "queue-seconds", chan->language);
2535 res = ast_waitstream(chan, "");
2538 res = ast_streamfile(chan, sound, chan->language);
2539 res = ast_waitstream(chan, "");
2542 check = ast_autoservice_stop(peer);
2545 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)
2547 /* Copy voice back and forth between the two channels. Give the peer
2548 the ability to transfer calls with '#<extension' syntax. */
2550 struct ast_channel *cs[3];
2552 struct ast_frame *f;
2553 struct ast_channel *who = NULL;
2557 int o0nativeformats;
2558 int o1nativeformats;
2559 struct timeval start_time,precise_now;
2560 long elapsed_ms=0, time_left_ms=0;
2561 int playit=0, playitagain=1, first_time=1;
2563 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);
2566 firstpass = config->firstpass;
2567 config->firstpass = 0;
2570 gettimeofday(&start_time,NULL);
2571 time_left_ms = config->timelimit;
2573 if (config->play_to_caller && config->start_sound && firstpass)
2574 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2575 if (config->play_to_callee && config->start_sound && firstpass)
2576 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2578 /* Stop if we're a zombie or need a soft hangup */
2579 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))
2582 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2583 c0->name, c0->_bridge->name);
2587 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2588 c1->name, c1->_bridge->name);
2592 /* Keep track of bridge */
2598 manager_event(EVENT_FLAG_CALL, "Link",
2602 "Uniqueid2: %s\r\n",
2603 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2604 o1nativeformats = c1->nativeformats;
2605 o0nativeformats = c0->nativeformats;
2606 for (/* ever */;;) {
2608 if (config->timelimit) {
2609 gettimeofday(&precise_now,NULL);
2610 elapsed_ms = tvdiff(&precise_now,&start_time);
2611 time_left_ms = config->timelimit - elapsed_ms;
2613 if (playitagain && (config->play_to_caller || config->play_to_callee) && (config->play_warning && time_left_ms <= config->play_warning)) {
2614 /* narrowing down to the end */
2615 if (config->warning_freq == 0) {
2619 } else if (first_time) {
2623 if ((time_left_ms % config->warning_freq) <= 50) {
2628 if (time_left_ms <= 0) {
2629 if (config->play_to_caller && config->end_sound)
2630 bridge_playfile(c0,c1,config->end_sound,0);
2631 if (config->play_to_callee && config->end_sound)
2632 bridge_playfile(c1,c0,config->end_sound,0);
2638 if (time_left_ms >= 5000 && playit) {
2639 if (config->play_to_caller && config->warning_sound && config->play_warning)
2640 bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
2641 if (config->play_to_callee && config->warning_sound && config->play_warning)
2642 bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
2647 /* Stop if we're a zombie or need a soft hangup */
2648 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)) {
2652 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");
2655 if (c0->pvt->bridge && config->timelimit==0 &&
2656 (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2657 /* Looks like they share a bridge code */
2658 if (option_verbose > 2)
2659 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2660 if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2663 manager_event(EVENT_FLAG_CALL, "Unlink",
2667 "Uniqueid2: %s\r\n",
2668 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2669 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2672 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
2673 my not wanting to bridge */
2674 if ((res != -2) && (res != -3))
2675 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2676 if (res != -3) nativefailed++;
2679 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
2680 !(c0->generator || c1->generator)) {
2681 if (ast_channel_make_compatible(c0, c1)) {
2682 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2683 manager_event(EVENT_FLAG_CALL, "Unlink",
2687 "Uniqueid2: %s\r\n",
2688 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2691 o0nativeformats = c0->nativeformats;
2692 o1nativeformats = c1->nativeformats;
2694 who = ast_waitfor_n(cs, 2, &to);
2696 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2704 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2708 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2712 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2715 if ((f->frametype == AST_FRAME_VOICE) ||
2716 (f->frametype == AST_FRAME_TEXT) ||
2717 (f->frametype == AST_FRAME_VIDEO) ||
2718 (f->frametype == AST_FRAME_IMAGE) ||
2719 (f->frametype == AST_FRAME_DTMF)) {
2720 if ((f->frametype == AST_FRAME_DTMF) &&
2721 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2723 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2726 /* Take out of conference mode */
2728 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2734 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2738 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2745 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2747 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2751 /* Don't copy packets if there is a generator on either one, since they're
2752 not supposed to be listening anyway */
2761 /* Swap who gets priority */
2768 manager_event(EVENT_FLAG_CALL, "Unlink",
2772 "Uniqueid2: %s\r\n",
2773 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2774 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2778 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2781 if (chan->pvt->setoption) {
2782 res = chan->pvt->setoption(chan, option, data, datalen);
2790 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2791 intermediate packets. XXX */
2792 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2798 struct tonepair_def {
2805 struct tonepair_state {
2813 unsigned char offset[AST_FRIENDLY_OFFSET];
2817 static void tonepair_release(struct ast_channel *chan, void *params)
2819 struct tonepair_state *ts = params;
2821 ast_set_write_format(chan, ts->origwfmt);
2826 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2828 struct tonepair_state *ts;
2829 struct tonepair_def *td = params;
2830 ts = malloc(sizeof(struct tonepair_state));
2833 memset(ts, 0, sizeof(struct tonepair_state));
2834 ts->origwfmt = chan->writeformat;
2835 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2836 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2837 tonepair_release(NULL, ts);
2840 ts->freq1 = td->freq1;
2841 ts->freq2 = td->freq2;
2842 ts->duration = td->duration;
2845 /* Let interrupts interrupt :) */
2846 ast_set_flag(chan, AST_FLAG_WRITE_INT);
2850 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2852 struct tonepair_state *ts = data;
2855 /* we need to prepare a frame with 16 * timelen samples as we're
2856 * generating SLIN audio
2860 if (len > sizeof(ts->data) / 2 - 1) {
2861 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2864 memset(&ts->f, 0, sizeof(ts->f));
2865 for (x=0;x<len/2;x++) {
2866 ts->data[x] = ts->vol * (
2867 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2868 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2871 ts->f.frametype = AST_FRAME_VOICE;
2872 ts->f.subclass = AST_FORMAT_SLINEAR;
2873 ts->f.datalen = len;
2874 ts->f.samples = samples;
2875 ts->f.offset = AST_FRIENDLY_OFFSET;
2876 ts->f.data = ts->data;
2877 ast_write(chan, &ts->f);
2879 if (ts->duration > 0) {
2880 if (ts->pos >= ts->duration * 8)
2886 static struct ast_generator tonepair = {
2887 alloc: tonepair_alloc,
2888 release: tonepair_release,
2889 generate: tonepair_generator,
2892 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2894 struct tonepair_def d = { 0, };
2897 d.duration = duration;
2902 if (ast_activate_generator(chan, &tonepair, &d))
2907 void ast_tonepair_stop(struct ast_channel *chan)
2909 ast_deactivate_generator(chan);
2912 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2914 struct ast_frame *f;
2916 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2919 /* Give us some wiggle room */
2920 while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2930 unsigned int ast_get_group(char *s)
2935 int start=0, finish=0,x;
2936 unsigned int group = 0;
2937 copy = ast_strdupa(s);
2939 ast_log(LOG_ERROR, "Out of memory\n");
2944 while((piece = strsep(&c, ","))) {
2945 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
2947 } else if (sscanf(piece, "%d", &start)) {
2951 ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'. Using '0'\n", s,piece);
2954 for (x=start;x<=finish;x++) {
2955 if ((x > 31) || (x < 0)) {
2956 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 31)\n", x);
2965 static int (*ast_moh_start_ptr)(struct ast_channel *, char *) = NULL;
2966 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
2969 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, char *),
2970 void (*stop_ptr)(struct ast_channel *))
2972 ast_moh_start_ptr = start_ptr;
2973 ast_moh_stop_ptr = stop_ptr;
2976 void ast_uninstall_music_functions(void)
2978 ast_moh_start_ptr = NULL;
2979 ast_moh_stop_ptr = NULL;
2982 /*! Turn on/off music on hold on a given channel */
2984 int ast_moh_start(struct ast_channel *chan, char *mclass)
2986 if(ast_moh_start_ptr)
2987 return ast_moh_start_ptr(chan, mclass);
2989 if (option_verbose > 2)
2990 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : "default");
2995 void ast_moh_stop(struct ast_channel *chan)
2997 if(ast_moh_stop_ptr)
2998 ast_moh_stop_ptr(chan);