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 if (option_verbose > 1)
439 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
440 chan->tech->description);
442 AST_RWLIST_UNLOCK(&channels);
446 /*! \brief Unregister channel driver */
447 void ast_channel_unregister(const struct ast_channel_tech *tech)
449 struct chanlist *chan;
451 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
453 AST_RWLIST_WRLOCK(&channels);
455 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
456 if (chan->tech == tech) {
457 AST_LIST_REMOVE_CURRENT(&backends, list);
459 if (option_verbose > 1)
460 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
464 AST_LIST_TRAVERSE_SAFE_END
466 AST_RWLIST_UNLOCK(&channels);
469 /*! \brief Get handle to channel driver based on name */
470 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
472 struct chanlist *chanls;
473 const struct ast_channel_tech *ret = NULL;
475 if (AST_RWLIST_RDLOCK(&channels)) {
476 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
480 AST_LIST_TRAVERSE(&backends, chanls, list) {
481 if (!strcasecmp(name, chanls->tech->type)) {
487 AST_RWLIST_UNLOCK(&channels);
492 /*! \brief Gives the string form of a given hangup cause */
493 const char *ast_cause2str(int cause)
497 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
498 if (causes[x].cause == cause)
499 return causes[x].desc;
505 /*! \brief Convert a symbolic hangup cause to number */
506 int ast_str2cause(const char *name)
510 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
511 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
512 return causes[x].cause;
517 /*! \brief Gives the string form of a given channel state.
518 \note This function is not reentrant.
520 const char *ast_state2str(enum ast_channel_state state)
527 case AST_STATE_RESERVED:
529 case AST_STATE_OFFHOOK:
531 case AST_STATE_DIALING:
535 case AST_STATE_RINGING:
541 case AST_STATE_DIALING_OFFHOOK:
542 return "Dialing Offhook";
543 case AST_STATE_PRERING:
546 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
548 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
553 /*! \brief Gives the string form of a given transfer capability */
554 char *ast_transfercapability2str(int transfercapability)
556 switch (transfercapability) {
557 case AST_TRANS_CAP_SPEECH:
559 case AST_TRANS_CAP_DIGITAL:
561 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
562 return "RESTRICTED_DIGITAL";
563 case AST_TRANS_CAP_3_1K_AUDIO:
565 case AST_TRANS_CAP_DIGITAL_W_TONES:
566 return "DIGITAL_W_TONES";
567 case AST_TRANS_CAP_VIDEO:
574 /*! \brief Pick the best audio codec */
575 int ast_best_codec(int fmts)
577 /* This just our opinion, expressed in code. We are asked to choose
578 the best codec to use, given no information */
580 static const int prefs[] =
582 /*! Okay, ulaw is used by all telephony equipment, so start with it */
584 /*! Unless of course, you're a silly European, so then prefer ALAW */
586 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
588 /*! Okay, well, signed linear is easy to translate into other stuff */
590 /*! G.726 is standard ADPCM, in RFC3551 packing order */
592 /*! G.726 is standard ADPCM, in AAL2 packing order */
593 AST_FORMAT_G726_AAL2,
594 /*! ADPCM has great sound quality and is still pretty easy to translate */
596 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
597 translate and sounds pretty good */
599 /*! iLBC is not too bad */
601 /*! Speex is free, but computationally more expensive than GSM */
603 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
606 /*! G.729a is faster than 723 and slightly less expensive */
608 /*! Down to G.723.1 which is proprietary but at least designed for voice */
612 /* Strip out video */
613 fmts &= AST_FORMAT_AUDIO_MASK;
615 /* Find the first preferred codec in the format given */
616 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
619 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
623 static const struct ast_channel_tech null_tech = {
625 .description = "Null channel (should not see this)",
628 /*! \brief Create a new channel structure */
629 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, ...)
631 struct ast_channel *tmp;
634 struct varshead *headp;
637 /* If shutting down, don't allocate any new channels */
639 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
643 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
646 if (!(tmp->sched = sched_context_create())) {
647 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
652 if ((ast_string_field_init(tmp, 128))) {
653 sched_context_destroy(tmp->sched);
658 /* Don't bother initializing the last two FD here, because they
659 will *always* be set just a few lines down (AST_TIMING_FD,
661 for (x = 0; x < AST_MAX_FDS - 2; x++)
665 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
666 if (tmp->timingfd > -1) {
667 /* Check if timing interface supports new
670 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
678 if (pipe(tmp->alertpipe)) {
679 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
680 ast_string_field_free_pools(tmp);
684 flags = fcntl(tmp->alertpipe[0], F_GETFL);
685 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
686 flags = fcntl(tmp->alertpipe[1], F_GETFL);
687 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
689 } else /* Make sure we've got it done right if they don't */
690 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
692 /* Always watch the alertpipe */
693 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
694 /* And timing pipe */
695 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
696 ast_string_field_set(tmp, name, "**Unknown**");
703 tmp->fin = global_fin;
704 tmp->fout = global_fout;
706 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
707 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
708 ast_atomic_fetchadd_int(&uniqueint, 1));
710 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
711 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
714 tmp->cid.cid_name = ast_strdup(cid_name);
715 tmp->cid.cid_num = ast_strdup(cid_num);
717 if (!ast_strlen_zero(name_fmt)) {
718 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
719 * And they all use slightly different formats for their name string.
720 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
721 * This means, that the stringfields must have a routine that takes the va_lists directly, and
722 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
723 * This new function was written so this can be accomplished.
725 va_start(ap1, name_fmt);
726 va_start(ap2, name_fmt);
727 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
731 /* and now, since the channel structure is built, and has its name, let's call the
732 * manager event generator with this Newchannel event. This is the proper and correct
733 * place to make this call, but you sure do have to pass a lot of data into this func
736 manager_event(EVENT_FLAG_CALL, "Newchannel",
739 "CallerIDNum: %s\r\n"
740 "CallerIDName: %s\r\n"
742 tmp->name, ast_state2str(state),
743 S_OR(cid_num, "<unknown>"),
744 S_OR(cid_name, "<unknown>"),
748 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
750 /* These 4 variables need to be set up for the cdr_init() to work right */
752 tmp->amaflags = amaflag;
754 tmp->amaflags = ast_default_amaflags;
756 if (!ast_strlen_zero(acctcode))
757 ast_string_field_set(tmp, accountcode, acctcode);
759 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
761 if (!ast_strlen_zero(context))
762 ast_copy_string(tmp->context, context, sizeof(tmp->context));
764 strcpy(tmp->context, "default");
766 if (!ast_strlen_zero(exten))
767 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
769 strcpy(tmp->exten, "s");
773 tmp->cdr = ast_cdr_alloc();
774 ast_cdr_init(tmp->cdr, tmp);
775 ast_cdr_start(tmp->cdr);
777 headp = &tmp->varshead;
778 AST_LIST_HEAD_INIT_NOLOCK(headp);
780 ast_mutex_init(&tmp->lock);
782 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
784 ast_string_field_set(tmp, language, defaultlanguage);
786 tmp->tech = &null_tech;
788 AST_RWLIST_WRLOCK(&channels);
789 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
790 AST_RWLIST_UNLOCK(&channels);
795 /*! \brief Queue an outgoing media frame */
796 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
799 struct ast_frame *cur;
803 /* Build us a copy and free the original one */
804 if (!(f = ast_frdup(fin))) {
805 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
808 ast_channel_lock(chan);
810 /* See if the last frame on the queue is a hangup, if so don't queue anything */
811 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
813 ast_channel_unlock(chan);
817 /* Count how many frames exist on the queue */
818 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
822 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
823 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
824 if (fin->frametype != AST_FRAME_VOICE) {
825 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
828 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
830 ast_channel_unlock(chan);
834 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
835 if (chan->alertpipe[1] > -1) {
836 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
837 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
838 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
840 } else if (chan->timingfd > -1) {
841 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
843 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
844 pthread_kill(chan->blocker, SIGURG);
846 ast_channel_unlock(chan);
850 /*! \brief Queue a hangup frame for channel */
851 int ast_queue_hangup(struct ast_channel *chan)
853 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
854 /* Yeah, let's not change a lock-critical value without locking */
855 if (!ast_channel_trylock(chan)) {
856 chan->_softhangup |= AST_SOFTHANGUP_DEV;
857 ast_channel_unlock(chan);
859 return ast_queue_frame(chan, &f);
862 /*! \brief Queue a control frame */
863 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
865 struct ast_frame f = { AST_FRAME_CONTROL, };
867 f.subclass = control;
869 return ast_queue_frame(chan, &f);
872 /*! \brief Queue a control frame with payload */
873 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
874 const void *data, size_t datalen)
876 struct ast_frame f = { AST_FRAME_CONTROL, };
878 f.subclass = control;
879 f.data = (void *) data;
882 return ast_queue_frame(chan, &f);
885 /*! \brief Set defer DTMF flag on channel */
886 int ast_channel_defer_dtmf(struct ast_channel *chan)
891 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
892 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
897 /*! \brief Unset defer DTMF flag on channel */
898 void ast_channel_undefer_dtmf(struct ast_channel *chan)
901 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
905 * \brief Helper function to find channels.
907 * It supports these modes:
909 * prev != NULL : get channel next in list after prev
910 * name != NULL : get channel with matching name
911 * name != NULL && namelen != 0 : get channel whose name starts with prefix
912 * exten != NULL : get channel whose exten or macroexten matches
913 * context != NULL && exten != NULL : get channel whose context or macrocontext
915 * It returns with the channel's lock held. If getting the individual lock fails,
916 * unlock and retry quickly up to 10 times, then give up.
918 * \note XXX Note that this code has cost O(N) because of the need to verify
919 * that the object is still on the global list.
921 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
922 * can only be done with the lock held or someone could delete the
923 * object while we work on it. This causes some ugliness in the code.
924 * Note that removing the first ast_log() may be harmful, as it would
925 * shorten the retry period and possibly cause failures.
926 * We should definitely go for a better scheme that is deadlock-free.
928 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
929 const char *name, const int namelen,
930 const char *context, const char *exten)
932 const char *msg = prev ? "deadlock" : "initial deadlock";
934 struct ast_channel *c;
936 for (retries = 0; retries < 10; retries++) {
938 AST_RWLIST_RDLOCK(&channels);
939 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
940 if (prev) { /* look for next item */
941 if (c != prev) /* not this one */
943 /* found, prepare to return c->next */
944 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
945 /* If prev was the last item on the channel list, then we just
946 * want to return NULL, instead of trying to deref NULL in the
950 /* We want prev to be NULL in case we end up doing more searching through
951 * the channel list to find the channel (ie: name searching). If we didn't
952 * set this to NULL the logic would just blow up
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 usleep(1); /* give other threads a chance before retrying */
1000 /*! \brief Browse channels in use */
1001 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1003 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1006 /*! \brief Get channel by name and lock it */
1007 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1009 return channel_find_locked(NULL, name, 0, NULL, NULL);
1012 /*! \brief Get channel by name prefix and lock it */
1013 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1015 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1018 /*! \brief Get next channel by name prefix and lock it */
1019 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1022 return channel_find_locked(chan, name, namelen, NULL, NULL);
1025 /*! \brief Get channel by exten (and optionally context) and lock it */
1026 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1028 return channel_find_locked(NULL, NULL, 0, context, exten);
1031 /*! \brief Get next channel by exten (and optionally context) and lock it */
1032 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1033 const char *context)
1035 return channel_find_locked(chan, NULL, 0, context, exten);
1038 /*! \brief Wait, look for hangups and condition arg */
1039 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1041 struct ast_frame *f;
1044 if (cond && ((*cond)(data) == 0))
1046 ms = ast_waitfor(chan, ms);
1059 /*! \brief Wait, look for hangups */
1060 int ast_safe_sleep(struct ast_channel *chan, int ms)
1062 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1065 static void free_cid(struct ast_callerid *cid)
1068 ast_free(cid->cid_dnid);
1070 ast_free(cid->cid_num);
1072 ast_free(cid->cid_name);
1074 ast_free(cid->cid_ani);
1076 ast_free(cid->cid_rdnis);
1077 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1080 /*! \brief Free a channel structure */
1081 void ast_channel_free(struct ast_channel *chan)
1084 struct ast_var_t *vardata;
1085 struct ast_frame *f;
1086 struct varshead *headp;
1087 struct ast_datastore *datastore = NULL;
1088 char name[AST_CHANNEL_NAME];
1090 headp=&chan->varshead;
1092 AST_RWLIST_WRLOCK(&channels);
1093 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1094 AST_RWLIST_UNLOCK(&channels);
1095 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1097 /* Lock and unlock the channel just to be sure nobody
1098 has it locked still */
1099 ast_channel_lock(chan);
1100 ast_channel_unlock(chan);
1101 if (chan->tech_pvt) {
1102 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1103 ast_free(chan->tech_pvt);
1107 sched_context_destroy(chan->sched);
1109 ast_copy_string(name, chan->name, sizeof(name));
1111 /* Stop monitoring */
1113 chan->monitor->stop( chan, 0 );
1115 /* If there is native format music-on-hold state, free it */
1116 if (chan->music_state)
1117 ast_moh_cleanup(chan);
1119 /* if someone is whispering on the channel, stop them */
1121 ast_channel_whisper_stop(chan);
1123 /* Free translators */
1124 if (chan->readtrans)
1125 ast_translator_free_path(chan->readtrans);
1126 if (chan->writetrans)
1127 ast_translator_free_path(chan->writetrans);
1129 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1130 free_cid(&chan->cid);
1131 ast_mutex_destroy(&chan->lock);
1132 /* Close pipes if appropriate */
1133 if ((fd = chan->alertpipe[0]) > -1)
1135 if ((fd = chan->alertpipe[1]) > -1)
1137 if ((fd = chan->timingfd) > -1)
1139 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1142 /* Get rid of each of the data stores on the channel */
1143 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1144 /* Free the data store */
1145 ast_channel_datastore_free(datastore);
1146 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1148 /* loop over the variables list, freeing all data and deleting list items */
1149 /* no need to lock the list, as the channel is already locked */
1151 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1152 ast_var_delete(vardata);
1154 ast_app_group_discard(chan);
1156 /* Destroy the jitterbuffer */
1157 ast_jb_destroy(chan);
1159 ast_string_field_free_pools(chan);
1161 AST_RWLIST_UNLOCK(&channels);
1163 ast_device_state_changed_literal(name);
1166 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1168 struct ast_datastore *datastore = NULL;
1170 /* Make sure we at least have type so we can identify this */
1175 /* Allocate memory for datastore and clear it */
1176 datastore = ast_calloc(1, sizeof(*datastore));
1181 datastore->info = info;
1183 datastore->uid = ast_strdup(uid);
1188 int ast_channel_datastore_free(struct ast_datastore *datastore)
1192 /* Using the destroy function (if present) destroy the data */
1193 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1194 datastore->info->destroy(datastore->data);
1195 datastore->data = NULL;
1198 /* Free allocated UID memory */
1199 if (datastore->uid != NULL) {
1200 ast_free(datastore->uid);
1201 datastore->uid = NULL;
1204 /* Finally free memory used by ourselves */
1205 ast_free(datastore);
1210 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1212 struct ast_datastore *datastore = NULL, *datastore2;
1214 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1215 if (datastore->inheritance > 0) {
1216 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1218 datastore2->data = datastore->info->duplicate(datastore->data);
1219 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1220 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1227 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1231 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1236 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1238 struct ast_datastore *datastore2 = NULL;
1241 /* Find our position and remove ourselves */
1242 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1243 if (datastore2 == datastore) {
1244 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1249 AST_LIST_TRAVERSE_SAFE_END
1254 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1256 struct ast_datastore *datastore = NULL;
1261 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1262 if (datastore->info == info) {
1263 if (uid != NULL && datastore->uid != NULL) {
1264 if (!strcasecmp(uid, datastore->uid)) {
1265 /* Matched by type AND uid */
1269 /* Matched by type at least */
1274 AST_LIST_TRAVERSE_SAFE_END
1279 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1281 /* Link the owner channel to the spy */
1284 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1285 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1286 spy->type, chan->name);
1290 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1291 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1292 ast_getformatname(spy->read_queue.format));
1296 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1297 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1298 ast_getformatname(spy->write_queue.format));
1302 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1303 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1304 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1305 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1306 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1311 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1315 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1316 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1318 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1321 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1322 ast_cond_init(&spy->trigger, NULL);
1323 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1324 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1327 ast_debug(1, "Spy %s added to channel %s\n",
1328 spy->type, chan->name);
1333 /* Clean up a channel's spy information */
1334 static void spy_cleanup(struct ast_channel *chan)
1336 if (!AST_LIST_EMPTY(&chan->spies->list))
1338 if (chan->spies->read_translator.path)
1339 ast_translator_free_path(chan->spies->read_translator.path);
1340 if (chan->spies->write_translator.path)
1341 ast_translator_free_path(chan->spies->write_translator.path);
1342 ast_free(chan->spies);
1347 /* Detach a spy from it's channel */
1348 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1350 ast_mutex_lock(&spy->lock);
1352 /* We only need to poke them if they aren't already done */
1353 if (spy->status != CHANSPY_DONE) {
1354 /* Indicate to the spy to stop */
1355 spy->status = CHANSPY_STOP;
1357 /* Poke the spy if needed */
1358 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1359 ast_cond_signal(&spy->trigger);
1362 /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1363 ast_debug(1, "Spy %s removed from channel %s\n", spy->type, chan->name);
1365 ast_mutex_unlock(&spy->lock);
1370 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1372 struct ast_channel_spy *spy = NULL;
1377 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1378 ast_mutex_lock(&spy->lock);
1379 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1380 ast_mutex_unlock(&spy->lock);
1381 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1382 spy_detach(spy, chan);
1384 ast_mutex_unlock(&spy->lock);
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 ast_mutex_lock(&spy->lock);
1498 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1500 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1501 if (!translated_frame) {
1502 if (trans->path && (trans->last_format != f->subclass)) {
1503 ast_translator_free_path(trans->path);
1507 ast_debug(1, "Building translator from %s to SLINEAR for spies on channel %s\n",
1508 ast_getformatname(f->subclass), chan->name);
1509 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1510 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1511 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1512 ast_mutex_unlock(&spy->lock);
1515 trans->last_format = f->subclass;
1518 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1519 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1520 ast_getformatname(AST_FORMAT_SLINEAR));
1521 ast_mutex_unlock(&spy->lock);
1525 duped_fr = ast_frdup(translated_frame);
1526 } else if (f->subclass != queue->format) {
1527 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1528 spy->type, chan->name,
1529 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1530 ast_mutex_unlock(&spy->lock);
1533 duped_fr = ast_frdup(f);
1535 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1537 queue->samples += f->samples;
1539 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1540 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1541 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1542 case CHANSPY_TRIGGER_READ:
1543 if (dir == SPY_WRITE) {
1544 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1545 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1546 ast_debug(1, "Switching spy '%s' on '%s' to write-trigger mode\n",
1547 spy->type, chan->name);
1550 case CHANSPY_TRIGGER_WRITE:
1551 if (dir == SPY_READ) {
1552 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1553 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1554 ast_debug(1, "Switching spy '%s' on '%s' to read-trigger mode\n",
1555 spy->type, chan->name);
1559 ast_debug(1, "Triggering queue flush for spy '%s' on '%s'\n",
1560 spy->type, chan->name);
1561 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1562 ast_cond_signal(&spy->trigger);
1564 ast_debug(1, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1565 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1566 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1567 struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1568 queue->samples -= drop->samples;
1573 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1574 case CHANSPY_TRIGGER_READ:
1575 if (dir == SPY_READ)
1576 ast_cond_signal(&spy->trigger);
1578 case CHANSPY_TRIGGER_WRITE:
1579 if (dir == SPY_WRITE)
1580 ast_cond_signal(&spy->trigger);
1585 ast_mutex_unlock(&spy->lock);
1588 if (translated_frame)
1589 ast_frfree(translated_frame);
1592 static void free_translation(struct ast_channel *clone)
1594 if (clone->writetrans)
1595 ast_translator_free_path(clone->writetrans);
1596 if (clone->readtrans)
1597 ast_translator_free_path(clone->readtrans);
1598 clone->writetrans = NULL;
1599 clone->readtrans = NULL;
1600 clone->rawwriteformat = clone->nativeformats;
1601 clone->rawreadformat = clone->nativeformats;
1604 /*! \brief Hangup a channel */
1605 int ast_hangup(struct ast_channel *chan)
1608 struct ast_cdr *cdr = NULL;
1610 /* Don't actually hang up a channel that will masquerade as someone else, or
1611 if someone is going to masquerade as us */
1612 ast_channel_lock(chan);
1614 detach_spies(chan); /* get rid of spies */
1617 if (ast_do_masquerade(chan))
1618 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1622 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1623 ast_channel_unlock(chan);
1626 /* If this channel is one which will be masqueraded into something,
1627 mark it as a zombie already, so we know to free it later */
1629 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1630 ast_channel_unlock(chan);
1633 free_translation(chan);
1634 /* Close audio stream */
1636 ast_closestream(chan->stream);
1637 chan->stream = NULL;
1639 /* Close video stream */
1640 if (chan->vstream) {
1641 ast_closestream(chan->vstream);
1642 chan->vstream = NULL;
1645 sched_context_destroy(chan->sched);
1649 if (chan->generatordata) /* Clear any tone stuff remaining */
1650 if (chan->generator && chan->generator->release)
1651 chan->generator->release(chan, chan->generatordata);
1652 chan->generatordata = NULL;
1653 chan->generator = NULL;
1654 if (chan->cdr) { /* End the CDR if it hasn't already */
1655 ast_cdr_end(chan->cdr);
1659 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1660 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1661 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1662 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1665 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1666 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1667 if (chan->tech->hangup)
1668 res = chan->tech->hangup(chan);
1670 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1673 ast_channel_unlock(chan);
1674 manager_event(EVENT_FLAG_CALL, "Hangup",
1678 "Cause-txt: %s\r\n",
1682 ast_cause2str(chan->hangupcause)
1684 ast_channel_free(chan);
1687 ast_cdr_detach(cdr);
1692 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1696 ast_channel_lock(chan);
1698 /* You can't answer an outbound call */
1699 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1700 ast_channel_unlock(chan);
1704 /* Stop if we're a zombie or need a soft hangup */
1705 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1706 ast_channel_unlock(chan);
1710 switch (chan->_state) {
1711 case AST_STATE_RINGING:
1712 case AST_STATE_RING:
1713 if (chan->tech->answer)
1714 res = chan->tech->answer(chan);
1715 ast_setstate(chan, AST_STATE_UP);
1716 ast_cdr_answer(chan->cdr);
1717 ast_channel_unlock(chan);
1719 ast_safe_sleep(chan, delay);
1723 ast_cdr_answer(chan->cdr);
1729 ast_channel_unlock(chan);
1734 int ast_answer(struct ast_channel *chan)
1736 return __ast_answer(chan, 500);
1739 void ast_deactivate_generator(struct ast_channel *chan)
1741 ast_channel_lock(chan);
1742 if (chan->generatordata) {
1743 if (chan->generator && chan->generator->release)
1744 chan->generator->release(chan, chan->generatordata);
1745 chan->generatordata = NULL;
1746 chan->generator = NULL;
1747 chan->fds[AST_GENERATOR_FD] = -1;
1748 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1749 ast_settimeout(chan, 0, NULL, NULL);
1751 ast_channel_unlock(chan);
1754 static int generator_force(void *data)
1756 /* Called if generator doesn't have data */
1759 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1760 struct ast_channel *chan = data;
1761 tmp = chan->generatordata;
1762 chan->generatordata = NULL;
1763 generate = chan->generator->generate;
1764 res = generate(chan, tmp, 0, 160);
1765 chan->generatordata = tmp;
1767 ast_debug(1, "Auto-deactivating generator\n");
1768 ast_deactivate_generator(chan);
1773 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1777 ast_channel_lock(chan);
1779 if (chan->generatordata) {
1780 if (chan->generator && chan->generator->release)
1781 chan->generator->release(chan, chan->generatordata);
1782 chan->generatordata = NULL;
1786 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1791 ast_settimeout(chan, 160, generator_force, chan);
1792 chan->generator = gen;
1795 ast_channel_unlock(chan);
1800 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1801 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1804 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1808 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1809 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1810 int *exception, int *outfd, int *ms)
1812 struct timeval start = { 0 , 0 };
1813 struct pollfd *pfds;
1819 long whentohangup = 0, diff;
1820 struct ast_channel *winner = NULL;
1826 sz = n * AST_MAX_FDS + nfds;
1827 pfds = alloca(sizeof(*pfds) * sz);
1828 fdmap = alloca(sizeof(*fdmap) * sz);
1835 /* Perform any pending masquerades */
1836 for (x=0; x < n; x++) {
1837 ast_channel_lock(c[x]);
1839 if (ast_do_masquerade(c[x])) {
1840 ast_log(LOG_WARNING, "Masquerade failed\n");
1842 ast_channel_unlock(c[x]);
1846 if (c[x]->whentohangup) {
1849 diff = c[x]->whentohangup - now;
1851 /* Should already be hungup */
1852 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1853 ast_channel_unlock(c[x]);
1856 if (!whentohangup || (diff < whentohangup))
1857 whentohangup = diff;
1859 ast_channel_unlock(c[x]);
1861 /* Wait full interval */
1864 rms = whentohangup * 1000; /* timeout in milliseconds */
1865 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1869 * Build the pollfd array, putting the channels' fds first,
1870 * followed by individual fds. Order is important because
1871 * individual fd's must have priority over channel fds.
1874 for (x=0; x<n; x++) {
1875 for (y=0; y<AST_MAX_FDS; y++) {
1876 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1877 fdmap[max].chan = x; /* channel x is linked to this pfds */
1878 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1880 CHECK_BLOCKING(c[x]);
1882 /* Add the individual fds */
1883 for (x=0; x<nfds; x++) {
1884 fdmap[max].chan = -1;
1885 max += ast_add_fd(&pfds[max], fds[x]);
1889 start = ast_tvnow();
1891 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1896 res = poll(pfds, max, kbrms);
1899 } while (!res && (rms > 0));
1901 res = poll(pfds, max, rms);
1904 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1905 if (res < 0) { /* Simulate a timeout if we were interrupted */
1910 if (whentohangup) { /* if we have a timeout, check who expired */
1912 for (x=0; x<n; x++) {
1913 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1914 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1920 if (res == 0) { /* no fd ready, reset timeout and done */
1921 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1925 * Then check if any channel or fd has a pending event.
1926 * Remember to check channels first and fds last, as they
1927 * must have priority on setting 'winner'
1929 for (x = 0; x < max; x++) {
1930 res = pfds[x].revents;
1933 if (fdmap[x].chan >= 0) { /* this is a channel */
1934 winner = c[fdmap[x].chan]; /* override previous winners */
1936 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1938 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1939 winner->fdno = fdmap[x].fdno;
1940 } else { /* this is an fd */
1942 *outfd = pfds[x].fd;
1944 *exception = (res & POLLPRI) ? -1 : 0;
1949 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1956 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1958 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1961 int ast_waitfor(struct ast_channel *c, int ms)
1963 int oldms = ms; /* -1 if no timeout */
1965 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1966 if ((ms < 0) && (oldms < 0))
1971 /* XXX never to be called with ms = -1 */
1972 int ast_waitfordigit(struct ast_channel *c, int ms)
1974 return ast_waitfordigit_full(c, ms, -1, -1);
1977 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1981 if (c->timingfd > -1) {
1986 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
1987 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1988 c->timingfunc = func;
1989 c->timingdata = data;
1995 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1998 /* Stop if we're a zombie or need a soft hangup */
1999 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2001 /* Wait for a digit, no more than ms milliseconds total. */
2003 struct ast_channel *rchan;
2007 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2008 if (!rchan && outfd < 0 && ms) {
2009 if (errno == 0 || errno == EINTR)
2011 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2013 } else if (outfd > -1) {
2014 /* The FD we were watching has something waiting */
2018 struct ast_frame *f = ast_read(c);
2022 switch (f->frametype) {
2023 case AST_FRAME_DTMF:
2027 case AST_FRAME_CONTROL:
2028 switch (f->subclass) {
2029 case AST_CONTROL_HANGUP:
2032 case AST_CONTROL_RINGING:
2033 case AST_CONTROL_ANSWER:
2037 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2041 case AST_FRAME_VOICE:
2042 /* Write audio if appropriate */
2044 write(audiofd, f->data, f->datalen);
2052 return 0; /* Time is up */
2055 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2057 manager_event(EVENT_FLAG_DTMF,
2065 chan->name, chan->uniqueid, digit, direction, begin, end);
2068 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2070 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2071 void *tmp = chan->generatordata;
2074 if (chan->timingfunc) {
2075 if (option_debug > 1)
2076 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2077 ast_settimeout(chan, 0, NULL, NULL);
2080 chan->generatordata = NULL; /* reset, to let writes go through */
2081 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2082 chan->generatordata = tmp;
2084 if (option_debug > 1)
2085 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2086 ast_deactivate_generator(chan);
2089 } else if (f->frametype == AST_FRAME_CNG) {
2090 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2091 if (option_debug > 1)
2092 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2093 ast_settimeout(chan, 160, generator_force, chan);
2098 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2100 struct ast_frame *f = NULL; /* the return value */
2104 /* this function is very long so make sure there is only one return
2105 * point at the end (there is only one exception to this).
2107 ast_channel_lock(chan);
2109 if (ast_do_masquerade(chan))
2110 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2112 f = &ast_null_frame;
2116 /* Stop if we're a zombie or need a soft hangup */
2117 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2118 if (chan->generator)
2119 ast_deactivate_generator(chan);
2122 prestate = chan->_state;
2124 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2125 !ast_strlen_zero(chan->dtmfq) &&
2126 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2127 /* We have DTMF that has been deferred. Return it now */
2128 chan->dtmff.subclass = chan->dtmfq[0];
2129 /* Drop first digit from the buffer */
2130 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2132 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY))
2133 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2135 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2136 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2137 chan->emulate_dtmf_digit = f->subclass;
2138 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2140 chan->dtmf_tv = ast_tvnow();
2144 /* Read and ignore anything on the alertpipe, but read only
2145 one sizeof(blah) per frame that we send from it */
2146 if (chan->alertpipe[0] > -1)
2147 read(chan->alertpipe[0], &blah, sizeof(blah));
2150 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2153 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2155 /* IF we can't get event, assume it's an expired as-per the old interface */
2156 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2158 blah = ZT_EVENT_TIMER_EXPIRED;
2160 if (blah == ZT_EVENT_TIMER_PING) {
2161 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2162 /* Acknowledge PONG unless we need it again */
2163 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2164 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2167 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2168 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2169 if (chan->timingfunc) {
2170 /* save a copy of func/data before unlocking the channel */
2171 int (*func)(void *) = chan->timingfunc;
2172 void *data = chan->timingdata;
2173 ast_channel_unlock(chan);
2177 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2178 chan->timingdata = NULL;
2179 ast_channel_unlock(chan);
2181 /* cannot 'goto done' because the channel is already unlocked */
2182 return &ast_null_frame;
2184 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2187 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2188 /* if the AST_GENERATOR_FD is set, call the generator with args
2189 * set to -1 so it can do whatever it needs to.
2191 void *tmp = chan->generatordata;
2192 chan->generatordata = NULL; /* reset to let ast_write get through */
2193 chan->generator->generate(chan, tmp, -1, -1);
2194 chan->generatordata = tmp;
2195 f = &ast_null_frame;
2199 /* Check for pending read queue */
2200 if (!AST_LIST_EMPTY(&chan->readq)) {
2201 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2202 /* Interpret hangup and return NULL */
2203 /* XXX why not the same for frames from the channel ? */
2204 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2209 chan->blocker = pthread_self();
2210 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2211 if (chan->tech->exception)
2212 f = chan->tech->exception(chan);
2214 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2215 f = &ast_null_frame;
2217 /* Clear the exception flag */
2218 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2219 } else if (chan->tech->read)
2220 f = chan->tech->read(chan);
2222 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2226 /* if the channel driver returned more than one frame, stuff the excess
2227 into the readq for the next ast_read call (note that we can safely assume
2228 that the readq is empty, because otherwise we would not have called into
2229 the channel driver and f would be only a single frame)
2231 if (AST_LIST_NEXT(f, frame_list)) {
2232 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2233 AST_LIST_NEXT(f, frame_list) = NULL;
2236 switch (f->frametype) {
2237 case AST_FRAME_CONTROL:
2238 if (f->subclass == AST_CONTROL_ANSWER) {
2239 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2240 ast_debug(1, "Ignoring answer on an inbound call!\n");
2242 f = &ast_null_frame;
2243 } else if (prestate == AST_STATE_UP) {
2244 ast_debug(1, "Dropping duplicate answer!\n");
2246 f = &ast_null_frame;
2248 /* Answer the CDR */
2249 ast_setstate(chan, AST_STATE_UP);
2250 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2251 to keep from throwing off the basic order of the universe,
2252 we will try to keep this cdr from getting posted. */
2253 chan->cdr = ast_cdr_alloc();
2254 ast_cdr_init(chan->cdr, chan);
2255 ast_cdr_start(chan->cdr);
2258 ast_cdr_answer(chan->cdr);
2262 case AST_FRAME_DTMF_END:
2263 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2264 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2265 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2266 * However, only let emulation be forced if the other end cares about BEGIN frames */
2267 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2268 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2269 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2270 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2272 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2274 f = &ast_null_frame;
2275 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2276 if (!ast_tvzero(chan->dtmf_tv) &&
2277 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2278 /* If it hasn't been long enough, defer this digit */
2279 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2280 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2282 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2284 f = &ast_null_frame;
2286 /* There was no begin, turn this into a begin and send the end later */
2287 f->frametype = AST_FRAME_DTMF_BEGIN;
2288 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2289 chan->emulate_dtmf_digit = f->subclass;
2290 chan->dtmf_tv = ast_tvnow();
2292 if (f->len > AST_MIN_DTMF_DURATION)
2293 chan->emulate_dtmf_duration = f->len;
2295 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2297 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2300 struct timeval now = ast_tvnow();
2301 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2303 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2304 if (f->len < AST_MIN_DTMF_DURATION) {
2305 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2306 chan->emulate_dtmf_digit = f->subclass;
2307 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2308 f = &ast_null_frame;
2310 chan->dtmf_tv = now;
2313 case AST_FRAME_DTMF_BEGIN:
2314 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2315 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2316 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) ||
2317 (!ast_tvzero(chan->dtmf_tv) &&
2318 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2320 f = &ast_null_frame;
2322 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2323 chan->dtmf_tv = ast_tvnow();
2326 case AST_FRAME_NULL:
2327 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2328 struct timeval now = ast_tvnow();
2329 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2330 chan->emulate_dtmf_duration = 0;
2333 f->frametype = AST_FRAME_DTMF_END;
2334 f->subclass = chan->emulate_dtmf_digit;
2335 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2336 chan->dtmf_tv = now;
2337 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2338 chan->emulate_dtmf_digit = 0;
2342 case AST_FRAME_VOICE:
2343 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2344 * is reached , because we want to make sure we pass at least one
2345 * voice frame through before starting the next digit, to ensure a gap
2346 * between DTMF digits. */
2347 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2348 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2349 chan->emulate_dtmf_digit = 0;
2352 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2354 ast_read_generator_actions(chan, f);
2356 f = &ast_null_frame;
2359 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2360 struct timeval now = ast_tvnow();
2361 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2362 chan->emulate_dtmf_duration = 0;
2365 f->frametype = AST_FRAME_DTMF_END;
2366 f->subclass = chan->emulate_dtmf_digit;
2367 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2368 chan->dtmf_tv = now;
2370 /* Drop voice frames while we're still in the middle of the digit */
2372 f = &ast_null_frame;
2374 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2375 /* This frame can't be from the current native formats -- drop it on the
2377 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2378 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2380 f = &ast_null_frame;
2381 } else if ((f->frametype == AST_FRAME_VOICE)) {
2383 queue_frame_to_spies(chan, f, SPY_READ);
2385 if (chan->monitor && chan->monitor->read_stream ) {
2386 /* XXX what does this do ? */
2387 #ifndef MONITOR_CONSTANT_DELAY
2388 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2390 jump = chan->outsmpl - chan->insmpl;
2391 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2392 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2393 chan->insmpl += jump + f->samples;
2395 chan->insmpl+= f->samples;
2397 int jump = chan->outsmpl - chan->insmpl;
2398 if (jump - MONITOR_DELAY >= 0) {
2399 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2400 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2401 chan->insmpl += jump;
2403 chan->insmpl += f->samples;
2405 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2406 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2407 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2411 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2412 f = &ast_null_frame;
2414 /* Run generator sitting on the line if timing device not available
2415 * and synchronous generation of outgoing frames is necessary */
2416 ast_read_generator_actions(chan, f);
2419 /* Just pass it on! */
2423 /* Make sure we always return NULL in the future */
2424 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2425 if (chan->generator)
2426 ast_deactivate_generator(chan);
2427 /* End the CDR if appropriate */
2429 ast_cdr_end(chan->cdr);
2432 /* High bit prints debugging */
2433 if (chan->fin & DEBUGCHAN_FLAG)
2434 ast_frame_dump(chan->name, f, "<<");
2435 chan->fin = FRAMECOUNT_INC(chan->fin);
2438 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2439 chan->generator->digit(chan, f->subclass);
2441 ast_channel_unlock(chan);
2445 int ast_internal_timing_enabled(struct ast_channel *chan)
2447 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2448 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2452 struct ast_frame *ast_read(struct ast_channel *chan)
2454 return __ast_read(chan, 0);
2457 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2459 return __ast_read(chan, 1);
2462 int ast_indicate(struct ast_channel *chan, int condition)
2464 return ast_indicate_data(chan, condition, NULL, 0);
2467 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2471 ast_channel_lock(chan);
2472 /* Stop if we're a zombie or need a soft hangup */
2473 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2474 ast_channel_unlock(chan);
2477 if (chan->tech->indicate)
2478 res = chan->tech->indicate(chan, condition, data, datalen);
2479 ast_channel_unlock(chan);
2480 if (!chan->tech->indicate || res) {
2482 * Device does not support (that) indication, lets fake
2483 * it by doing our own tone generation. (PM2002)
2486 ast_playtones_stop(chan);
2488 const struct ind_tone_zone_sound *ts = NULL;
2489 switch (condition) {
2490 case AST_CONTROL_RINGING:
2491 ts = ast_get_indication_tone(chan->zone, "ring");
2493 case AST_CONTROL_BUSY:
2494 ts = ast_get_indication_tone(chan->zone, "busy");
2496 case AST_CONTROL_CONGESTION:
2497 ts = ast_get_indication_tone(chan->zone, "congestion");
2500 if (ts && ts->data[0]) {
2501 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2502 ast_playtones_start(chan,0,ts->data, 1);
2504 } else if (condition == AST_CONTROL_PROGRESS) {
2505 /* ast_playtones_stop(chan); */
2506 } else if (condition == AST_CONTROL_PROCEEDING) {
2507 /* Do nothing, really */
2508 } else if (condition == AST_CONTROL_HOLD) {
2509 /* Do nothing.... */
2510 } else if (condition == AST_CONTROL_UNHOLD) {
2511 /* Do nothing.... */
2512 } else if (condition == AST_CONTROL_VIDUPDATE) {
2513 /* Do nothing.... */
2516 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2524 int ast_recvchar(struct ast_channel *chan, int timeout)
2527 char *buf = ast_recvtext(chan, timeout);
2529 return -1; /* error or timeout */
2530 c = *(unsigned char *)buf;
2535 char *ast_recvtext(struct ast_channel *chan, int timeout)
2541 struct ast_frame *f;
2542 if (ast_check_hangup(chan))
2544 res = ast_waitfor(chan, timeout);
2545 if (res <= 0) /* timeout or error */
2547 timeout = res; /* update timeout */
2550 break; /* no frame */
2551 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2552 done = 1; /* force a break */
2553 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2554 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2562 int ast_sendtext(struct ast_channel *chan, const char *text)
2565 /* Stop if we're a zombie or need a soft hangup */
2566 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2568 CHECK_BLOCKING(chan);
2569 if (chan->tech->send_text)
2570 res = chan->tech->send_text(chan, text);
2571 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2575 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2577 /* Device does not support DTMF tones, lets fake
2578 * it by doing our own generation. */
2579 static const char* dtmf_tones[] = {
2598 if (!chan->tech->send_digit_begin)
2601 if (!chan->tech->send_digit_begin(chan, digit))
2604 if (digit >= '0' && digit <='9')
2605 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2606 else if (digit >= 'A' && digit <= 'D')
2607 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2608 else if (digit == '*')
2609 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2610 else if (digit == '#')
2611 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2614 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2620 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2624 if (chan->tech->send_digit_end)
2625 res = chan->tech->send_digit_end(chan, digit, duration);
2627 if (res && chan->generator)
2628 ast_playtones_stop(chan);
2633 int ast_senddigit(struct ast_channel *chan, char digit)
2635 if (chan->tech->send_digit_begin) {
2636 ast_senddigit_begin(chan, digit);
2637 ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2640 return ast_senddigit_end(chan, digit, 100);
2643 int ast_prod(struct ast_channel *chan)
2645 struct ast_frame a = { AST_FRAME_VOICE };
2648 /* Send an empty audio frame to get things moving */
2649 if (chan->_state != AST_STATE_UP) {
2650 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2651 a.subclass = chan->rawwriteformat;
2652 a.data = nothing + AST_FRIENDLY_OFFSET;
2654 if (ast_write(chan, &a))
2655 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2660 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2663 if (!chan->tech->write_video)
2665 res = ast_write(chan, fr);
2671 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2674 struct ast_frame *f = NULL;
2676 /* Stop if we're a zombie or need a soft hangup */
2677 ast_channel_lock(chan);
2678 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2681 /* Handle any pending masquerades */
2682 if (chan->masq && ast_do_masquerade(chan)) {
2683 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2687 res = 0; /* XXX explain, why 0 ? */
2690 if (chan->generatordata) {
2691 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2692 ast_deactivate_generator(chan);
2694 if (fr->frametype == AST_FRAME_DTMF_END) {
2695 /* There is a generator running while we're in the middle of a digit.
2696 * It's probably inband DTMF, so go ahead and pass it so it can
2697 * stop the generator */
2698 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2699 ast_channel_unlock(chan);
2700 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2701 ast_channel_lock(chan);
2702 CHECK_BLOCKING(chan);
2703 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2704 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2705 res = (chan->tech->indicate == NULL) ? 0 :
2706 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2708 res = 0; /* XXX explain, why 0 ? */
2712 /* High bit prints debugging */
2713 if (chan->fout & DEBUGCHAN_FLAG)
2714 ast_frame_dump(chan->name, fr, ">>");
2715 CHECK_BLOCKING(chan);
2716 switch (fr->frametype) {
2717 case AST_FRAME_CONTROL:
2718 res = (chan->tech->indicate == NULL) ? 0 :
2719 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2721 case AST_FRAME_DTMF_BEGIN:
2722 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2723 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2724 ast_channel_unlock(chan);
2725 res = ast_senddigit_begin(chan, fr->subclass);
2726 ast_channel_lock(chan);
2727 CHECK_BLOCKING(chan);
2729 case AST_FRAME_DTMF_END:
2730 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2731 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2732 ast_channel_unlock(chan);
2733 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2734 ast_channel_lock(chan);
2735 CHECK_BLOCKING(chan);
2737 case AST_FRAME_TEXT:
2738 if (fr->subclass == AST_FORMAT_T140) {
2739 res = (chan->tech->write_text == NULL) ? 0 :
2740 chan->tech->write_text(chan, fr);
2742 res = (chan->tech->send_text == NULL) ? 0 :
2743 chan->tech->send_text(chan, (char *) fr->data);
2746 case AST_FRAME_HTML:
2747 res = (chan->tech->send_html == NULL) ? 0 :
2748 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2750 case AST_FRAME_VIDEO:
2751 /* XXX Handle translation of video codecs one day XXX */
2752 res = (chan->tech->write_video == NULL) ? 0 :
2753 chan->tech->write_video(chan, fr);
2755 case AST_FRAME_MODEM:
2756 res = (chan->tech->write == NULL) ? 0 :
2757 chan->tech->write(chan, fr);
2759 case AST_FRAME_VOICE:
2760 if (chan->tech->write == NULL)
2761 break; /*! \todo XXX should return 0 maybe ? */
2763 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2764 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2765 if (fr->subclass == AST_FORMAT_SLINEAR)
2768 ast_mutex_lock(&chan->whisper->lock);
2769 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2770 /* Rebuild the translation path and set our write format back to signed linear */
2771 chan->whisper->original_format = chan->writeformat;
2772 ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2773 if (chan->whisper->path)
2774 ast_translator_free_path(chan->whisper->path);
2775 chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2777 /* Translate frame using the above translation path */
2778 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2779 ast_mutex_unlock(&chan->whisper->lock);
2782 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2783 if (fr->subclass == chan->rawwriteformat)
2786 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2789 /* If we have no frame of audio, then we have to bail out */
2795 /* If spies are on the channel then queue the frame out to them */
2797 queue_frame_to_spies(chan, f, SPY_WRITE);
2799 /* If Monitor is running on this channel, then we have to write frames out there too */
2800 if (chan->monitor && chan->monitor->write_stream) {
2801 /* XXX must explain this code */
2802 #ifndef MONITOR_CONSTANT_DELAY
2803 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2805 jump = chan->insmpl - chan->outsmpl;
2806 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2807 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2808 chan->outsmpl += jump + f->samples;
2810 chan->outsmpl += f->samples;
2812 int jump = chan->insmpl - chan->outsmpl;
2813 if (jump - MONITOR_DELAY >= 0) {
2814 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2815 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2816 chan->outsmpl += jump;
2818 chan->outsmpl += f->samples;
2820 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2821 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2822 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2826 /* Finally the good part! Write this out to the channel */
2827 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2828 /* frame is assumed to be in SLINEAR, since that is
2829 required for whisper mode */
2830 ast_frame_adjust_volume(f, -2);
2831 if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2832 short buf[f->samples];
2833 struct ast_frame whisper = {
2834 .frametype = AST_FRAME_VOICE,
2835 .subclass = AST_FORMAT_SLINEAR,
2837 .datalen = sizeof(buf),
2838 .samples = f->samples,
2841 ast_mutex_lock(&chan->whisper->lock);
2842 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2843 ast_frame_slinear_sum(f, &whisper);
2844 ast_mutex_unlock(&chan->whisper->lock);
2846 /* and now put it through the regular translator */
2847 f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2849 res = f ? chan->tech->write(chan, f) : 0;
2851 case AST_FRAME_NULL:
2857 /* At this point, fr is the incoming frame and f is NULL. Channels do
2858 * not expect to get NULL as a frame pointer and will segfault. Hence,
2859 * we output the original frame passed in. */
2860 res = chan->tech->write(chan, fr);
2866 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2867 /* Consider a write failure to force a soft hangup */
2869 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2871 chan->fout = FRAMECOUNT_INC(chan->fout);
2874 ast_channel_unlock(chan);
2878 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2879 struct ast_trans_pvt **trans, const int direction)
2884 /* Make sure we only consider audio */
2885 fmt &= AST_FORMAT_AUDIO_MASK;
2887 native = chan->nativeformats;
2888 /* Find a translation path from the native format to one of the desired formats */
2891 res = ast_translator_best_choice(&fmt, &native);
2894 res = ast_translator_best_choice(&native, &fmt);
2897 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2898 ast_getformatname(native), ast_getformatname(fmt));
2902 /* Now we have a good choice for both. */
2903 ast_channel_lock(chan);
2905 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2906 /* the channel is already in these formats, so nothing to do */
2907 ast_channel_unlock(chan);
2911 *rawformat = native;
2912 /* User perspective is fmt */
2914 /* Free any read translation we have right now */
2916 ast_translator_free_path(*trans);
2917 /* Build a translation path from the raw format to the desired format */
2920 *trans = ast_translator_build_path(*format, *rawformat);
2923 *trans = ast_translator_build_path(*rawformat, *format);
2924 ast_channel_unlock(chan);
2925 ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
2926 direction ? "write" : "read", ast_getformatname(fmt));
2930 int ast_set_read_format(struct ast_channel *chan, int fmt)
2932 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2933 &chan->readtrans, 0);
2936 int ast_set_write_format(struct ast_channel *chan, int fmt)
2938 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2939 &chan->writetrans, 1);
2942 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)
2946 struct ast_channel *chan;
2952 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2954 chan = ast_request(type, format, data, &cause);
2956 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2957 /* compute error and return */
2958 if (cause == AST_CAUSE_BUSY)
2959 *outstate = AST_CONTROL_BUSY;
2960 else if (cause == AST_CAUSE_CONGESTION)
2961 *outstate = AST_CONTROL_CONGESTION;
2967 ast_set_variables(chan, oh->vars);
2968 /* XXX why is this necessary, for the parent_channel perhaps ? */
2969 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2970 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2971 if (oh->parent_channel) {
2972 ast_channel_inherit_variables(oh->parent_channel, chan);
2973 ast_channel_datastore_inherit(oh->parent_channel, chan);
2976 ast_cdr_setaccount(chan, oh->account);
2978 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2982 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2983 to keep from throwing off the basic order of the universe,
2984 we will try to keep this cdr from getting posted. */
2985 chan->cdr = ast_cdr_alloc();
2986 ast_cdr_init(chan->cdr, chan);
2987 ast_cdr_start(chan->cdr);
2989 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2990 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2992 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2993 while (timeout && chan->_state != AST_STATE_UP) {
2994 struct ast_frame *f;
2995 res = ast_waitfor(chan, timeout);
2996 if (res <= 0) /* error, timeout, or done */
3002 *outstate = AST_CONTROL_HANGUP;
3006 if (f->frametype == AST_FRAME_CONTROL) {
3007 switch (f->subclass) {
3008 case AST_CONTROL_RINGING: /* record but keep going */
3009 *outstate = f->subclass;
3012 case AST_CONTROL_BUSY:
3013 case AST_CONTROL_CONGESTION:
3014 case AST_CONTROL_ANSWER:
3015 *outstate = f->subclass;
3016 timeout = 0; /* trick to force exit from the while() */
3020 case AST_CONTROL_PROGRESS:
3021 case AST_CONTROL_PROCEEDING:
3022 case AST_CONTROL_HOLD:
3023 case AST_CONTROL_UNHOLD:
3024 case AST_CONTROL_VIDUPDATE:
3025 case -1: /* Ignore -- just stopping indications */
3029 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3038 if (!ast_strlen_zero(oh->context))
3039 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3040 if (!ast_strlen_zero(oh->exten))
3041 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3043 chan->priority = oh->priority;
3045 if (chan->_state == AST_STATE_UP)
3046 *outstate = AST_CONTROL_ANSWER;
3049 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3050 ast_cdr_init(chan->cdr, chan);
3053 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);