2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Channel Management
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #include "asterisk/zapata.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/options.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/chanspy.h"
48 #include "asterisk/musiconhold.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/say.h"
51 #include "asterisk/file.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/translate.h"
54 #include "asterisk/manager.h"
55 #include "asterisk/chanvars.h"
56 #include "asterisk/linkedlists.h"
57 #include "asterisk/indications.h"
58 #include "asterisk/monitor.h"
59 #include "asterisk/causes.h"
60 #include "asterisk/callerid.h"
61 #include "asterisk/utils.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/app.h"
64 #include "asterisk/transcap.h"
65 #include "asterisk/devicestate.h"
66 #include "asterisk/sha1.h"
67 #include "asterisk/threadstorage.h"
68 #include "asterisk/slinfactory.h"
70 struct channel_spy_trans {
72 struct ast_trans_pvt *path;
75 /*! \brief List of SPY structures
77 struct ast_channel_spy_list {
78 struct channel_spy_trans read_translator;
79 struct channel_spy_trans write_translator;
80 AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
83 /*! \brief Definition of the Whisper buffer */
84 struct ast_channel_whisper_buffer {
86 struct ast_slinfactory sf;
87 unsigned int original_format;
88 struct ast_trans_pvt *path;
91 /* uncomment if you have problems with 'monitoring' synchronized files */
93 #define MONITOR_CONSTANT_DELAY
94 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
97 /*! \brief Prevent new channel allocation if shutting down. */
98 static int shutting_down;
100 static int uniqueint;
102 unsigned long global_fin, global_fout;
104 AST_THREADSTORAGE(state2str_threadbuf);
105 #define STATE2STR_BUFSIZE 32
107 /*! Default amount of time to use when emulating a digit as a begin and end
109 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
111 /*! Minimum allowed digit length - 80ms */
112 #define AST_MIN_DTMF_DURATION 80
114 /*! Minimum amount of time between the end of the last digit and the beginning
115 * of a new one - 45ms */
116 #define AST_MIN_DTMF_GAP 45
118 /*! \brief List of channel drivers */
120 const struct ast_channel_tech *tech;
121 AST_LIST_ENTRY(chanlist) list;
124 /*! \brief the list of registered channel types */
125 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
127 /*! \brief the list of channels we have. Note that the lock for this list is used for
128 both the channels list and the backends list. */
129 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
131 /*! \brief map AST_CAUSE's to readable string representations
135 const struct ast_cause {
140 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
141 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
142 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
143 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
144 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
145 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
146 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
147 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
148 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
149 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
150 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
151 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
152 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
153 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
154 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
155 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
156 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
157 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
158 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
159 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
160 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
161 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
162 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
163 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
164 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
165 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
166 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
167 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
168 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
169 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
170 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
171 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
172 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
173 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
174 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
175 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
176 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
177 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
178 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
179 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
180 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
181 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
182 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
183 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
186 struct ast_variable *ast_channeltype_list(void)
189 struct ast_variable *var=NULL, *prev = NULL;
190 AST_LIST_TRAVERSE(&backends, cl, list) {
192 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
195 var = ast_variable_new(cl->tech->type, cl->tech->description);
202 /*! \brief Show channel types - CLI command */
203 static int show_channeltypes(int fd, int argc, char *argv[])
205 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
209 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
210 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
211 if (AST_RWLIST_RDLOCK(&channels)) {
212 ast_log(LOG_WARNING, "Unable to lock channel list\n");
215 AST_LIST_TRAVERSE(&backends, cl, list) {
216 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
217 (cl->tech->devicestate) ? "yes" : "no",
218 (cl->tech->indicate) ? "yes" : "no",
219 (cl->tech->transfer) ? "yes" : "no");
222 AST_RWLIST_UNLOCK(&channels);
223 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
224 return RESULT_SUCCESS;
230 /*! \brief Show details about a channel driver - CLI command */
231 static int show_channeltype(int fd, int argc, char *argv[])
233 struct chanlist *cl = NULL;
236 return RESULT_SHOWUSAGE;
238 if (AST_RWLIST_RDLOCK(&channels)) {
239 ast_log(LOG_WARNING, "Unable to lock channel list\n");
240 return RESULT_FAILURE;
243 AST_LIST_TRAVERSE(&backends, cl, list) {
244 if (!strncasecmp(cl->tech->type, argv[3], strlen(cl->tech->type))) {
251 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[3]);
252 AST_RWLIST_UNLOCK(&channels);
253 return RESULT_FAILURE;
257 "-- Info about channel driver: %s --\n"
258 " Device State: %s\n"
261 " Capabilities: %d\n"
265 " Image Support: %s\n"
266 " Text Support: %s\n",
268 (cl->tech->devicestate) ? "yes" : "no",
269 (cl->tech->indicate) ? "yes" : "no",
270 (cl->tech->transfer) ? "yes" : "no",
271 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
272 (cl->tech->send_digit_begin) ? "yes" : "no",
273 (cl->tech->send_digit_end) ? "yes" : "no",
274 (cl->tech->send_html) ? "yes" : "no",
275 (cl->tech->send_image) ? "yes" : "no",
276 (cl->tech->send_text) ? "yes" : "no"
280 AST_RWLIST_UNLOCK(&channels);
281 return RESULT_SUCCESS;
284 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
294 wordlen = strlen(word);
296 AST_LIST_TRAVERSE(&backends, cl, list) {
297 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
298 ret = ast_strdup(cl->tech->type);
306 static const char show_channeltypes_usage[] =
307 "Usage: core show channeltypes\n"
308 " Lists available channel types registered in your Asterisk server.\n";
310 static const char show_channeltype_usage[] =
311 "Usage: core show channeltype <name>\n"
312 " Show details about the specified channel type, <name>.\n";
314 static struct ast_cli_entry cli_channel[] = {
315 { { "core", "show", "channeltypes", NULL },
316 show_channeltypes, "List available channel types",
317 show_channeltypes_usage },
319 { { "core", "show", "channeltype", NULL },
320 show_channeltype, "Give more details on that channel type",
321 show_channeltype_usage, complete_channeltypes },
324 /*! \brief Checks to see if a channel is needing hang up */
325 int ast_check_hangup(struct ast_channel *chan)
327 if (chan->_softhangup) /* yes if soft hangup flag set */
329 if (!chan->tech_pvt) /* yes if no technology private data */
331 if (!chan->whentohangup) /* no if no hangup scheduled */
333 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
335 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
339 static int ast_check_hangup_locked(struct ast_channel *chan)
342 ast_channel_lock(chan);
343 res = ast_check_hangup(chan);
344 ast_channel_unlock(chan);
348 /*! \brief Initiate system shutdown */
349 void ast_begin_shutdown(int hangup)
351 struct ast_channel *c;
354 AST_RWLIST_RDLOCK(&channels);
355 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
356 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
357 AST_RWLIST_UNLOCK(&channels);
361 /*! \brief returns number of active/allocated channels */
362 int ast_active_channels(void)
364 struct ast_channel *c;
366 AST_RWLIST_RDLOCK(&channels);
367 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
369 AST_RWLIST_UNLOCK(&channels);
373 /*! \brief Cancel a shutdown in progress */
374 void ast_cancel_shutdown(void)
379 /*! \brief Returns non-zero if Asterisk is being shut down */
380 int ast_shutting_down(void)
382 return shutting_down;
385 /*! \brief Set when to hangup channel */
386 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
388 chan->whentohangup = offset ? time(NULL) + offset : 0;
389 ast_queue_frame(chan, &ast_null_frame);
393 /*! \brief Compare a offset with when to hangup channel */
394 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
398 if (!chan->whentohangup)
399 return (offset == 0) ? 0 : -1;
401 if (!offset) /* XXX why is this special? */
404 whentohangup = offset + time(NULL);
406 if (chan->whentohangup < whentohangup)
408 else if (chan->whentohangup == whentohangup)
414 /*! \brief Register a new telephony channel in Asterisk */
415 int ast_channel_register(const struct ast_channel_tech *tech)
417 struct chanlist *chan;
419 AST_RWLIST_WRLOCK(&channels);
421 AST_LIST_TRAVERSE(&backends, chan, list) {
422 if (!strcasecmp(tech->type, chan->tech->type)) {
423 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
424 AST_RWLIST_UNLOCK(&channels);
429 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
430 AST_RWLIST_UNLOCK(&channels);
434 AST_LIST_INSERT_HEAD(&backends, chan, list);
436 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
438 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
440 AST_RWLIST_UNLOCK(&channels);
444 /*! \brief Unregister channel driver */
445 void ast_channel_unregister(const struct ast_channel_tech *tech)
447 struct chanlist *chan;
449 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
451 AST_RWLIST_WRLOCK(&channels);
453 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
454 if (chan->tech == tech) {
455 AST_LIST_REMOVE_CURRENT(&backends, list);
457 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
461 AST_LIST_TRAVERSE_SAFE_END
463 AST_RWLIST_UNLOCK(&channels);
466 /*! \brief Get handle to channel driver based on name */
467 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
469 struct chanlist *chanls;
470 const struct ast_channel_tech *ret = NULL;
472 if (AST_RWLIST_RDLOCK(&channels)) {
473 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
477 AST_LIST_TRAVERSE(&backends, chanls, list) {
478 if (!strcasecmp(name, chanls->tech->type)) {
484 AST_RWLIST_UNLOCK(&channels);
489 /*! \brief Gives the string form of a given hangup cause */
490 const char *ast_cause2str(int cause)
494 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
495 if (causes[x].cause == cause)
496 return causes[x].desc;
502 /*! \brief Convert a symbolic hangup cause to number */
503 int ast_str2cause(const char *name)
507 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
508 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
509 return causes[x].cause;
514 /*! \brief Gives the string form of a given channel state.
515 \note This function is not reentrant.
517 const char *ast_state2str(enum ast_channel_state state)
524 case AST_STATE_RESERVED:
526 case AST_STATE_OFFHOOK:
528 case AST_STATE_DIALING:
532 case AST_STATE_RINGING:
538 case AST_STATE_DIALING_OFFHOOK:
539 return "Dialing Offhook";
540 case AST_STATE_PRERING:
543 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
545 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
550 /*! \brief Gives the string form of a given transfer capability */
551 char *ast_transfercapability2str(int transfercapability)
553 switch (transfercapability) {
554 case AST_TRANS_CAP_SPEECH:
556 case AST_TRANS_CAP_DIGITAL:
558 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
559 return "RESTRICTED_DIGITAL";
560 case AST_TRANS_CAP_3_1K_AUDIO:
562 case AST_TRANS_CAP_DIGITAL_W_TONES:
563 return "DIGITAL_W_TONES";
564 case AST_TRANS_CAP_VIDEO:
571 /*! \brief Pick the best audio codec */
572 int ast_best_codec(int fmts)
574 /* This just our opinion, expressed in code. We are asked to choose
575 the best codec to use, given no information */
577 static const int prefs[] =
579 /*! Okay, ulaw is used by all telephony equipment, so start with it */
581 /*! Unless of course, you're a silly European, so then prefer ALAW */
583 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
585 /*! Okay, well, signed linear is easy to translate into other stuff */
587 /*! G.726 is standard ADPCM, in RFC3551 packing order */
589 /*! G.726 is standard ADPCM, in AAL2 packing order */
590 AST_FORMAT_G726_AAL2,
591 /*! ADPCM has great sound quality and is still pretty easy to translate */
593 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
594 translate and sounds pretty good */
596 /*! iLBC is not too bad */
598 /*! Speex is free, but computationally more expensive than GSM */
600 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
603 /*! G.729a is faster than 723 and slightly less expensive */
605 /*! Down to G.723.1 which is proprietary but at least designed for voice */
609 /* Strip out video */
610 fmts &= AST_FORMAT_AUDIO_MASK;
612 /* Find the first preferred codec in the format given */
613 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
616 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
620 static const struct ast_channel_tech null_tech = {
622 .description = "Null channel (should not see this)",
625 /*! \brief Create a new channel structure */
626 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *acctcode, const char *exten, const char *context, const int amaflag, const char *name_fmt, ...)
628 struct ast_channel *tmp;
631 struct varshead *headp;
634 /* If shutting down, don't allocate any new channels */
636 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
640 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
643 if (!(tmp->sched = sched_context_create())) {
644 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
649 if ((ast_string_field_init(tmp, 128))) {
650 sched_context_destroy(tmp->sched);
655 /* Don't bother initializing the last two FD here, because they
656 will *always* be set just a few lines down (AST_TIMING_FD,
658 for (x = 0; x < AST_MAX_FDS - 2; x++)
662 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
663 if (tmp->timingfd > -1) {
664 /* Check if timing interface supports new
667 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
675 if (pipe(tmp->alertpipe)) {
676 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
677 ast_string_field_free_pools(tmp);
681 flags = fcntl(tmp->alertpipe[0], F_GETFL);
682 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
683 flags = fcntl(tmp->alertpipe[1], F_GETFL);
684 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
686 } else /* Make sure we've got it done right if they don't */
687 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
689 /* Always watch the alertpipe */
690 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
691 /* And timing pipe */
692 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
693 ast_string_field_set(tmp, name, "**Unknown**");
700 tmp->fin = global_fin;
701 tmp->fout = global_fout;
703 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
704 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
705 ast_atomic_fetchadd_int(&uniqueint, 1));
707 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
708 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
711 tmp->cid.cid_name = ast_strdup(cid_name);
712 tmp->cid.cid_num = ast_strdup(cid_num);
714 if (!ast_strlen_zero(name_fmt)) {
715 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
716 * And they all use slightly different formats for their name string.
717 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
718 * This means, that the stringfields must have a routine that takes the va_lists directly, and
719 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
720 * This new function was written so this can be accomplished.
722 va_start(ap1, name_fmt);
723 va_start(ap2, name_fmt);
724 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
728 /* and now, since the channel structure is built, and has its name, let's call the
729 * manager event generator with this Newchannel event. This is the proper and correct
730 * place to make this call, but you sure do have to pass a lot of data into this func
733 manager_event(EVENT_FLAG_CALL, "Newchannel",
736 "CallerIDNum: %s\r\n"
737 "CallerIDName: %s\r\n"
739 tmp->name, ast_state2str(state),
740 S_OR(cid_num, "<unknown>"),
741 S_OR(cid_name, "<unknown>"),
745 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
747 /* These 4 variables need to be set up for the cdr_init() to work right */
749 tmp->amaflags = amaflag;
751 tmp->amaflags = ast_default_amaflags;
753 if (!ast_strlen_zero(acctcode))
754 ast_string_field_set(tmp, accountcode, acctcode);
756 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
758 if (!ast_strlen_zero(context))
759 ast_copy_string(tmp->context, context, sizeof(tmp->context));
761 strcpy(tmp->context, "default");
763 if (!ast_strlen_zero(exten))
764 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
766 strcpy(tmp->exten, "s");
770 tmp->cdr = ast_cdr_alloc();
771 ast_cdr_init(tmp->cdr, tmp);
772 ast_cdr_start(tmp->cdr);
774 headp = &tmp->varshead;
775 AST_LIST_HEAD_INIT_NOLOCK(headp);
777 ast_mutex_init(&tmp->lock);
779 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
781 ast_string_field_set(tmp, language, defaultlanguage);
783 tmp->tech = &null_tech;
785 AST_RWLIST_WRLOCK(&channels);
786 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
787 AST_RWLIST_UNLOCK(&channels);
792 /*! \brief Queue an outgoing media frame */
793 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
796 struct ast_frame *cur;
800 /* Build us a copy and free the original one */
801 if (!(f = ast_frdup(fin))) {
802 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
805 ast_channel_lock(chan);
807 /* See if the last frame on the queue is a hangup, if so don't queue anything */
808 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
810 ast_channel_unlock(chan);
814 /* Count how many frames exist on the queue */
815 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
819 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
820 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
821 if (fin->frametype != AST_FRAME_VOICE) {
822 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
825 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
827 ast_channel_unlock(chan);
831 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
832 if (chan->alertpipe[1] > -1) {
833 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
834 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
835 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
837 } else if (chan->timingfd > -1) {
838 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
840 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
841 pthread_kill(chan->blocker, SIGURG);
843 ast_channel_unlock(chan);
847 /*! \brief Queue a hangup frame for channel */
848 int ast_queue_hangup(struct ast_channel *chan)
850 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
851 /* Yeah, let's not change a lock-critical value without locking */
852 if (!ast_channel_trylock(chan)) {
853 chan->_softhangup |= AST_SOFTHANGUP_DEV;
854 ast_channel_unlock(chan);
856 return ast_queue_frame(chan, &f);
859 /*! \brief Queue a control frame */
860 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
862 struct ast_frame f = { AST_FRAME_CONTROL, };
864 f.subclass = control;
866 return ast_queue_frame(chan, &f);
869 /*! \brief Queue a control frame with payload */
870 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
871 const void *data, size_t datalen)
873 struct ast_frame f = { AST_FRAME_CONTROL, };
875 f.subclass = control;
876 f.data = (void *) data;
879 return ast_queue_frame(chan, &f);
882 /*! \brief Set defer DTMF flag on channel */
883 int ast_channel_defer_dtmf(struct ast_channel *chan)
888 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
889 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
894 /*! \brief Unset defer DTMF flag on channel */
895 void ast_channel_undefer_dtmf(struct ast_channel *chan)
898 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
902 * \brief Helper function to find channels.
904 * It supports these modes:
906 * prev != NULL : get channel next in list after prev
907 * name != NULL : get channel with matching name
908 * name != NULL && namelen != 0 : get channel whose name starts with prefix
909 * exten != NULL : get channel whose exten or macroexten matches
910 * context != NULL && exten != NULL : get channel whose context or macrocontext
912 * It returns with the channel's lock held. If getting the individual lock fails,
913 * unlock and retry quickly up to 10 times, then give up.
915 * \note XXX Note that this code has cost O(N) because of the need to verify
916 * that the object is still on the global list.
918 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
919 * can only be done with the lock held or someone could delete the
920 * object while we work on it. This causes some ugliness in the code.
921 * Note that removing the first ast_log() may be harmful, as it would
922 * shorten the retry period and possibly cause failures.
923 * We should definitely go for a better scheme that is deadlock-free.
925 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
926 const char *name, const int namelen,
927 const char *context, const char *exten)
929 const char *msg = prev ? "deadlock" : "initial deadlock";
931 struct ast_channel *c;
932 const struct ast_channel *_prev = prev;
934 for (retries = 0; retries < 10; retries++, prev = _prev) {
936 AST_RWLIST_RDLOCK(&channels);
937 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
939 if (prev) { /* look for next item */
940 if (c != prev) /* not this one */
942 /* found, prepare to return c->next */
943 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
944 /* If prev was the last item on the channel list, then we just
945 * want to return NULL, instead of trying to deref NULL in the
949 /* We want prev to be NULL in case we end up doing more searching through
950 * the channel list to find the channel (ie: name searching). If we didn't
951 * set this to NULL the logic would just blow up
952 * XXX Need a better explanation for this ...
955 if (name) { /* want match by name */
956 if ((!namelen && strcasecmp(c->name, name)) ||
957 (namelen && strncasecmp(c->name, name, namelen)))
958 continue; /* name match failed */
960 if (context && strcasecmp(c->context, context) &&
961 strcasecmp(c->macrocontext, context))
962 continue; /* context match failed */
963 if (strcasecmp(c->exten, exten) &&
964 strcasecmp(c->macroexten, exten))
965 continue; /* exten match failed */
967 /* if we get here, c points to the desired record */
970 /* exit if chan not found or mutex acquired successfully */
971 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
972 done = c == NULL || ast_channel_trylock(c) == 0;
974 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
976 /* We are about to fail due to a deadlock, so report this
977 * while we still have the list lock.
979 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
980 /* As we have deadlocked, we will skip this channel and
981 * see if there is another match.
982 * NOTE: No point doing this for a full-name match,
983 * as there can be no more matches.
985 if (!(name && !namelen)) {
991 AST_RWLIST_UNLOCK(&channels);
994 /* If we reach this point we basically tried to lock a channel and failed. Instead of
995 * starting from the beginning of the list we can restore our saved pointer to the previous
996 * channel and start from there.
999 usleep(1); /* give other threads a chance before retrying */
1005 /*! \brief Browse channels in use */
1006 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1008 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1011 /*! \brief Get channel by name and lock it */
1012 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1014 return channel_find_locked(NULL, name, 0, NULL, NULL);
1017 /*! \brief Get channel by name prefix and lock it */
1018 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1020 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1023 /*! \brief Get next channel by name prefix and lock it */
1024 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1027 return channel_find_locked(chan, name, namelen, NULL, NULL);
1030 /*! \brief Get channel by exten (and optionally context) and lock it */
1031 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1033 return channel_find_locked(NULL, NULL, 0, context, exten);
1036 /*! \brief Get next channel by exten (and optionally context) and lock it */
1037 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1038 const char *context)
1040 return channel_find_locked(chan, NULL, 0, context, exten);
1043 /*! \brief Wait, look for hangups and condition arg */
1044 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1046 struct ast_frame *f;
1049 if (cond && ((*cond)(data) == 0))
1051 ms = ast_waitfor(chan, ms);
1064 /*! \brief Wait, look for hangups */
1065 int ast_safe_sleep(struct ast_channel *chan, int ms)
1067 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1070 static void free_cid(struct ast_callerid *cid)
1073 ast_free(cid->cid_dnid);
1075 ast_free(cid->cid_num);
1077 ast_free(cid->cid_name);
1079 ast_free(cid->cid_ani);
1081 ast_free(cid->cid_rdnis);
1082 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1085 /*! \brief Free a channel structure */
1086 void ast_channel_free(struct ast_channel *chan)
1089 struct ast_var_t *vardata;
1090 struct ast_frame *f;
1091 struct varshead *headp;
1092 struct ast_datastore *datastore = NULL;
1093 char name[AST_CHANNEL_NAME];
1095 headp=&chan->varshead;
1097 AST_RWLIST_WRLOCK(&channels);
1098 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1099 AST_RWLIST_UNLOCK(&channels);
1100 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1102 /* Lock and unlock the channel just to be sure nobody
1103 has it locked still */
1104 ast_channel_lock(chan);
1105 ast_channel_unlock(chan);
1106 if (chan->tech_pvt) {
1107 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1108 ast_free(chan->tech_pvt);
1112 sched_context_destroy(chan->sched);
1114 ast_copy_string(name, chan->name, sizeof(name));
1116 /* Stop monitoring */
1118 chan->monitor->stop( chan, 0 );
1120 /* If there is native format music-on-hold state, free it */
1121 if (chan->music_state)
1122 ast_moh_cleanup(chan);
1124 /* if someone is whispering on the channel, stop them */
1126 ast_channel_whisper_stop(chan);
1128 /* Free translators */
1129 if (chan->readtrans)
1130 ast_translator_free_path(chan->readtrans);
1131 if (chan->writetrans)
1132 ast_translator_free_path(chan->writetrans);
1134 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1135 free_cid(&chan->cid);
1136 ast_mutex_destroy(&chan->lock);
1137 /* Close pipes if appropriate */
1138 if ((fd = chan->alertpipe[0]) > -1)
1140 if ((fd = chan->alertpipe[1]) > -1)
1142 if ((fd = chan->timingfd) > -1)
1144 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1147 /* Get rid of each of the data stores on the channel */
1148 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1149 /* Free the data store */
1150 ast_channel_datastore_free(datastore);
1151 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1153 /* loop over the variables list, freeing all data and deleting list items */
1154 /* no need to lock the list, as the channel is already locked */
1156 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1157 ast_var_delete(vardata);
1159 ast_app_group_discard(chan);
1161 /* Destroy the jitterbuffer */
1162 ast_jb_destroy(chan);
1164 ast_string_field_free_pools(chan);
1166 AST_RWLIST_UNLOCK(&channels);
1168 ast_device_state_changed_literal(name);
1171 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1173 struct ast_datastore *datastore = NULL;
1175 /* Make sure we at least have type so we can identify this */
1180 /* Allocate memory for datastore and clear it */
1181 datastore = ast_calloc(1, sizeof(*datastore));
1186 datastore->info = info;
1188 datastore->uid = ast_strdup(uid);
1193 int ast_channel_datastore_free(struct ast_datastore *datastore)
1197 /* Using the destroy function (if present) destroy the data */
1198 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1199 datastore->info->destroy(datastore->data);
1200 datastore->data = NULL;
1203 /* Free allocated UID memory */
1204 if (datastore->uid != NULL) {
1205 ast_free(datastore->uid);
1206 datastore->uid = NULL;
1209 /* Finally free memory used by ourselves */
1210 ast_free(datastore);
1215 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1217 struct ast_datastore *datastore = NULL, *datastore2;
1219 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1220 if (datastore->inheritance > 0) {
1221 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1223 datastore2->data = datastore->info->duplicate(datastore->data);
1224 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1225 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1232 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1236 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1241 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1243 struct ast_datastore *datastore2 = NULL;
1246 /* Find our position and remove ourselves */
1247 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1248 if (datastore2 == datastore) {
1249 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1254 AST_LIST_TRAVERSE_SAFE_END
1259 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1261 struct ast_datastore *datastore = NULL;
1266 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1267 if (datastore->info == info) {
1268 if (uid != NULL && datastore->uid != NULL) {
1269 if (!strcasecmp(uid, datastore->uid)) {
1270 /* Matched by type AND uid */
1274 /* Matched by type at least */
1279 AST_LIST_TRAVERSE_SAFE_END
1284 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1286 /* Link the owner channel to the spy */
1289 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1290 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1291 spy->type, chan->name);
1295 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1296 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1297 ast_getformatname(spy->read_queue.format));
1301 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1302 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1303 ast_getformatname(spy->write_queue.format));
1307 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1308 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1309 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1310 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1311 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1316 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1320 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1321 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1323 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1326 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1327 ast_cond_init(&spy->trigger, NULL);
1328 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1329 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1332 ast_debug(1, "Spy %s added to channel %s\n",
1333 spy->type, chan->name);
1338 /* Clean up a channel's spy information */
1339 static void spy_cleanup(struct ast_channel *chan)
1341 if (!AST_LIST_EMPTY(&chan->spies->list))
1343 if (chan->spies->read_translator.path)
1344 ast_translator_free_path(chan->spies->read_translator.path);
1345 if (chan->spies->write_translator.path)
1346 ast_translator_free_path(chan->spies->write_translator.path);
1347 ast_free(chan->spies);
1352 /* Detach a spy from it's channel */
1353 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1355 /* We only need to poke them if they aren't already done */
1356 if (spy->status != CHANSPY_DONE) {
1357 ast_mutex_lock(&spy->lock);
1358 /* Indicate to the spy to stop */
1359 spy->status = CHANSPY_STOP;
1361 /* Poke the spy if needed */
1362 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1363 ast_cond_signal(&spy->trigger);
1364 ast_mutex_unlock(&spy->lock);
1367 /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1368 ast_debug(1, "Spy %s removed from channel %s\n", spy->type, chan->name);
1373 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1375 struct ast_channel_spy *spy = NULL;
1380 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1381 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1382 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1383 spy_detach(spy, chan);
1386 AST_LIST_TRAVERSE_SAFE_END
1390 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1395 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1396 ts.tv_sec = tv.tv_sec;
1397 ts.tv_nsec = tv.tv_usec * 1000;
1399 ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1402 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1407 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1408 spy_detach(spy, chan);
1412 void ast_channel_spy_free(struct ast_channel_spy *spy)
1414 struct ast_frame *f = NULL;
1416 if (spy->status == CHANSPY_DONE)
1419 /* Switch status to done in case we get called twice */
1420 spy->status = CHANSPY_DONE;
1422 /* Drop any frames in the queue */
1423 while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1425 while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1428 /* Destroy the condition if in use */
1429 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1430 ast_cond_destroy(&spy->trigger);
1432 /* Destroy our mutex since it is no longer in use */
1433 ast_mutex_destroy(&spy->lock);
1438 static void detach_spies(struct ast_channel *chan)
1440 struct ast_channel_spy *spy = NULL;
1445 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1446 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1447 spy_detach(spy, chan);
1449 AST_LIST_TRAVERSE_SAFE_END
1454 /*! \brief Softly hangup a channel, don't lock */
1455 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1457 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1458 /* Inform channel driver that we need to be hung up, if it cares */
1459 chan->_softhangup |= cause;
1460 ast_queue_frame(chan, &ast_null_frame);
1461 /* Interrupt any poll call or such */
1462 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1463 pthread_kill(chan->blocker, SIGURG);
1467 /*! \brief Softly hangup a channel, lock */
1468 int ast_softhangup(struct ast_channel *chan, int cause)
1471 ast_channel_lock(chan);
1472 res = ast_softhangup_nolock(chan, cause);
1473 ast_channel_unlock(chan);
1477 enum spy_direction {
1482 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1484 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1486 struct ast_frame *translated_frame = NULL;
1487 struct ast_channel_spy *spy;
1488 struct channel_spy_trans *trans;
1490 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1492 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1493 struct ast_channel_spy_queue *queue;
1494 struct ast_frame *duped_fr;
1496 if (spy->status != CHANSPY_RUNNING)
1499 ast_mutex_lock(&spy->lock);
1501 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1503 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1504 if (!translated_frame) {
1505 if (trans->path && (trans->last_format != f->subclass)) {
1506 ast_translator_free_path(trans->path);
1510 ast_debug(1, "Building translator from %s to SLINEAR for spies on channel %s\n",
1511 ast_getformatname(f->subclass), chan->name);
1512 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1513 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1514 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1515 ast_mutex_unlock(&spy->lock);
1518 trans->last_format = f->subclass;
1521 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1522 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1523 ast_getformatname(AST_FORMAT_SLINEAR));
1524 ast_mutex_unlock(&spy->lock);
1528 duped_fr = ast_frdup(translated_frame);
1529 } else if (f->subclass != queue->format) {
1530 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1531 spy->type, chan->name,
1532 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1533 ast_mutex_unlock(&spy->lock);
1536 duped_fr = ast_frdup(f);
1538 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1540 queue->samples += f->samples;
1542 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1543 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1544 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1545 case CHANSPY_TRIGGER_READ:
1546 if (dir == SPY_WRITE) {
1547 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1548 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1549 ast_debug(1, "Switching spy '%s' on '%s' to write-trigger mode\n",
1550 spy->type, chan->name);
1553 case CHANSPY_TRIGGER_WRITE:
1554 if (dir == SPY_READ) {
1555 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1556 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1557 ast_debug(1, "Switching spy '%s' on '%s' to read-trigger mode\n",
1558 spy->type, chan->name);
1562 ast_debug(1, "Triggering queue flush for spy '%s' on '%s'\n",
1563 spy->type, chan->name);
1564 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1565 ast_cond_signal(&spy->trigger);
1567 ast_debug(1, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1568 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1569 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1570 struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1571 queue->samples -= drop->samples;
1576 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1577 case CHANSPY_TRIGGER_READ:
1578 if (dir == SPY_READ)
1579 ast_cond_signal(&spy->trigger);
1581 case CHANSPY_TRIGGER_WRITE:
1582 if (dir == SPY_WRITE)
1583 ast_cond_signal(&spy->trigger);
1588 ast_mutex_unlock(&spy->lock);
1591 if (translated_frame)
1592 ast_frfree(translated_frame);
1595 static void free_translation(struct ast_channel *clone)
1597 if (clone->writetrans)
1598 ast_translator_free_path(clone->writetrans);
1599 if (clone->readtrans)
1600 ast_translator_free_path(clone->readtrans);
1601 clone->writetrans = NULL;
1602 clone->readtrans = NULL;
1603 clone->rawwriteformat = clone->nativeformats;
1604 clone->rawreadformat = clone->nativeformats;
1607 /*! \brief Hangup a channel */
1608 int ast_hangup(struct ast_channel *chan)
1611 struct ast_cdr *cdr = NULL;
1613 /* Don't actually hang up a channel that will masquerade as someone else, or
1614 if someone is going to masquerade as us */
1615 ast_channel_lock(chan);
1617 detach_spies(chan); /* get rid of spies */
1620 if (ast_do_masquerade(chan))
1621 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1625 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1626 ast_channel_unlock(chan);
1629 /* If this channel is one which will be masqueraded into something,
1630 mark it as a zombie already, so we know to free it later */
1632 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1633 ast_channel_unlock(chan);
1636 free_translation(chan);
1637 /* Close audio stream */
1639 ast_closestream(chan->stream);
1640 chan->stream = NULL;
1642 /* Close video stream */
1643 if (chan->vstream) {
1644 ast_closestream(chan->vstream);
1645 chan->vstream = NULL;
1648 sched_context_destroy(chan->sched);
1652 if (chan->generatordata) /* Clear any tone stuff remaining */
1653 if (chan->generator && chan->generator->release)
1654 chan->generator->release(chan, chan->generatordata);
1655 chan->generatordata = NULL;
1656 chan->generator = NULL;
1657 if (chan->cdr) { /* End the CDR if it hasn't already */
1658 ast_cdr_end(chan->cdr);
1662 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1663 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1664 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1665 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1668 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1669 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1670 if (chan->tech->hangup)
1671 res = chan->tech->hangup(chan);
1673 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1676 ast_channel_unlock(chan);
1677 manager_event(EVENT_FLAG_CALL, "Hangup",
1681 "Cause-txt: %s\r\n",
1685 ast_cause2str(chan->hangupcause)
1687 ast_channel_free(chan);
1690 ast_cdr_detach(cdr);
1695 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1699 ast_channel_lock(chan);
1701 /* You can't answer an outbound call */
1702 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1703 ast_channel_unlock(chan);
1707 /* Stop if we're a zombie or need a soft hangup */
1708 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1709 ast_channel_unlock(chan);
1713 switch (chan->_state) {
1714 case AST_STATE_RINGING:
1715 case AST_STATE_RING:
1716 if (chan->tech->answer)
1717 res = chan->tech->answer(chan);
1718 ast_setstate(chan, AST_STATE_UP);
1719 ast_cdr_answer(chan->cdr);
1720 ast_channel_unlock(chan);
1722 ast_safe_sleep(chan, delay);
1726 ast_cdr_answer(chan->cdr);
1732 ast_channel_unlock(chan);
1737 int ast_answer(struct ast_channel *chan)
1739 return __ast_answer(chan, 500);
1742 void ast_deactivate_generator(struct ast_channel *chan)
1744 ast_channel_lock(chan);
1745 if (chan->generatordata) {
1746 if (chan->generator && chan->generator->release)
1747 chan->generator->release(chan, chan->generatordata);
1748 chan->generatordata = NULL;
1749 chan->generator = NULL;
1750 chan->fds[AST_GENERATOR_FD] = -1;
1751 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1752 ast_settimeout(chan, 0, NULL, NULL);
1754 ast_channel_unlock(chan);
1757 static int generator_force(void *data)
1759 /* Called if generator doesn't have data */
1762 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1763 struct ast_channel *chan = data;
1764 tmp = chan->generatordata;
1765 chan->generatordata = NULL;
1766 generate = chan->generator->generate;
1767 res = generate(chan, tmp, 0, 160);
1768 chan->generatordata = tmp;
1770 ast_debug(1, "Auto-deactivating generator\n");
1771 ast_deactivate_generator(chan);
1776 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1780 ast_channel_lock(chan);
1782 if (chan->generatordata) {
1783 if (chan->generator && chan->generator->release)
1784 chan->generator->release(chan, chan->generatordata);
1785 chan->generatordata = NULL;
1789 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1794 ast_settimeout(chan, 160, generator_force, chan);
1795 chan->generator = gen;
1798 ast_channel_unlock(chan);
1803 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1804 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1807 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1811 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1812 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1813 int *exception, int *outfd, int *ms)
1815 struct timeval start = { 0 , 0 };
1816 struct pollfd *pfds;
1822 long whentohangup = 0, diff;
1823 struct ast_channel *winner = NULL;
1829 sz = n * AST_MAX_FDS + nfds;
1830 pfds = alloca(sizeof(*pfds) * sz);
1831 fdmap = alloca(sizeof(*fdmap) * sz);
1838 /* Perform any pending masquerades */
1839 for (x=0; x < n; x++) {
1840 ast_channel_lock(c[x]);
1842 if (ast_do_masquerade(c[x])) {
1843 ast_log(LOG_WARNING, "Masquerade failed\n");
1845 ast_channel_unlock(c[x]);
1849 if (c[x]->whentohangup) {
1852 diff = c[x]->whentohangup - now;
1854 /* Should already be hungup */
1855 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1856 ast_channel_unlock(c[x]);
1859 if (!whentohangup || (diff < whentohangup))
1860 whentohangup = diff;
1862 ast_channel_unlock(c[x]);
1864 /* Wait full interval */
1867 rms = whentohangup * 1000; /* timeout in milliseconds */
1868 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1872 * Build the pollfd array, putting the channels' fds first,
1873 * followed by individual fds. Order is important because
1874 * individual fd's must have priority over channel fds.
1877 for (x=0; x<n; x++) {
1878 for (y=0; y<AST_MAX_FDS; y++) {
1879 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1880 fdmap[max].chan = x; /* channel x is linked to this pfds */
1881 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1883 CHECK_BLOCKING(c[x]);
1885 /* Add the individual fds */
1886 for (x=0; x<nfds; x++) {
1887 fdmap[max].chan = -1;
1888 max += ast_add_fd(&pfds[max], fds[x]);
1892 start = ast_tvnow();
1894 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1899 res = poll(pfds, max, kbrms);
1902 } while (!res && (rms > 0));
1904 res = poll(pfds, max, rms);
1907 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1908 if (res < 0) { /* Simulate a timeout if we were interrupted */
1913 if (whentohangup) { /* if we have a timeout, check who expired */
1915 for (x=0; x<n; x++) {
1916 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1917 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1923 if (res == 0) { /* no fd ready, reset timeout and done */
1924 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1928 * Then check if any channel or fd has a pending event.
1929 * Remember to check channels first and fds last, as they
1930 * must have priority on setting 'winner'
1932 for (x = 0; x < max; x++) {
1933 res = pfds[x].revents;
1936 if (fdmap[x].chan >= 0) { /* this is a channel */
1937 winner = c[fdmap[x].chan]; /* override previous winners */
1939 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1941 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1942 winner->fdno = fdmap[x].fdno;
1943 } else { /* this is an fd */
1945 *outfd = pfds[x].fd;
1947 *exception = (res & POLLPRI) ? -1 : 0;
1952 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1959 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1961 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1964 int ast_waitfor(struct ast_channel *c, int ms)
1966 int oldms = ms; /* -1 if no timeout */
1968 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1969 if ((ms < 0) && (oldms < 0))
1974 /* XXX never to be called with ms = -1 */
1975 int ast_waitfordigit(struct ast_channel *c, int ms)
1977 return ast_waitfordigit_full(c, ms, -1, -1);
1980 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1984 if (c->timingfd > -1) {
1989 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
1990 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1991 c->timingfunc = func;
1992 c->timingdata = data;
1998 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2000 int begin_digit = 0;
2002 /* Stop if we're a zombie or need a soft hangup */
2003 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2005 /* Wait for a digit, no more than ms milliseconds total. */
2007 struct ast_channel *rchan;
2011 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2012 if (!rchan && outfd < 0 && ms) {
2013 if (errno == 0 || errno == EINTR)
2015 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2017 } else if (outfd > -1) {
2018 /* The FD we were watching has something waiting */
2022 struct ast_frame *f = ast_read(c);
2026 switch (f->frametype) {
2027 case AST_FRAME_DTMF_BEGIN:
2028 begin_digit = f->subclass;
2030 case AST_FRAME_DTMF_END:
2031 if (begin_digit != f->subclass)
2036 case AST_FRAME_CONTROL:
2037 switch (f->subclass) {
2038 case AST_CONTROL_HANGUP:
2041 case AST_CONTROL_RINGING:
2042 case AST_CONTROL_ANSWER:
2046 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2050 case AST_FRAME_VOICE:
2051 /* Write audio if appropriate */
2053 write(audiofd, f->data, f->datalen);
2061 return 0; /* Time is up */
2064 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2066 manager_event(EVENT_FLAG_DTMF,
2074 chan->name, chan->uniqueid, digit, direction, begin, end);
2077 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2079 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2080 void *tmp = chan->generatordata;
2083 if (chan->timingfunc) {
2084 if (option_debug > 1)
2085 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2086 ast_settimeout(chan, 0, NULL, NULL);
2089 chan->generatordata = NULL; /* reset, to let writes go through */
2090 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2091 chan->generatordata = tmp;
2093 if (option_debug > 1)
2094 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2095 ast_deactivate_generator(chan);
2098 } else if (f->frametype == AST_FRAME_CNG) {
2099 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2100 if (option_debug > 1)
2101 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2102 ast_settimeout(chan, 160, generator_force, chan);
2107 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2109 struct ast_frame *f = NULL; /* the return value */
2113 /* this function is very long so make sure there is only one return
2114 * point at the end (there is only one exception to this).
2116 ast_channel_lock(chan);
2118 if (ast_do_masquerade(chan))
2119 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2121 f = &ast_null_frame;
2125 /* Stop if we're a zombie or need a soft hangup */
2126 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2127 if (chan->generator)
2128 ast_deactivate_generator(chan);
2131 prestate = chan->_state;
2133 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2134 !ast_strlen_zero(chan->dtmfq) &&
2135 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2136 /* We have DTMF that has been deferred. Return it now */
2137 chan->dtmff.subclass = chan->dtmfq[0];
2138 /* Drop first digit from the buffer */
2139 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2141 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2142 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2143 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2145 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
2146 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2147 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2148 chan->emulate_dtmf_digit = f->subclass;
2149 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2151 chan->dtmf_tv = ast_tvnow();
2155 /* Read and ignore anything on the alertpipe, but read only
2156 one sizeof(blah) per frame that we send from it */
2157 if (chan->alertpipe[0] > -1)
2158 read(chan->alertpipe[0], &blah, sizeof(blah));
2161 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2164 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2166 /* IF we can't get event, assume it's an expired as-per the old interface */
2167 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2169 blah = ZT_EVENT_TIMER_EXPIRED;
2171 if (blah == ZT_EVENT_TIMER_PING) {
2172 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2173 /* Acknowledge PONG unless we need it again */
2174 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2175 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2178 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2179 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2180 if (chan->timingfunc) {
2181 /* save a copy of func/data before unlocking the channel */
2182 int (*func)(void *) = chan->timingfunc;
2183 void *data = chan->timingdata;
2184 ast_channel_unlock(chan);
2188 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2189 chan->timingdata = NULL;
2190 ast_channel_unlock(chan);
2192 /* cannot 'goto done' because the channel is already unlocked */
2193 return &ast_null_frame;
2195 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2198 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2199 /* if the AST_GENERATOR_FD is set, call the generator with args
2200 * set to -1 so it can do whatever it needs to.
2202 void *tmp = chan->generatordata;
2203 chan->generatordata = NULL; /* reset to let ast_write get through */
2204 chan->generator->generate(chan, tmp, -1, -1);
2205 chan->generatordata = tmp;
2206 f = &ast_null_frame;
2210 /* Check for pending read queue */
2211 if (!AST_LIST_EMPTY(&chan->readq)) {
2212 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2213 /* Interpret hangup and return NULL */
2214 /* XXX why not the same for frames from the channel ? */
2215 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2220 chan->blocker = pthread_self();
2221 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2222 if (chan->tech->exception)
2223 f = chan->tech->exception(chan);
2225 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2226 f = &ast_null_frame;
2228 /* Clear the exception flag */
2229 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2230 } else if (chan->tech->read)
2231 f = chan->tech->read(chan);
2233 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2237 /* if the channel driver returned more than one frame, stuff the excess
2238 into the readq for the next ast_read call (note that we can safely assume
2239 that the readq is empty, because otherwise we would not have called into
2240 the channel driver and f would be only a single frame)
2242 if (AST_LIST_NEXT(f, frame_list)) {
2243 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2244 AST_LIST_NEXT(f, frame_list) = NULL;
2247 switch (f->frametype) {
2248 case AST_FRAME_CONTROL:
2249 if (f->subclass == AST_CONTROL_ANSWER) {
2250 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2251 ast_debug(1, "Ignoring answer on an inbound call!\n");
2253 f = &ast_null_frame;
2254 } else if (prestate == AST_STATE_UP) {
2255 ast_debug(1, "Dropping duplicate answer!\n");
2257 f = &ast_null_frame;
2259 /* Answer the CDR */
2260 ast_setstate(chan, AST_STATE_UP);
2261 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2262 to keep from throwing off the basic order of the universe,
2263 we will try to keep this cdr from getting posted. */
2264 chan->cdr = ast_cdr_alloc();
2265 ast_cdr_init(chan->cdr, chan);
2266 ast_cdr_start(chan->cdr);
2269 ast_cdr_answer(chan->cdr);
2273 case AST_FRAME_DTMF_END:
2274 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2275 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2276 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2277 * However, only let emulation be forced if the other end cares about BEGIN frames */
2278 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2279 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2280 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2281 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2283 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2285 f = &ast_null_frame;
2286 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2287 if (!ast_tvzero(chan->dtmf_tv) &&
2288 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2289 /* If it hasn't been long enough, defer this digit */
2290 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2291 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2293 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2295 f = &ast_null_frame;
2297 /* There was no begin, turn this into a begin and send the end later */
2298 f->frametype = AST_FRAME_DTMF_BEGIN;
2299 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2300 chan->emulate_dtmf_digit = f->subclass;
2301 chan->dtmf_tv = ast_tvnow();
2303 if (f->len > AST_MIN_DTMF_DURATION)
2304 chan->emulate_dtmf_duration = f->len;
2306 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2308 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2309 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2312 struct timeval now = ast_tvnow();
2313 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2314 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2316 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2318 f->len = AST_MIN_DTMF_DURATION;
2319 if (f->len < AST_MIN_DTMF_DURATION) {
2320 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2321 chan->emulate_dtmf_digit = f->subclass;
2322 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2323 f = &ast_null_frame;
2325 chan->dtmf_tv = now;
2328 case AST_FRAME_DTMF_BEGIN:
2329 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2330 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2331 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) ||
2332 (!ast_tvzero(chan->dtmf_tv) &&
2333 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2335 f = &ast_null_frame;
2337 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2338 chan->dtmf_tv = ast_tvnow();
2341 case AST_FRAME_NULL:
2342 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2343 struct timeval now = ast_tvnow();
2344 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2345 chan->emulate_dtmf_duration = 0;
2348 f->frametype = AST_FRAME_DTMF_END;
2349 f->subclass = chan->emulate_dtmf_digit;
2350 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2351 chan->dtmf_tv = now;
2352 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2353 chan->emulate_dtmf_digit = 0;
2354 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2358 case AST_FRAME_VOICE:
2359 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2360 * is reached , because we want to make sure we pass at least one
2361 * voice frame through before starting the next digit, to ensure a gap
2362 * between DTMF digits. */
2363 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2364 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2365 chan->emulate_dtmf_digit = 0;
2368 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2370 ast_read_generator_actions(chan, f);
2372 f = &ast_null_frame;
2375 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2376 struct timeval now = ast_tvnow();
2377 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2378 chan->emulate_dtmf_duration = 0;
2381 f->frametype = AST_FRAME_DTMF_END;
2382 f->subclass = chan->emulate_dtmf_digit;
2383 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2384 chan->dtmf_tv = now;
2385 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2387 /* Drop voice frames while we're still in the middle of the digit */
2389 f = &ast_null_frame;
2391 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2392 /* This frame can't be from the current native formats -- drop it on the
2394 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2395 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2397 f = &ast_null_frame;
2398 } else if ((f->frametype == AST_FRAME_VOICE)) {
2400 queue_frame_to_spies(chan, f, SPY_READ);
2402 if (chan->monitor && chan->monitor->read_stream ) {
2403 /* XXX what does this do ? */
2404 #ifndef MONITOR_CONSTANT_DELAY
2405 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2407 jump = chan->outsmpl - chan->insmpl;
2408 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2409 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2410 chan->insmpl += jump + f->samples;
2412 chan->insmpl+= f->samples;
2414 int jump = chan->outsmpl - chan->insmpl;
2415 if (jump - MONITOR_DELAY >= 0) {
2416 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2417 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2418 chan->insmpl += jump;
2420 chan->insmpl += f->samples;
2422 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2423 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2424 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2428 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2429 f = &ast_null_frame;
2431 /* Run generator sitting on the line if timing device not available
2432 * and synchronous generation of outgoing frames is necessary */
2433 ast_read_generator_actions(chan, f);
2436 /* Just pass it on! */
2440 /* Make sure we always return NULL in the future */
2441 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2442 if (chan->generator)
2443 ast_deactivate_generator(chan);
2444 /* End the CDR if appropriate */
2446 ast_cdr_end(chan->cdr);
2449 /* High bit prints debugging */
2450 if (chan->fin & DEBUGCHAN_FLAG)
2451 ast_frame_dump(chan->name, f, "<<");
2452 chan->fin = FRAMECOUNT_INC(chan->fin);
2455 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2456 chan->generator->digit(chan, f->subclass);
2458 ast_channel_unlock(chan);
2462 int ast_internal_timing_enabled(struct ast_channel *chan)
2464 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2465 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2469 struct ast_frame *ast_read(struct ast_channel *chan)
2471 return __ast_read(chan, 0);
2474 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2476 return __ast_read(chan, 1);
2479 int ast_indicate(struct ast_channel *chan, int condition)
2481 return ast_indicate_data(chan, condition, NULL, 0);
2484 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2488 ast_channel_lock(chan);
2489 /* Stop if we're a zombie or need a soft hangup */
2490 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2491 ast_channel_unlock(chan);
2494 if (chan->tech->indicate)
2495 res = chan->tech->indicate(chan, condition, data, datalen);
2496 ast_channel_unlock(chan);
2497 if (!chan->tech->indicate || res) {
2499 * Device does not support (that) indication, lets fake
2500 * it by doing our own tone generation. (PM2002)
2503 ast_playtones_stop(chan);
2505 const struct ind_tone_zone_sound *ts = NULL;
2506 switch (condition) {
2507 case AST_CONTROL_RINGING:
2508 ts = ast_get_indication_tone(chan->zone, "ring");
2510 case AST_CONTROL_BUSY:
2511 ts = ast_get_indication_tone(chan->zone, "busy");
2513 case AST_CONTROL_CONGESTION:
2514 ts = ast_get_indication_tone(chan->zone, "congestion");
2517 if (ts && ts->data[0]) {
2518 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2519 ast_playtones_start(chan,0,ts->data, 1);
2521 } else if (condition == AST_CONTROL_PROGRESS) {
2522 /* ast_playtones_stop(chan); */
2523 } else if (condition == AST_CONTROL_PROCEEDING) {
2524 /* Do nothing, really */
2525 } else if (condition == AST_CONTROL_HOLD) {
2526 /* Do nothing.... */
2527 } else if (condition == AST_CONTROL_UNHOLD) {
2528 /* Do nothing.... */
2529 } else if (condition == AST_CONTROL_VIDUPDATE) {
2530 /* Do nothing.... */
2533 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2541 int ast_recvchar(struct ast_channel *chan, int timeout)
2544 char *buf = ast_recvtext(chan, timeout);
2546 return -1; /* error or timeout */
2547 c = *(unsigned char *)buf;
2552 char *ast_recvtext(struct ast_channel *chan, int timeout)
2558 struct ast_frame *f;
2559 if (ast_check_hangup(chan))
2561 res = ast_waitfor(chan, timeout);
2562 if (res <= 0) /* timeout or error */
2564 timeout = res; /* update timeout */
2567 break; /* no frame */
2568 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2569 done = 1; /* force a break */
2570 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2571 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2579 int ast_sendtext(struct ast_channel *chan, const char *text)
2582 /* Stop if we're a zombie or need a soft hangup */
2583 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2585 CHECK_BLOCKING(chan);
2586 if (chan->tech->send_text)
2587 res = chan->tech->send_text(chan, text);
2588 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2592 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2594 /* Device does not support DTMF tones, lets fake
2595 * it by doing our own generation. */
2596 static const char* dtmf_tones[] = {
2615 if (!chan->tech->send_digit_begin)
2618 if (!chan->tech->send_digit_begin(chan, digit))
2621 if (digit >= '0' && digit <='9')
2622 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2623 else if (digit >= 'A' && digit <= 'D')
2624 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2625 else if (digit == '*')
2626 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2627 else if (digit == '#')
2628 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2631 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2637 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2641 if (chan->tech->send_digit_end)
2642 res = chan->tech->send_digit_end(chan, digit, duration);
2644 if (res && chan->generator)
2645 ast_playtones_stop(chan);
2650 int ast_senddigit(struct ast_channel *chan, char digit)
2652 if (chan->tech->send_digit_begin) {
2653 ast_senddigit_begin(chan, digit);
2654 ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
2657 return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
2660 int ast_prod(struct ast_channel *chan)
2662 struct ast_frame a = { AST_FRAME_VOICE };
2665 /* Send an empty audio frame to get things moving */
2666 if (chan->_state != AST_STATE_UP) {
2667 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2668 a.subclass = chan->rawwriteformat;
2669 a.data = nothing + AST_FRIENDLY_OFFSET;
2671 if (ast_write(chan, &a))
2672 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2677 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2680 if (!chan->tech->write_video)
2682 res = ast_write(chan, fr);
2688 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2691 struct ast_frame *f = NULL;
2693 /* Stop if we're a zombie or need a soft hangup */
2694 ast_channel_lock(chan);
2695 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2698 /* Handle any pending masquerades */
2699 if (chan->masq && ast_do_masquerade(chan)) {
2700 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2704 res = 0; /* XXX explain, why 0 ? */
2707 if (chan->generatordata) {
2708 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2709 ast_deactivate_generator(chan);
2711 if (fr->frametype == AST_FRAME_DTMF_END) {
2712 /* There is a generator running while we're in the middle of a digit.
2713 * It's probably inband DTMF, so go ahead and pass it so it can
2714 * stop the generator */
2715 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2716 ast_channel_unlock(chan);
2717 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2718 ast_channel_lock(chan);
2719 CHECK_BLOCKING(chan);
2720 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2721 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2722 res = (chan->tech->indicate == NULL) ? 0 :
2723 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2725 res = 0; /* XXX explain, why 0 ? */
2729 /* High bit prints debugging */
2730 if (chan->fout & DEBUGCHAN_FLAG)
2731 ast_frame_dump(chan->name, fr, ">>");
2732 CHECK_BLOCKING(chan);
2733 switch (fr->frametype) {
2734 case AST_FRAME_CONTROL:
2735 res = (chan->tech->indicate == NULL) ? 0 :
2736 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2738 case AST_FRAME_DTMF_BEGIN:
2739 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2740 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2741 ast_channel_unlock(chan);
2742 res = ast_senddigit_begin(chan, fr->subclass);
2743 ast_channel_lock(chan);
2744 CHECK_BLOCKING(chan);
2746 case AST_FRAME_DTMF_END:
2747 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2748 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2749 ast_channel_unlock(chan);
2750 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2751 ast_channel_lock(chan);
2752 CHECK_BLOCKING(chan);
2754 case AST_FRAME_TEXT:
2755 if (fr->subclass == AST_FORMAT_T140) {
2756 res = (chan->tech->write_text == NULL) ? 0 :
2757 chan->tech->write_text(chan, fr);
2759 res = (chan->tech->send_text == NULL) ? 0 :
2760 chan->tech->send_text(chan, (char *) fr->data);
2763 case AST_FRAME_HTML:
2764 res = (chan->tech->send_html == NULL) ? 0 :
2765 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2767 case AST_FRAME_VIDEO:
2768 /* XXX Handle translation of video codecs one day XXX */
2769 res = (chan->tech->write_video == NULL) ? 0 :
2770 chan->tech->write_video(chan, fr);
2772 case AST_FRAME_MODEM:
2773 res = (chan->tech->write == NULL) ? 0 :
2774 chan->tech->write(chan, fr);
2776 case AST_FRAME_VOICE:
2777 if (chan->tech->write == NULL)
2778 break; /*! \todo XXX should return 0 maybe ? */
2780 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2781 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2782 if (fr->subclass == AST_FORMAT_SLINEAR)
2785 ast_mutex_lock(&chan->whisper->lock);
2786 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2787 /* Rebuild the translation path and set our write format back to signed linear */
2788 chan->whisper->original_format = chan->writeformat;
2789 ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2790 if (chan->whisper->path)
2791 ast_translator_free_path(chan->whisper->path);
2792 chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2794 /* Translate frame using the above translation path */
2795 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2796 ast_mutex_unlock(&chan->whisper->lock);
2799 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2800 if (fr->subclass == chan->rawwriteformat)
2803 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2806 /* If we have no frame of audio, then we have to bail out */
2812 /* If spies are on the channel then queue the frame out to them */
2814 queue_frame_to_spies(chan, f, SPY_WRITE);
2816 /* If Monitor is running on this channel, then we have to write frames out there too */
2817 if (chan->monitor && chan->monitor->write_stream) {
2818 /* XXX must explain this code */
2819 #ifndef MONITOR_CONSTANT_DELAY
2820 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2822 jump = chan->insmpl - chan->outsmpl;
2823 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2824 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2825 chan->outsmpl += jump + f->samples;
2827 chan->outsmpl += f->samples;
2829 int jump = chan->insmpl - chan->outsmpl;
2830 if (jump - MONITOR_DELAY >= 0) {
2831 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2832 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2833 chan->outsmpl += jump;
2835 chan->outsmpl += f->samples;
2837 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2838 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2839 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2843 /* Finally the good part! Write this out to the channel */
2844 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2845 /* frame is assumed to be in SLINEAR, since that is
2846 required for whisper mode */
2847 ast_frame_adjust_volume(f, -2);
2848 if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2849 short buf[f->samples];
2850 struct ast_frame whisper = {
2851 .frametype = AST_FRAME_VOICE,
2852 .subclass = AST_FORMAT_SLINEAR,
2854 .datalen = sizeof(buf),
2855 .samples = f->samples,
2858 ast_mutex_lock(&chan->whisper->lock);
2859 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2860 ast_frame_slinear_sum(f, &whisper);
2861 ast_mutex_unlock(&chan->whisper->lock);
2863 /* and now put it through the regular translator */
2864 f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2866 res = f ? chan->tech->write(chan, f) : 0;
2868 case AST_FRAME_NULL:
2874 /* At this point, fr is the incoming frame and f is NULL. Channels do
2875 * not expect to get NULL as a frame pointer and will segfault. Hence,
2876 * we output the original frame passed in. */
2877 res = chan->tech->write(chan, fr);
2883 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2884 /* Consider a write failure to force a soft hangup */
2886 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2888 chan->fout = FRAMECOUNT_INC(chan->fout);
2891 ast_channel_unlock(chan);
2895 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2896 struct ast_trans_pvt **trans, const int direction)
2901 /* Make sure we only consider audio */
2902 fmt &= AST_FORMAT_AUDIO_MASK;
2904 native = chan->nativeformats;
2905 /* Find a translation path from the native format to one of the desired formats */
2908 res = ast_translator_best_choice(&fmt, &native);
2911 res = ast_translator_best_choice(&native, &fmt);
2914 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2915 ast_getformatname(native), ast_getformatname(fmt));
2919 /* Now we have a good choice for both. */
2920 ast_channel_lock(chan);
2922 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2923 /* the channel is already in these formats, so nothing to do */
2924 ast_channel_unlock(chan);
2928 *rawformat = native;
2929 /* User perspective is fmt */
2931 /* Free any read translation we have right now */
2933 ast_translator_free_path(*trans);
2934 /* Build a translation path from the raw format to the desired format */
2937 *trans = ast_translator_build_path(*format, *rawformat);
2940 *trans = ast_translator_build_path(*rawformat, *format);
2941 ast_channel_unlock(chan);
2942 ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
2943 direction ? "write" : "read", ast_getformatname(fmt));
2947 int ast_set_read_format(struct ast_channel *chan, int fmt)
2949 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2950 &chan->readtrans, 0);
2953 int ast_set_write_format(struct ast_channel *chan, int fmt)
2955 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2956 &chan->writetrans, 1);
2959 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)
2963 struct ast_channel *chan;
2969 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2971 chan = ast_request(type, format, data, &cause);
2973 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2974 /* compute error and return */
2975 if (cause == AST_CAUSE_BUSY)
2976 *outstate = AST_CONTROL_BUSY;
2977 else if (cause == AST_CAUSE_CONGESTION)
2978 *outstate = AST_CONTROL_CONGESTION;
2984 ast_set_variables(chan, oh->vars);
2985 /* XXX why is this necessary, for the parent_channel perhaps ? */
2986 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2987 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2988 if (oh->parent_channel) {
2989 ast_channel_inherit_variables(oh->parent_channel, chan);
2990 ast_channel_datastore_inherit(oh->parent_channel, chan);
2993 ast_cdr_setaccount(chan, oh->account);
2995 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2999 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
3000 to keep from throwing off the basic order of the universe,
3001 we will try to keep this cdr from getting posted. */
3002 chan->cdr = ast_cdr_alloc();
3003 ast_cdr_init(chan->cdr, chan);
3004 ast_cdr_start(chan->cdr);
3006 if (ast_call(chan, data, 0)) { /* ast_call failed... */
3007 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3009 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
3010 while (timeout && chan->_state != AST_STATE_UP) {
3011 struct ast_frame *f;
3012 res = ast_waitfor(chan, timeout);
3013 if (res <= 0) /* error, timeout, or done */
3019 *outstate = AST_CONTROL_HANGUP;
3023 if (f->frametype == AST_FRAME_CONTROL) {
3024 switch (f->subclass) {
3025 case AST_CONTROL_RINGING: /* record but keep going */
3026 *outstate = f->subclass;
3029 case AST_CONTROL_BUSY:
3030 case AST_CONTROL_CONGESTION:
3031 case AST_CONTROL_ANSWER:
3032 *outstate = f->subclass;
3033 timeout = 0; /* trick to force exit from the while() */
3037 case AST_CONTROL_PROGRESS:
3038 case AST_CONTROL_PROCEEDING:
3039 case AST_CONTROL_HOLD:
3040 case AST_CONTROL_UNHOLD:
3041 case AST_CONTROL_VIDUPDATE:
3042 case -1: /* Ignore -- just stopping indications */
3046 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3055 if (!ast_strlen_zero(oh->context))
3056 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3057 if (!ast_strlen_zero(oh->exten))
3058 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3060 chan->priority = oh->priority;
3062 if (chan->_state == AST_STATE_UP)
3063 *outstate = AST_CONTROL_ANSWER;
3066 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3067 ast_cdr_init(chan->cdr, chan);
3070 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3071 ast_cdr_setapp(chan->cdr,"Dial",tmp);
3072 ast_cdr_update(chan);
3073 ast_cdr_start(chan->cdr);
3074 ast_cdr_end(chan->cdr);
3075 /* If the cause wasn't handled properly */
3076 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3077 ast_cdr_failed(chan->cdr);
3085 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3087 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3090 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3092 struct chanlist *chan;
3093 struct ast_channel *c;
3098 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3099 int textformat = format & AST_FORMAT_TEXT_MASK;
3103 *cause = AST_CAUSE_NOTDEFINED;
3105 if (AST_RWLIST_RDLOCK(&channels)) {
3106 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3110 AST_LIST_TRAVERSE(&backends, chan, list) {
3111 if (strcasecmp(type, chan->tech->type))
3114 capabilities = chan->tech->capabilities;
3115 fmt = format & AST_FORMAT_AUDIO_MASK;
3116 res = ast_translator_best_choice(&fmt, &capabilities);
3118 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
3119 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3120 AST_RWLIST_UNLOCK(&channels);
3123 AST_RWLIST_UNLOCK(&channels);
3124 if (!chan->tech->requester)
3127 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
3130 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3134 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3135 *cause = AST_CAUSE_NOSUCHDRIVER;
3136 AST_RWLIST_UNLOCK(&channels);
3141 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3143 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3144 If the remote end does not answer within the timeout, then do NOT hang up, but
3147 /* Stop if we're a zombie or need a soft hangup */
3148 ast_channel_lock(chan);
3149 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3150 if (chan->tech->call)
3151 res = chan->tech->call(chan, addr, timeout);
3152 ast_set_flag(chan, AST_FLAG_OUTGOING);
3154 ast_channel_unlock(chan);
3159 \brief Transfer a call to dest, if the channel supports transfer
3163 \arg the manager interface
3165 int ast_transfer(struct ast_channel *chan, char *dest)
3169 /* Stop if we're a zombie or need a soft hangup */
3170 ast_channel_lock(chan);
3171 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3172 if (chan->tech->transfer) {
3173 res = chan->tech->transfer(chan, dest);
3179 ast_channel_unlock(chan);
3183 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3185 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3188 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3190 int pos = 0; /* index in the buffer where we accumulate digits */
3193 /* Stop if we're a zombie or need a soft hangup */
3194 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3201 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3205 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3207 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3219 if (!strchr(enders, d))
3221 if (strchr(enders, d) || (pos >= len)) {
3231 int ast_channel_supports_html(struct ast_channel *chan)
3233 return (chan->tech->send_html) ? 1 : 0;
3236 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3238 if (chan->tech->send_html)
3239 return chan->tech->send_html(chan, subclass, data, datalen);
3243 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3245 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3248 /*! \brief Set up translation from one channel to another */
3249 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3254 if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
3255 /* Already compatible! Moving on ... */
3259 /* Set up translation from the 'from' channel to the 'to' channel */
3260 src = from->nativeformats;
3261 dst = to->nativeformats;
3262 if (ast_translator_best_choice(&dst, &src) < 0) {
3263 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3267 /* if the best path is not 'pass through', then
3268 transcoding is needed; if desired, force transcode path
3269 to use SLINEAR between channels, but only if there is
3270 no direct conversion available */
3271 if ((src != dst) && ast_opt_transcode_via_slin &&
3272 (ast_translate_path_steps(dst, src) != 1))
3273 dst = AST_FORMAT_SLINEAR;
3274 if (ast_set_read_format(from, dst) < 0) {
3275 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3278 if (ast_set_write_format(to, dst) < 0) {
3279 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3285 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3287 /* Some callers do not check return code, and we must try to set all call legs correctly */
3290 /* Set up translation from the chan to the peer */
3291 rc = ast_channel_make_compatible_helper(chan, peer);
3296 /* Set up translation from the peer to the chan */
3297 rc = ast_channel_make_compatible_helper(peer, chan);
3302 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3305 struct ast_channel *final_orig = original, *final_clone = clone;
3307 ast_channel_lock(original);
3308 while (ast_channel_trylock(clone)) {
3309 ast_channel_unlock(original);
3311 ast_channel_lock(original);
3314 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3315 and if so, we don't really want to masquerade it, but its proxy */
3316 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3317 final_orig = original->_bridge;
3319 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3320 final_clone = clone->_bridge;
3322 if ((final_orig != original) || (final_clone != clone)) {
3323 ast_channel_lock(final_orig);
3324 while (ast_channel_trylock(final_clone)) {
3325 ast_channel_unlock(final_orig);
3327 ast_channel_lock(final_orig);
3329 ast_channel_unlock(clone);
3330 ast_channel_unlock(original);
3331 original = final_orig;
3332 clone = final_clone;
3335 if (original == clone) {
3336 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3337 ast_channel_unlock(clone);
3338 ast_channel_unlock(original);
3342 ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
3343 clone->name, original->name);
3344 if (original->masq) {
3345 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3346 original->masq->name, original->name);
3347 } else if (clone->masqr) {
3348 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3349 clone->name, clone->masqr->name);
3351 original->masq = clone;
3352 clone->masqr = original;
3353 ast_queue_frame(original, &ast_null_frame);
3354 ast_queue_frame(clone, &ast_null_frame);
3355 ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3359 ast_channel_unlock(clone);
3360 ast_channel_unlock(original);
3365 void ast_change_name(struct ast_channel *chan, char *newname)
3367 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3368 ast_string_field_set(chan, name, newname);
3371 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3373 struct ast_var_t *current, *newvar;
3374 const char *varname;
3376 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3379 varname = ast_var_full_name(current);
3383 if (varname[0] == '_') {
3385 if (varname[1] == '_')
3391 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3393 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3394 ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3398 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3400 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3401 ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3405 ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
3412 \brief Clone channel variables from 'clone' channel into 'original' channel
3414 All variables except those related to app_groupcount are cloned.
3415 Variables are actually _removed_ from 'clone' channel, presumably
3416 because it will subsequently be destroyed.
3418 \note Assumes locks will be in place on both channels when called.
3420 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3422 struct ast_var_t *current, *newvar;
3423 /* Append variables from clone channel into original channel */
3424 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3425 if (AST_LIST_FIRST(&clone->varshead))
3426 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3427 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3429 /* then, dup the varshead list into the clone */
3431 AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3432 newvar = ast_var_assign(current->name, current->value);
3434 AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
3439 \brief Masquerade a channel
3441 \note Assumes channel will be locked when called
3443 int ast_do_masquerade(struct ast_channel *original)
3448 struct ast_frame *cur;
3449 const struct ast_channel_tech *t;
3451 struct ast_callerid tmpcid;
3452 struct ast_channel *clone = original->masq;
3453 struct ast_channel_spy_list *spy_list = NULL;
3454 struct ast_channel_spy *spy = NULL;
3455 struct ast_cdr *cdr;
3456 int rformat = original->readformat;
3457 int wformat = original->writeformat;
3463 ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3464 clone->name, clone->_state, original->name, original->_state);
3466 manager_event(EVENT_FLAG_CALL, "Masquerade", "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
3467 clone->name, ast_state2str(clone->_state), original->name, ast_state2str(original->_state));
3469 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3470 the clone channel into the original channel. Start by killing off the original
3471 channel's backend. I'm not sure we're going to keep this function, because
3472 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3474 /* We need the clone's lock, too */
3475 ast_channel_lock(clone);
3477 ast_debug(2, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3479 /* Having remembered the original read/write formats, we turn off any translation on either
3481 free_translation(clone);
3482 free_translation(original);
3485 /* Unlink the masquerade */
3486 original->masq = NULL;
3487 clone->masqr = NULL;
3489 /* Save the original name */
3490 ast_copy_string(orig, original->name, sizeof(orig));
3491 /* Save the new name */
3492 ast_copy_string(newn, clone->name, sizeof(newn));
3493 /* Create the masq name */
3494 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3496 /* Copy the name from the clone channel */
3497 ast_string_field_set(original, name, newn);
3499 /* Mangle the name of the clone channel */
3500 ast_string_field_set(clone, name, masqn);
3502 /* Notify any managers of the change, first the masq then the other */
3503 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3504 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3506 /* Swap the technologies */
3508 original->tech = clone->tech;
3512 cdr = original->cdr;
3513 original->cdr = clone->cdr;
3516 t_pvt = original->tech_pvt;