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$")
30 #include "asterisk/_private.h"
36 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
37 #include "asterisk/zapata.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/musiconhold.h"
44 #include "asterisk/say.h"
45 #include "asterisk/file.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/translate.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/chanvars.h"
50 #include "asterisk/linkedlists.h"
51 #include "asterisk/indications.h"
52 #include "asterisk/monitor.h"
53 #include "asterisk/causes.h"
54 #include "asterisk/callerid.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/app.h"
58 #include "asterisk/transcap.h"
59 #include "asterisk/devicestate.h"
60 #include "asterisk/sha1.h"
61 #include "asterisk/threadstorage.h"
62 #include "asterisk/slinfactory.h"
63 #include "asterisk/audiohook.h"
66 #include <sys/epoll.h>
69 struct ast_epoll_data {
70 struct ast_channel *chan;
74 /* uncomment if you have problems with 'monitoring' synchronized files */
76 #define MONITOR_CONSTANT_DELAY
77 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
80 /*! \brief Prevent new channel allocation if shutting down. */
81 static int shutting_down;
85 unsigned long global_fin, global_fout;
87 AST_THREADSTORAGE(state2str_threadbuf);
88 #define STATE2STR_BUFSIZE 32
90 /*! Default amount of time to use when emulating a digit as a begin and end
92 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
94 /*! Minimum allowed digit length - 80ms */
95 #define AST_MIN_DTMF_DURATION 80
97 /*! Minimum amount of time between the end of the last digit and the beginning
98 * of a new one - 45ms */
99 #define AST_MIN_DTMF_GAP 45
101 /*! \brief List of channel drivers */
103 const struct ast_channel_tech *tech;
104 AST_LIST_ENTRY(chanlist) list;
108 /*! \brief Structure to hold channel context backtrace data */
109 struct ast_chan_trace_data {
111 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
114 /*! \brief Structure to save contexts where an ast_chan has been into */
115 struct ast_chan_trace {
116 char context[AST_MAX_CONTEXT];
117 char exten[AST_MAX_EXTENSION];
119 AST_LIST_ENTRY(ast_chan_trace) entry;
123 /*! \brief the list of registered channel types */
124 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
126 /*! \brief the list of channels we have. Note that the lock for this list is used for
127 both the channels list and the backends list. */
128 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
130 /*! \brief map AST_CAUSE's to readable string representations
134 const struct ast_cause {
139 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
140 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
141 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
142 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
143 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
144 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
145 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
146 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
147 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
148 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
149 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
150 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
151 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
152 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
153 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
154 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
155 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
156 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
157 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
158 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
159 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
160 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
161 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
162 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
163 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
164 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
165 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
166 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
167 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
168 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
169 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
170 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
171 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
172 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
173 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
174 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
175 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
176 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
177 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
178 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
179 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
180 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
181 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
182 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
185 struct ast_variable *ast_channeltype_list(void)
188 struct ast_variable *var=NULL, *prev = NULL;
189 AST_LIST_TRAVERSE(&backends, cl, list) {
191 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
194 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
201 /*! \brief Show channel types - CLI command */
202 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
204 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
210 e->command = "core show channeltypes";
212 "Usage: core show channeltypes\n"
213 " Lists available channel types registered in your\n"
214 " Asterisk server.\n";
221 return CLI_SHOWUSAGE;
223 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
224 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
226 AST_RWLIST_RDLOCK(&channels);
228 AST_LIST_TRAVERSE(&backends, cl, list) {
229 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
230 (cl->tech->devicestate) ? "yes" : "no",
231 (cl->tech->indicate) ? "yes" : "no",
232 (cl->tech->transfer) ? "yes" : "no");
236 AST_RWLIST_UNLOCK(&channels);
238 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
245 static char *complete_channeltypes(struct ast_cli_args *a)
255 wordlen = strlen(a->word);
257 AST_LIST_TRAVERSE(&backends, cl, list) {
258 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
259 ret = ast_strdup(cl->tech->type);
267 /*! \brief Show details about a channel driver - CLI command */
268 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
270 struct chanlist *cl = NULL;
274 e->command = "core show channeltype";
276 "Usage: core show channeltype <name>\n"
277 " Show details about the specified channel type, <name>.\n";
280 return complete_channeltypes(a);
284 return CLI_SHOWUSAGE;
286 AST_RWLIST_RDLOCK(&channels);
288 AST_LIST_TRAVERSE(&backends, cl, list) {
289 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
295 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
296 AST_RWLIST_UNLOCK(&channels);
301 "-- Info about channel driver: %s --\n"
302 " Device State: %s\n"
305 " Capabilities: %d\n"
309 " Image Support: %s\n"
310 " Text Support: %s\n",
312 (cl->tech->devicestate) ? "yes" : "no",
313 (cl->tech->indicate) ? "yes" : "no",
314 (cl->tech->transfer) ? "yes" : "no",
315 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
316 (cl->tech->send_digit_begin) ? "yes" : "no",
317 (cl->tech->send_digit_end) ? "yes" : "no",
318 (cl->tech->send_html) ? "yes" : "no",
319 (cl->tech->send_image) ? "yes" : "no",
320 (cl->tech->send_text) ? "yes" : "no"
324 AST_RWLIST_UNLOCK(&channels);
328 static struct ast_cli_entry cli_channel[] = {
329 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
330 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
334 /*! \brief Destructor for the channel trace datastore */
335 static void ast_chan_trace_destroy_cb(void *data)
337 struct ast_chan_trace *trace;
338 struct ast_chan_trace_data *traced = data;
339 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
345 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
346 const struct ast_datastore_info ast_chan_trace_datastore_info = {
348 .destroy = ast_chan_trace_destroy_cb
351 /*! \brief Put the channel backtrace in a string */
352 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
355 struct ast_chan_trace *trace;
356 struct ast_chan_trace_data *traced;
357 struct ast_datastore *store;
359 ast_channel_lock(chan);
360 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
362 ast_channel_unlock(chan);
365 traced = store->data;
367 (*buf)->str[0] = '\0';
368 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
369 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
370 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
376 ast_channel_unlock(chan);
380 /* !\brief Whether or not context tracing is enabled */
381 int ast_channel_trace_is_enabled(struct ast_channel *chan)
383 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
386 return ((struct ast_chan_trace_data *)store->data)->enabled;
389 /*! \brief Update the context backtrace data if tracing is enabled */
390 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
392 struct ast_chan_trace *trace;
393 if (!traced->enabled)
395 /* If the last saved context does not match the current one
396 OR we have not saved any context so far, then save the current context */
397 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
398 (AST_LIST_EMPTY(&traced->trace))) {
399 /* Just do some debug logging */
400 if (AST_LIST_EMPTY(&traced->trace))
401 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
403 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
404 /* alloc or bail out */
405 trace = ast_malloc(sizeof(*trace));
408 /* save the current location and store it in the trace list */
409 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
410 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
411 trace->priority = chan->priority;
412 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
417 /*! \brief Update the context backtrace if tracing is enabled */
418 int ast_channel_trace_update(struct ast_channel *chan)
420 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
423 return ast_channel_trace_data_update(chan, store->data);
426 /*! \brief Enable context tracing in the channel */
427 int ast_channel_trace_enable(struct ast_channel *chan)
429 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
430 struct ast_chan_trace_data *traced;
432 store = ast_channel_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
435 traced = ast_calloc(1, sizeof(*traced));
437 ast_channel_datastore_free(store);
440 store->data = traced;
441 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
442 ast_channel_datastore_add(chan, store);
444 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
445 ast_channel_trace_data_update(chan, store->data);
449 /*! \brief Disable context tracing in the channel */
450 int ast_channel_trace_disable(struct ast_channel *chan)
452 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
455 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
458 #endif /* CHANNEL_TRACE */
460 /*! \brief Checks to see if a channel is needing hang up */
461 int ast_check_hangup(struct ast_channel *chan)
463 if (chan->_softhangup) /* yes if soft hangup flag set */
465 if (!chan->tech_pvt) /* yes if no technology private data */
467 if (!chan->whentohangup) /* no if no hangup scheduled */
469 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
471 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
475 static int ast_check_hangup_locked(struct ast_channel *chan)
478 ast_channel_lock(chan);
479 res = ast_check_hangup(chan);
480 ast_channel_unlock(chan);
484 /*! \brief Initiate system shutdown */
485 void ast_begin_shutdown(int hangup)
487 struct ast_channel *c;
490 AST_RWLIST_RDLOCK(&channels);
491 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
492 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
493 AST_RWLIST_UNLOCK(&channels);
497 /*! \brief returns number of active/allocated channels */
498 int ast_active_channels(void)
500 struct ast_channel *c;
502 AST_RWLIST_RDLOCK(&channels);
503 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
505 AST_RWLIST_UNLOCK(&channels);
509 /*! \brief Cancel a shutdown in progress */
510 void ast_cancel_shutdown(void)
515 /*! \brief Returns non-zero if Asterisk is being shut down */
516 int ast_shutting_down(void)
518 return shutting_down;
521 /*! \brief Set when to hangup channel */
522 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
524 chan->whentohangup = offset ? time(NULL) + offset : 0;
525 ast_queue_frame(chan, &ast_null_frame);
529 /*! \brief Compare a offset with when to hangup channel */
530 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
534 if (!chan->whentohangup)
535 return (offset == 0) ? 0 : -1;
537 if (!offset) /* XXX why is this special? */
540 whentohangup = offset + time(NULL);
542 if (chan->whentohangup < whentohangup)
544 else if (chan->whentohangup == whentohangup)
550 /*! \brief Register a new telephony channel in Asterisk */
551 int ast_channel_register(const struct ast_channel_tech *tech)
553 struct chanlist *chan;
555 AST_RWLIST_WRLOCK(&channels);
557 AST_LIST_TRAVERSE(&backends, chan, list) {
558 if (!strcasecmp(tech->type, chan->tech->type)) {
559 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
560 AST_RWLIST_UNLOCK(&channels);
565 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
566 AST_RWLIST_UNLOCK(&channels);
570 AST_LIST_INSERT_HEAD(&backends, chan, list);
572 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
574 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
576 AST_RWLIST_UNLOCK(&channels);
580 /*! \brief Unregister channel driver */
581 void ast_channel_unregister(const struct ast_channel_tech *tech)
583 struct chanlist *chan;
585 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
587 AST_RWLIST_WRLOCK(&channels);
589 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
590 if (chan->tech == tech) {
591 AST_LIST_REMOVE_CURRENT(list);
593 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
597 AST_LIST_TRAVERSE_SAFE_END;
599 AST_RWLIST_UNLOCK(&channels);
602 /*! \brief Get handle to channel driver based on name */
603 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
605 struct chanlist *chanls;
606 const struct ast_channel_tech *ret = NULL;
608 AST_RWLIST_RDLOCK(&channels);
610 AST_LIST_TRAVERSE(&backends, chanls, list) {
611 if (!strcasecmp(name, chanls->tech->type)) {
617 AST_RWLIST_UNLOCK(&channels);
622 /*! \brief Gives the string form of a given hangup cause */
623 const char *ast_cause2str(int cause)
627 for (x = 0; x < ARRAY_LEN(causes); x++) {
628 if (causes[x].cause == cause)
629 return causes[x].desc;
635 /*! \brief Convert a symbolic hangup cause to number */
636 int ast_str2cause(const char *name)
640 for (x = 0; x < ARRAY_LEN(causes); x++)
641 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
642 return causes[x].cause;
647 /*! \brief Gives the string form of a given channel state.
648 \note This function is not reentrant.
650 const char *ast_state2str(enum ast_channel_state state)
657 case AST_STATE_RESERVED:
659 case AST_STATE_OFFHOOK:
661 case AST_STATE_DIALING:
665 case AST_STATE_RINGING:
671 case AST_STATE_DIALING_OFFHOOK:
672 return "Dialing Offhook";
673 case AST_STATE_PRERING:
676 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
678 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
683 /*! \brief Gives the string form of a given transfer capability */
684 char *ast_transfercapability2str(int transfercapability)
686 switch (transfercapability) {
687 case AST_TRANS_CAP_SPEECH:
689 case AST_TRANS_CAP_DIGITAL:
691 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
692 return "RESTRICTED_DIGITAL";
693 case AST_TRANS_CAP_3_1K_AUDIO:
695 case AST_TRANS_CAP_DIGITAL_W_TONES:
696 return "DIGITAL_W_TONES";
697 case AST_TRANS_CAP_VIDEO:
704 /*! \brief Pick the best audio codec */
705 int ast_best_codec(int fmts)
707 /* This just our opinion, expressed in code. We are asked to choose
708 the best codec to use, given no information */
710 static const int prefs[] =
712 /*! Okay, ulaw is used by all telephony equipment, so start with it */
714 /*! Unless of course, you're a silly European, so then prefer ALAW */
716 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
718 /*! Okay, well, signed linear is easy to translate into other stuff */
719 AST_FORMAT_SLINEAR16,
721 /*! G.726 is standard ADPCM, in RFC3551 packing order */
723 /*! G.726 is standard ADPCM, in AAL2 packing order */
724 AST_FORMAT_G726_AAL2,
725 /*! ADPCM has great sound quality and is still pretty easy to translate */
727 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
728 translate and sounds pretty good */
730 /*! iLBC is not too bad */
732 /*! Speex is free, but computationally more expensive than GSM */
734 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
737 /*! G.729a is faster than 723 and slightly less expensive */
739 /*! Down to G.723.1 which is proprietary but at least designed for voice */
743 /* Strip out video */
744 fmts &= AST_FORMAT_AUDIO_MASK;
746 /* Find the first preferred codec in the format given */
747 for (x = 0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++) {
752 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
757 static const struct ast_channel_tech null_tech = {
759 .description = "Null channel (should not see this)",
762 /*! \brief Create a new channel structure */
763 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, ...)
765 struct ast_channel *tmp;
768 struct varshead *headp;
771 /* If shutting down, don't allocate any new channels */
773 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
777 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
780 if (!(tmp->sched = sched_context_create())) {
781 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
786 if ((ast_string_field_init(tmp, 128))) {
787 sched_context_destroy(tmp->sched);
793 tmp->epfd = epoll_create(25);
796 for (x = 0; x < AST_MAX_FDS; x++) {
799 tmp->epfd_data[x] = NULL;
804 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
805 if (tmp->timingfd > -1) {
806 /* Check if timing interface supports new
809 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
817 if (pipe(tmp->alertpipe)) {
818 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
820 if (tmp->timingfd > -1)
821 close(tmp->timingfd);
823 sched_context_destroy(tmp->sched);
824 ast_string_field_free_memory(tmp);
828 flags = fcntl(tmp->alertpipe[0], F_GETFL);
829 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
830 flags = fcntl(tmp->alertpipe[1], F_GETFL);
831 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
833 } else /* Make sure we've got it done right if they don't */
834 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
836 /* Always watch the alertpipe */
837 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
838 /* And timing pipe */
839 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
840 ast_string_field_set(tmp, name, "**Unknown**");
847 tmp->fin = global_fin;
848 tmp->fout = global_fout;
850 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
851 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
852 ast_atomic_fetchadd_int(&uniqueint, 1));
854 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
855 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
858 tmp->cid.cid_name = ast_strdup(cid_name);
859 tmp->cid.cid_num = ast_strdup(cid_num);
861 if (!ast_strlen_zero(name_fmt)) {
862 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
863 * And they all use slightly different formats for their name string.
864 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
865 * This means, that the stringfields must have a routine that takes the va_lists directly, and
866 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
867 * This new function was written so this can be accomplished.
869 va_start(ap1, name_fmt);
870 va_start(ap2, name_fmt);
871 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
876 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
878 /* These 4 variables need to be set up for the cdr_init() to work right */
880 tmp->amaflags = amaflag;
882 tmp->amaflags = ast_default_amaflags;
884 if (!ast_strlen_zero(acctcode))
885 ast_string_field_set(tmp, accountcode, acctcode);
887 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
889 if (!ast_strlen_zero(context))
890 ast_copy_string(tmp->context, context, sizeof(tmp->context));
892 strcpy(tmp->context, "default");
894 if (!ast_strlen_zero(exten))
895 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
897 strcpy(tmp->exten, "s");
901 tmp->cdr = ast_cdr_alloc();
902 ast_cdr_init(tmp->cdr, tmp);
903 ast_cdr_start(tmp->cdr);
905 headp = &tmp->varshead;
906 AST_LIST_HEAD_INIT_NOLOCK(headp);
908 ast_mutex_init(&tmp->lock_dont_use);
910 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
912 ast_string_field_set(tmp, language, defaultlanguage);
914 tmp->tech = &null_tech;
916 AST_RWLIST_WRLOCK(&channels);
917 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
918 AST_RWLIST_UNLOCK(&channels);
921 * and now, since the channel structure is built, and has its name, let's
922 * call the manager event generator with this Newchannel event. This is the
923 * proper and correct place to make this call, but you sure do have to pass
924 * a lot of data into this func to do it here!
926 if (!ast_strlen_zero(name_fmt)) {
927 manager_event(EVENT_FLAG_CALL, "Newchannel",
929 "ChannelState: %d\r\n"
930 "ChannelStateDesc: %s\r\n"
931 "CallerIDNum: %s\r\n"
932 "CallerIDName: %s\r\n"
933 "AccountCode: %s\r\n"
937 ast_state2str(state),
947 /*! \brief Queue an outgoing media frame */
948 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
951 struct ast_frame *cur;
955 /* Build us a copy and free the original one */
956 if (!(f = ast_frdup(fin))) {
957 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
960 ast_channel_lock(chan);
962 /* See if the last frame on the queue is a hangup, if so don't queue anything */
963 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
965 ast_channel_unlock(chan);
969 /* Count how many frames exist on the queue */
970 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
974 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
975 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
976 if (fin->frametype != AST_FRAME_VOICE) {
977 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
980 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
982 ast_channel_unlock(chan);
986 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
987 if (chan->alertpipe[1] > -1) {
988 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
989 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
990 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
992 } else if (chan->timingfd > -1) {
993 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
995 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
996 pthread_kill(chan->blocker, SIGURG);
998 ast_channel_unlock(chan);
1002 /*! \brief Queue a hangup frame for channel */
1003 int ast_queue_hangup(struct ast_channel *chan)
1005 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1006 /* Yeah, let's not change a lock-critical value without locking */
1007 if (!ast_channel_trylock(chan)) {
1008 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1009 ast_channel_unlock(chan);
1011 return ast_queue_frame(chan, &f);
1014 /*! \brief Queue a control frame */
1015 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1017 struct ast_frame f = { AST_FRAME_CONTROL, };
1019 f.subclass = control;
1021 return ast_queue_frame(chan, &f);
1024 /*! \brief Queue a control frame with payload */
1025 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1026 const void *data, size_t datalen)
1028 struct ast_frame f = { AST_FRAME_CONTROL, };
1030 f.subclass = control;
1031 f.data = (void *) data;
1032 f.datalen = datalen;
1034 return ast_queue_frame(chan, &f);
1037 /*! \brief Set defer DTMF flag on channel */
1038 int ast_channel_defer_dtmf(struct ast_channel *chan)
1043 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1044 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1049 /*! \brief Unset defer DTMF flag on channel */
1050 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1053 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1057 * \brief Helper function to find channels.
1059 * It supports these modes:
1061 * prev != NULL : get channel next in list after prev
1062 * name != NULL : get channel with matching name
1063 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1064 * exten != NULL : get channel whose exten or macroexten matches
1065 * context != NULL && exten != NULL : get channel whose context or macrocontext
1067 * It returns with the channel's lock held. If getting the individual lock fails,
1068 * unlock and retry quickly up to 10 times, then give up.
1070 * \note XXX Note that this code has cost O(N) because of the need to verify
1071 * that the object is still on the global list.
1073 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1074 * can only be done with the lock held or someone could delete the
1075 * object while we work on it. This causes some ugliness in the code.
1076 * Note that removing the first ast_log() may be harmful, as it would
1077 * shorten the retry period and possibly cause failures.
1078 * We should definitely go for a better scheme that is deadlock-free.
1080 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1081 const char *name, const int namelen,
1082 const char *context, const char *exten)
1084 const char *msg = prev ? "deadlock" : "initial deadlock";
1086 struct ast_channel *c;
1087 const struct ast_channel *_prev = prev;
1089 for (retries = 0; retries < 10; retries++) {
1091 AST_RWLIST_RDLOCK(&channels);
1092 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1094 if (prev) { /* look for next item */
1095 if (c != prev) /* not this one */
1097 /* found, prepare to return c->next */
1098 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
1099 /* If prev was the last item on the channel list, then we just
1100 * want to return NULL, instead of trying to deref NULL in the
1104 /* We want prev to be NULL in case we end up doing more searching through
1105 * the channel list to find the channel (ie: name searching). If we didn't
1106 * set this to NULL the logic would just blow up
1107 * XXX Need a better explanation for this ...
1110 if (name) { /* want match by name */
1111 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
1112 (namelen && strncasecmp(c->name, name, namelen)))
1113 continue; /* name match failed */
1115 if (context && strcasecmp(c->context, context) &&
1116 strcasecmp(c->macrocontext, context))
1117 continue; /* context match failed */
1118 if (strcasecmp(c->exten, exten) &&
1119 strcasecmp(c->macroexten, exten))
1120 continue; /* exten match failed */
1122 /* if we get here, c points to the desired record */
1125 /* exit if chan not found or mutex acquired successfully */
1126 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1127 done = c == NULL || ast_channel_trylock(c) == 0;
1129 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
1131 /* We are about to fail due to a deadlock, so report this
1132 * while we still have the list lock.
1134 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1135 /* As we have deadlocked, we will skip this channel and
1136 * see if there is another match.
1137 * NOTE: No point doing this for a full-name match,
1138 * as there can be no more matches.
1140 if (!(name && !namelen)) {
1146 AST_RWLIST_UNLOCK(&channels);
1149 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1150 * starting from the beginning of the list we can restore our saved pointer to the previous
1151 * channel and start from there.
1154 usleep(1); /* give other threads a chance before retrying */
1160 /*! \brief Browse channels in use */
1161 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1163 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1166 /*! \brief Get channel by name and lock it */
1167 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1169 return channel_find_locked(NULL, name, 0, NULL, NULL);
1172 /*! \brief Get channel by name prefix and lock it */
1173 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1175 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1178 /*! \brief Get next channel by name prefix and lock it */
1179 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1182 return channel_find_locked(chan, name, namelen, NULL, NULL);
1185 /*! \brief Get channel by exten (and optionally context) and lock it */
1186 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1188 return channel_find_locked(NULL, NULL, 0, context, exten);
1191 /*! \brief Get next channel by exten (and optionally context) and lock it */
1192 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1193 const char *context)
1195 return channel_find_locked(chan, NULL, 0, context, exten);
1198 /*! \brief Wait, look for hangups and condition arg */
1199 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1201 struct ast_frame *f;
1204 if (cond && ((*cond)(data) == 0))
1206 ms = ast_waitfor(chan, ms);
1219 /*! \brief Wait, look for hangups */
1220 int ast_safe_sleep(struct ast_channel *chan, int ms)
1222 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1225 static void free_cid(struct ast_callerid *cid)
1228 ast_free(cid->cid_dnid);
1230 ast_free(cid->cid_num);
1232 ast_free(cid->cid_name);
1234 ast_free(cid->cid_ani);
1236 ast_free(cid->cid_rdnis);
1237 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1240 /*! \brief Free a channel structure */
1241 void ast_channel_free(struct ast_channel *chan)
1247 struct ast_var_t *vardata;
1248 struct ast_frame *f;
1249 struct varshead *headp;
1250 struct ast_datastore *datastore = NULL;
1251 char name[AST_CHANNEL_NAME];
1253 headp=&chan->varshead;
1255 AST_RWLIST_WRLOCK(&channels);
1256 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1257 AST_RWLIST_UNLOCK(&channels);
1258 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1260 /* Lock and unlock the channel just to be sure nobody
1261 has it locked still */
1262 ast_channel_lock(chan);
1263 ast_channel_unlock(chan);
1264 if (chan->tech_pvt) {
1265 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1266 ast_free(chan->tech_pvt);
1270 sched_context_destroy(chan->sched);
1272 ast_copy_string(name, chan->name, sizeof(name));
1274 /* Stop monitoring */
1276 chan->monitor->stop( chan, 0 );
1278 /* If there is native format music-on-hold state, free it */
1279 if (chan->music_state)
1280 ast_moh_cleanup(chan);
1282 /* Free translators */
1283 if (chan->readtrans)
1284 ast_translator_free_path(chan->readtrans);
1285 if (chan->writetrans)
1286 ast_translator_free_path(chan->writetrans);
1288 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1289 free_cid(&chan->cid);
1290 ast_mutex_destroy(&chan->lock_dont_use);
1291 /* Close pipes if appropriate */
1292 if ((fd = chan->alertpipe[0]) > -1)
1294 if ((fd = chan->alertpipe[1]) > -1)
1296 if ((fd = chan->timingfd) > -1)
1299 for (i = 0; i < AST_MAX_FDS; i++) {
1300 if (chan->epfd_data[i])
1301 free(chan->epfd_data[i]);
1305 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1308 /* Get rid of each of the data stores on the channel */
1309 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1310 /* Free the data store */
1311 ast_channel_datastore_free(datastore);
1312 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1314 /* loop over the variables list, freeing all data and deleting list items */
1315 /* no need to lock the list, as the channel is already locked */
1317 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1318 ast_var_delete(vardata);
1320 ast_app_group_discard(chan);
1322 /* Destroy the jitterbuffer */
1323 ast_jb_destroy(chan);
1325 ast_string_field_free_memory(chan);
1327 AST_RWLIST_UNLOCK(&channels);
1329 ast_device_state_changed_literal(name);
1332 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1334 struct ast_datastore *datastore = NULL;
1336 /* Make sure we at least have type so we can identify this */
1341 /* Allocate memory for datastore and clear it */
1342 datastore = ast_calloc(1, sizeof(*datastore));
1347 datastore->info = info;
1349 datastore->uid = ast_strdup(uid);
1354 int ast_channel_datastore_free(struct ast_datastore *datastore)
1358 /* Using the destroy function (if present) destroy the data */
1359 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1360 datastore->info->destroy(datastore->data);
1361 datastore->data = NULL;
1364 /* Free allocated UID memory */
1365 if (datastore->uid != NULL) {
1366 ast_free((void *) datastore->uid);
1367 datastore->uid = NULL;
1370 /* Finally free memory used by ourselves */
1371 ast_free(datastore);
1376 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1378 struct ast_datastore *datastore = NULL, *datastore2;
1380 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1381 if (datastore->inheritance > 0) {
1382 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1384 datastore2->data = datastore->info->duplicate(datastore->data);
1385 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1386 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1393 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1397 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1402 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1404 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1407 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1409 struct ast_datastore *datastore = NULL;
1414 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1415 if (datastore->info == info) {
1416 if (uid != NULL && datastore->uid != NULL) {
1417 if (!strcasecmp(uid, datastore->uid)) {
1418 /* Matched by type AND uid */
1422 /* Matched by type at least */
1427 AST_LIST_TRAVERSE_SAFE_END
1432 /*! Set the file descriptor on the channel */
1433 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1436 struct epoll_event ev;
1437 struct ast_epoll_data *aed = NULL;
1439 if (chan->fds[which] > -1) {
1440 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1441 aed = chan->epfd_data[which];
1444 /* If this new fd is valid, add it to the epoll */
1446 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1449 chan->epfd_data[which] = aed;
1453 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1455 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1457 /* We don't have to keep around this epoll data structure now */
1459 chan->epfd_data[which] = NULL;
1462 chan->fds[which] = fd;
1466 /*! Add a channel to an optimized waitfor */
1467 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1470 struct epoll_event ev;
1473 if (chan0->epfd == -1)
1476 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1477 for (i = 0; i < AST_MAX_FDS; i++) {
1478 if (chan1->fds[i] == -1)
1480 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1481 ev.data.ptr = chan1->epfd_data[i];
1482 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1489 /*! Delete a channel from an optimized waitfor */
1490 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1493 struct epoll_event ev;
1496 if (chan0->epfd == -1)
1499 for (i = 0; i < AST_MAX_FDS; i++) {
1500 if (chan1->fds[i] == -1)
1502 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1509 /*! \brief Softly hangup a channel, don't lock */
1510 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1512 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1513 /* Inform channel driver that we need to be hung up, if it cares */
1514 chan->_softhangup |= cause;
1515 ast_queue_frame(chan, &ast_null_frame);
1516 /* Interrupt any poll call or such */
1517 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1518 pthread_kill(chan->blocker, SIGURG);
1522 /*! \brief Softly hangup a channel, lock */
1523 int ast_softhangup(struct ast_channel *chan, int cause)
1526 ast_channel_lock(chan);
1527 res = ast_softhangup_nolock(chan, cause);
1528 ast_channel_unlock(chan);
1532 static void free_translation(struct ast_channel *clone)
1534 if (clone->writetrans)
1535 ast_translator_free_path(clone->writetrans);
1536 if (clone->readtrans)
1537 ast_translator_free_path(clone->readtrans);
1538 clone->writetrans = NULL;
1539 clone->readtrans = NULL;
1540 clone->rawwriteformat = clone->nativeformats;
1541 clone->rawreadformat = clone->nativeformats;
1544 /*! \brief Hangup a channel */
1545 int ast_hangup(struct ast_channel *chan)
1548 struct ast_cdr *cdr = NULL;
1550 /* Don't actually hang up a channel that will masquerade as someone else, or
1551 if someone is going to masquerade as us */
1552 ast_channel_lock(chan);
1554 if (chan->audiohooks) {
1555 ast_audiohook_detach_list(chan->audiohooks);
1556 chan->audiohooks = NULL;
1559 ast_autoservice_stop(chan);
1562 if (ast_do_masquerade(chan))
1563 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1567 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1568 ast_channel_unlock(chan);
1571 /* If this channel is one which will be masqueraded into something,
1572 mark it as a zombie already, so we know to free it later */
1574 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1575 ast_channel_unlock(chan);
1578 free_translation(chan);
1579 /* Close audio stream */
1581 ast_closestream(chan->stream);
1582 chan->stream = NULL;
1584 /* Close video stream */
1585 if (chan->vstream) {
1586 ast_closestream(chan->vstream);
1587 chan->vstream = NULL;
1590 sched_context_destroy(chan->sched);
1594 if (chan->generatordata) /* Clear any tone stuff remaining */
1595 if (chan->generator && chan->generator->release)
1596 chan->generator->release(chan, chan->generatordata);
1597 chan->generatordata = NULL;
1598 chan->generator = NULL;
1599 if (chan->cdr) { /* End the CDR if it hasn't already */
1600 ast_cdr_end(chan->cdr);
1604 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1605 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1606 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1607 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1610 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1611 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1612 if (chan->tech->hangup)
1613 res = chan->tech->hangup(chan);
1615 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1618 ast_channel_unlock(chan);
1619 manager_event(EVENT_FLAG_CALL, "Hangup",
1622 "CallerIDNum: %s\r\n"
1623 "CallerIDName: %s\r\n"
1625 "Cause-txt: %s\r\n",
1628 S_OR(chan->cid.cid_num, "<unknown>"),
1629 S_OR(chan->cid.cid_name, "<unknown>"),
1631 ast_cause2str(chan->hangupcause)
1633 ast_channel_free(chan);
1636 ast_cdr_detach(cdr);
1641 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1645 ast_channel_lock(chan);
1647 /* You can't answer an outbound call */
1648 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1649 ast_channel_unlock(chan);
1653 /* Stop if we're a zombie or need a soft hangup */
1654 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1655 ast_channel_unlock(chan);
1659 switch (chan->_state) {
1660 case AST_STATE_RINGING:
1661 case AST_STATE_RING:
1662 if (chan->tech->answer)
1663 res = chan->tech->answer(chan);
1664 ast_setstate(chan, AST_STATE_UP);
1665 ast_cdr_answer(chan->cdr);
1666 ast_channel_unlock(chan);
1668 ast_safe_sleep(chan, delay);
1672 ast_cdr_answer(chan->cdr);
1677 chan->visible_indication = 0;
1678 ast_channel_unlock(chan);
1683 int ast_answer(struct ast_channel *chan)
1685 return __ast_answer(chan, 500);
1688 void ast_deactivate_generator(struct ast_channel *chan)
1690 ast_channel_lock(chan);
1691 if (chan->generatordata) {
1692 if (chan->generator && chan->generator->release)
1693 chan->generator->release(chan, chan->generatordata);
1694 chan->generatordata = NULL;
1695 chan->generator = NULL;
1696 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1697 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1698 ast_settimeout(chan, 0, NULL, NULL);
1700 ast_channel_unlock(chan);
1703 static int generator_force(const void *data)
1705 /* Called if generator doesn't have data */
1708 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1709 struct ast_channel *chan = (struct ast_channel *)data;
1711 ast_channel_lock(chan);
1712 tmp = chan->generatordata;
1713 chan->generatordata = NULL;
1714 generate = chan->generator->generate;
1715 ast_channel_unlock(chan);
1717 res = generate(chan, tmp, 0, 160);
1719 chan->generatordata = tmp;
1722 ast_debug(1, "Auto-deactivating generator\n");
1723 ast_deactivate_generator(chan);
1729 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1733 ast_channel_lock(chan);
1735 if (chan->generatordata) {
1736 if (chan->generator && chan->generator->release)
1737 chan->generator->release(chan, chan->generatordata);
1738 chan->generatordata = NULL;
1742 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1747 ast_settimeout(chan, 160, generator_force, chan);
1748 chan->generator = gen;
1751 ast_channel_unlock(chan);
1756 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1757 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1760 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1764 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1766 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1767 int *exception, int *outfd, int *ms)
1769 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1770 int *exception, int *outfd, int *ms)
1773 struct timeval start = { 0 , 0 };
1774 struct pollfd *pfds = NULL;
1780 long whentohangup = 0, diff;
1781 struct ast_channel *winner = NULL;
1787 if ((sz = n * AST_MAX_FDS + nfds)) {
1788 pfds = alloca(sizeof(*pfds) * sz);
1789 fdmap = alloca(sizeof(*fdmap) * sz);
1797 /* Perform any pending masquerades */
1798 for (x = 0; x < n; x++) {
1799 ast_channel_lock(c[x]);
1800 if (c[x]->masq && ast_do_masquerade(c[x])) {
1801 ast_log(LOG_WARNING, "Masquerade failed\n");
1803 ast_channel_unlock(c[x]);
1806 if (c[x]->whentohangup) {
1809 diff = c[x]->whentohangup - now;
1811 /* Should already be hungup */
1812 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1813 ast_channel_unlock(c[x]);
1816 if (!whentohangup || (diff < whentohangup))
1817 whentohangup = diff;
1819 ast_channel_unlock(c[x]);
1821 /* Wait full interval */
1824 rms = whentohangup * 1000; /* timeout in milliseconds */
1825 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1829 * Build the pollfd array, putting the channels' fds first,
1830 * followed by individual fds. Order is important because
1831 * individual fd's must have priority over channel fds.
1834 for (x = 0; x < n; x++) {
1835 for (y = 0; y < AST_MAX_FDS; y++) {
1836 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1837 fdmap[max].chan = x; /* channel x is linked to this pfds */
1838 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1840 CHECK_BLOCKING(c[x]);
1842 /* Add the individual fds */
1843 for (x = 0; x < nfds; x++) {
1844 fdmap[max].chan = -1;
1845 max += ast_add_fd(&pfds[max], fds[x]);
1849 start = ast_tvnow();
1851 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1856 res = poll(pfds, max, kbrms);
1859 } while (!res && (rms > 0));
1861 res = poll(pfds, max, rms);
1863 for (x = 0; x < n; x++)
1864 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1865 if (res < 0) { /* Simulate a timeout if we were interrupted */
1870 if (whentohangup) { /* if we have a timeout, check who expired */
1872 for (x = 0; x < n; x++) {
1873 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1874 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1880 if (res == 0) { /* no fd ready, reset timeout and done */
1881 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1885 * Then check if any channel or fd has a pending event.
1886 * Remember to check channels first and fds last, as they
1887 * must have priority on setting 'winner'
1889 for (x = 0; x < max; x++) {
1890 res = pfds[x].revents;
1893 if (fdmap[x].chan >= 0) { /* this is a channel */
1894 winner = c[fdmap[x].chan]; /* override previous winners */
1896 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1898 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1899 winner->fdno = fdmap[x].fdno;
1900 } else { /* this is an fd */
1902 *outfd = pfds[x].fd;
1904 *exception = (res & POLLPRI) ? -1 : 0;
1909 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1917 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1919 struct timeval start = { 0 , 0 };
1921 struct epoll_event ev[1];
1922 long whentohangup = 0, rms = *ms;
1924 struct ast_channel *winner = NULL;
1925 struct ast_epoll_data *aed = NULL;
1927 ast_channel_lock(chan);
1929 /* See if this channel needs to be masqueraded */
1930 if (chan->masq && ast_do_masquerade(chan)) {
1931 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1933 ast_channel_unlock(chan);
1937 /* Figure out their timeout */
1938 if (chan->whentohangup) {
1940 if ((whentohangup = chan->whentohangup - now) < 1) {
1941 /* They should already be hungup! */
1942 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1943 ast_channel_unlock(chan);
1946 /* If this value is smaller then the current one... make it priority */
1947 whentohangup *= 1000;
1948 if (rms > whentohangup)
1952 ast_channel_unlock(chan);
1954 /* Time to make this channel block... */
1955 CHECK_BLOCKING(chan);
1958 start = ast_tvnow();
1960 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1961 res = epoll_wait(chan->epfd, ev, 1, rms);
1964 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1966 /* Simulate a timeout if we were interrupted */
1973 /* If this channel has a timeout see if it expired */
1974 if (chan->whentohangup) {
1976 if (now >= chan->whentohangup) {
1977 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1982 /* No fd ready, reset timeout and be done for now */
1988 /* See what events are pending */
1989 aed = ev[0].data.ptr;
1990 chan->fdno = aed->which;
1991 if (ev[0].events & EPOLLPRI)
1992 ast_set_flag(chan, AST_FLAG_EXCEPTION);
1994 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1997 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2005 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2007 struct timeval start = { 0 , 0 };
2009 struct epoll_event ev[25] = { { 0, } };
2010 long whentohangup = 0, diff, rms = *ms;
2012 struct ast_channel *winner = NULL;
2014 for (i = 0; i < n; i++) {
2015 ast_channel_lock(c[i]);
2016 if (c[i]->masq && ast_do_masquerade(c[i])) {
2017 ast_log(LOG_WARNING, "Masquerade failed\n");
2019 ast_channel_unlock(c[i]);
2022 if (c[i]->whentohangup) {
2025 if ((diff = c[i]->whentohangup - now) < 1) {
2026 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2027 ast_channel_unlock(c[i]);
2030 if (!whentohangup || (diff < whentohangup))
2031 whentohangup = diff;
2033 ast_channel_unlock(c[i]);
2034 CHECK_BLOCKING(c[i]);
2039 rms = whentohangup * 1000;
2040 if (*ms >= 0 && *ms < rms)
2045 start = ast_tvnow();
2047 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2049 for (i = 0; i < n; i++)
2050 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2060 for (i = 0; i < n; i++) {
2061 if (c[i]->whentohangup && now >= c[i]->whentohangup) {
2062 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2074 for (i = 0; i < res; i++) {
2075 struct ast_epoll_data *aed = ev[i].data.ptr;
2077 if (!ev[i].events || !aed)
2081 if (ev[i].events & EPOLLPRI)
2082 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2084 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2085 winner->fdno = aed->which;
2089 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2097 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2098 int *exception, int *outfd, int *ms)
2100 /* Clear all provided values in one place. */
2106 /* If no epoll file descriptor is available resort to classic nandfds */
2107 if (!n || nfds || c[0]->epfd == -1)
2108 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2109 else if (!nfds && n == 1)
2110 return ast_waitfor_nandfds_simple(c[0], ms);
2112 return ast_waitfor_nandfds_complex(c, n, ms);
2116 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2118 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2121 int ast_waitfor(struct ast_channel *c, int ms)
2123 int oldms = ms; /* -1 if no timeout */
2125 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2126 if ((ms < 0) && (oldms < 0))
2131 /* XXX never to be called with ms = -1 */
2132 int ast_waitfordigit(struct ast_channel *c, int ms)
2134 return ast_waitfordigit_full(c, ms, -1, -1);
2137 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
2141 if (c->timingfd > -1) {
2146 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
2147 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
2148 c->timingfunc = func;
2149 c->timingdata = data;
2155 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2157 /* Stop if we're a zombie or need a soft hangup */
2158 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2161 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2162 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2164 /* Wait for a digit, no more than ms milliseconds total. */
2167 struct ast_channel *rchan;
2171 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2173 if (!rchan && outfd < 0 && ms) {
2174 if (errno == 0 || errno == EINTR)
2176 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2177 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2179 } else if (outfd > -1) {
2180 /* The FD we were watching has something waiting */
2181 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2182 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2186 struct ast_frame *f = ast_read(c);
2190 switch (f->frametype) {
2191 case AST_FRAME_DTMF_BEGIN:
2193 case AST_FRAME_DTMF_END:
2196 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2198 case AST_FRAME_CONTROL:
2199 switch (f->subclass) {
2200 case AST_CONTROL_HANGUP:
2202 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2204 case AST_CONTROL_RINGING:
2205 case AST_CONTROL_ANSWER:
2209 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2213 case AST_FRAME_VOICE:
2214 /* Write audio if appropriate */
2216 write(audiofd, f->data, f->datalen);
2225 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2227 return 0; /* Time is up */
2230 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2232 manager_event(EVENT_FLAG_DTMF,
2240 chan->name, chan->uniqueid, digit, direction, begin, end);
2243 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2245 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2246 void *tmp = chan->generatordata;
2249 if (chan->timingfunc) {
2250 if (option_debug > 1)
2251 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2252 ast_settimeout(chan, 0, NULL, NULL);
2255 chan->generatordata = NULL; /* reset, to let writes go through */
2256 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2257 chan->generatordata = tmp;
2259 if (option_debug > 1)
2260 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2261 ast_deactivate_generator(chan);
2264 } else if (f->frametype == AST_FRAME_CNG) {
2265 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2266 if (option_debug > 1)
2267 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2268 ast_settimeout(chan, 160, generator_force, chan);
2273 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2275 struct ast_frame *f = NULL; /* the return value */
2280 /* this function is very long so make sure there is only one return
2281 * point at the end (there are only two exceptions to this).
2283 while(ast_channel_trylock(chan)) {
2285 /*cannot goto done since the channel is not locked*/
2286 return &ast_null_frame;
2291 if (ast_do_masquerade(chan))
2292 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2294 f = &ast_null_frame;
2298 /* Stop if we're a zombie or need a soft hangup */
2299 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2300 if (chan->generator)
2301 ast_deactivate_generator(chan);
2304 prestate = chan->_state;
2306 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2307 !ast_strlen_zero(chan->dtmfq) &&
2308 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2309 /* We have DTMF that has been deferred. Return it now */
2310 chan->dtmff.subclass = chan->dtmfq[0];
2311 /* Drop first digit from the buffer */
2312 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2314 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2315 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2316 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2318 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);
2319 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2320 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2321 chan->emulate_dtmf_digit = f->subclass;
2322 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2324 chan->dtmf_tv = ast_tvnow();
2328 /* Read and ignore anything on the alertpipe, but read only
2329 one sizeof(blah) per frame that we send from it */
2330 if (chan->alertpipe[0] > -1)
2331 read(chan->alertpipe[0], &blah, sizeof(blah));
2334 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2337 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2339 /* IF we can't get event, assume it's an expired as-per the old interface */
2340 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2342 blah = ZT_EVENT_TIMER_EXPIRED;
2344 if (blah == ZT_EVENT_TIMER_PING) {
2345 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2346 /* Acknowledge PONG unless we need it again */
2347 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2348 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2351 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2352 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2353 if (chan->timingfunc) {
2354 /* save a copy of func/data before unlocking the channel */
2355 int (*func)(const void *) = chan->timingfunc;
2356 void *data = chan->timingdata;
2357 ast_channel_unlock(chan);
2361 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2362 chan->timingdata = NULL;
2363 ast_channel_unlock(chan);
2365 /* cannot 'goto done' because the channel is already unlocked */
2366 return &ast_null_frame;
2368 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2371 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2372 /* if the AST_GENERATOR_FD is set, call the generator with args
2373 * set to -1 so it can do whatever it needs to.
2375 void *tmp = chan->generatordata;
2376 chan->generatordata = NULL; /* reset to let ast_write get through */
2377 chan->generator->generate(chan, tmp, -1, -1);
2378 chan->generatordata = tmp;
2379 f = &ast_null_frame;
2383 /* Check for pending read queue */
2384 if (!AST_LIST_EMPTY(&chan->readq)) {
2385 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2386 /* Interpret hangup and return NULL */
2387 /* XXX why not the same for frames from the channel ? */
2388 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2393 chan->blocker = pthread_self();
2394 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2395 if (chan->tech->exception)
2396 f = chan->tech->exception(chan);
2398 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2399 f = &ast_null_frame;
2401 /* Clear the exception flag */
2402 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2403 } else if (chan->tech->read)
2404 f = chan->tech->read(chan);
2406 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2410 /* if the channel driver returned more than one frame, stuff the excess
2411 into the readq for the next ast_read call (note that we can safely assume
2412 that the readq is empty, because otherwise we would not have called into
2413 the channel driver and f would be only a single frame)
2415 if (AST_LIST_NEXT(f, frame_list)) {
2416 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2417 AST_LIST_NEXT(f, frame_list) = NULL;
2420 switch (f->frametype) {
2421 case AST_FRAME_CONTROL:
2422 if (f->subclass == AST_CONTROL_ANSWER) {
2423 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2424 ast_debug(1, "Ignoring answer on an inbound call!\n");
2426 f = &ast_null_frame;
2427 } else if (prestate == AST_STATE_UP) {
2428 ast_debug(1, "Dropping duplicate answer!\n");
2430 f = &ast_null_frame;
2432 /* Answer the CDR */
2433 ast_setstate(chan, AST_STATE_UP);
2434 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2435 to keep from throwing off the basic order of the universe,
2436 we will try to keep this cdr from getting posted. */
2437 chan->cdr = ast_cdr_alloc();
2438 ast_cdr_init(chan->cdr, chan);
2439 ast_cdr_start(chan->cdr);
2442 ast_cdr_answer(chan->cdr);
2446 case AST_FRAME_DTMF_END:
2447 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2448 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2449 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2450 * However, only let emulation be forced if the other end cares about BEGIN frames */
2451 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2452 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2453 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2454 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2455 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2457 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2459 f = &ast_null_frame;
2460 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2461 if (!ast_tvzero(chan->dtmf_tv) &&
2462 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2463 /* If it hasn't been long enough, defer this digit */
2464 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2465 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2466 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2468 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2470 f = &ast_null_frame;
2472 /* There was no begin, turn this into a begin and send the end later */
2473 f->frametype = AST_FRAME_DTMF_BEGIN;
2474 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2475 chan->emulate_dtmf_digit = f->subclass;
2476 chan->dtmf_tv = ast_tvnow();
2478 if (f->len > AST_MIN_DTMF_DURATION)
2479 chan->emulate_dtmf_duration = f->len;
2481 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2483 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2484 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2486 if (chan->audiohooks) {
2487 struct ast_frame *old_frame = f;
2489 * \todo XXX It is possible to write a digit to the audiohook twice
2490 * if the digit was originally read while the channel was in autoservice. */
2491 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2493 ast_frfree(old_frame);
2496 struct timeval now = ast_tvnow();
2497 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2498 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2499 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2501 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2502 } else if (!f->len) {
2503 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2504 f->len = AST_MIN_DTMF_DURATION;
2506 if (f->len < AST_MIN_DTMF_DURATION) {
2507 ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass, f->len, AST_MIN_DTMF_DURATION, chan->name);
2508 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2509 chan->emulate_dtmf_digit = f->subclass;
2510 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2512 f = &ast_null_frame;
2514 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2515 chan->dtmf_tv = now;
2517 if (chan->audiohooks) {
2518 struct ast_frame *old_frame = f;
2519 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2521 ast_frfree(old_frame);
2525 case AST_FRAME_DTMF_BEGIN:
2526 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2527 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2528 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2529 (!ast_tvzero(chan->dtmf_tv) &&
2530 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2531 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2533 f = &ast_null_frame;
2535 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2536 chan->dtmf_tv = ast_tvnow();
2537 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2540 case AST_FRAME_NULL:
2541 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2542 * is reached , because we want to make sure we pass at least one
2543 * voice frame through before starting the next digit, to ensure a gap
2544 * between DTMF digits. */
2545 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2546 struct timeval now = ast_tvnow();
2547 if (!chan->emulate_dtmf_duration) {
2548 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2549 chan->emulate_dtmf_digit = 0;
2550 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2551 chan->emulate_dtmf_duration = 0;
2554 f->frametype = AST_FRAME_DTMF_END;
2555 f->subclass = chan->emulate_dtmf_digit;
2556 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2557 chan->dtmf_tv = now;
2558 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2559 chan->emulate_dtmf_digit = 0;
2560 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2564 case AST_FRAME_VOICE:
2565 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2566 * is reached , because we want to make sure we pass at least one
2567 * voice frame through before starting the next digit, to ensure a gap
2568 * between DTMF digits. */
2569 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2570 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2571 chan->emulate_dtmf_digit = 0;
2574 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2576 ast_read_generator_actions(chan, f);
2578 f = &ast_null_frame;
2581 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2582 struct timeval now = ast_tvnow();
2583 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2584 chan->emulate_dtmf_duration = 0;
2587 f->frametype = AST_FRAME_DTMF_END;
2588 f->subclass = chan->emulate_dtmf_digit;
2589 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2590 chan->dtmf_tv = now;
2591 if (chan->audiohooks) {
2592 struct ast_frame *old_frame = f;
2593 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2595 ast_frfree(old_frame);
2597 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2599 /* Drop voice frames while we're still in the middle of the digit */
2601 f = &ast_null_frame;
2603 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2604 /* This frame can't be from the current native formats -- drop it on the
2606 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2607 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2609 f = &ast_null_frame;
2610 } else if ((f->frametype == AST_FRAME_VOICE)) {
2611 /* Send frame to audiohooks if present */
2612 if (chan->audiohooks) {
2613 struct ast_frame *old_frame = f;
2614 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2616 ast_frfree(old_frame);
2618 if (chan->monitor && chan->monitor->read_stream ) {
2619 /* XXX what does this do ? */
2620 #ifndef MONITOR_CONSTANT_DELAY
2621 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2623 jump = chan->outsmpl - chan->insmpl;
2624 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2625 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2626 chan->insmpl += jump + f->samples;
2628 chan->insmpl+= f->samples;
2630 int jump = chan->outsmpl - chan->insmpl;
2631 if (jump - MONITOR_DELAY >= 0) {
2632 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2633 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2634 chan->insmpl += jump;
2636 chan->insmpl += f->samples;
2638 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2639 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2640 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2644 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2645 f = &ast_null_frame;
2647 /* Run generator sitting on the line if timing device not available
2648 * and synchronous generation of outgoing frames is necessary */
2649 ast_read_generator_actions(chan, f);
2652 /* Just pass it on! */
2656 /* Make sure we always return NULL in the future */
2657 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2658 if (chan->generator)
2659 ast_deactivate_generator(chan);
2660 /* End the CDR if appropriate */
2662 ast_cdr_end(chan->cdr);
2665 /* High bit prints debugging */
2666 if (chan->fin & DEBUGCHAN_FLAG)
2667 ast_frame_dump(chan->name, f, "<<");
2668 chan->fin = FRAMECOUNT_INC(chan->fin);
2671 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2672 chan->generator->digit(chan, f->subclass);
2674 ast_channel_unlock(chan);
2678 int ast_internal_timing_enabled(struct ast_channel *chan)
2680 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2681 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2685 struct ast_frame *ast_read(struct ast_channel *chan)
2687 return __ast_read(chan, 0);
2690 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2692 return __ast_read(chan, 1);
2695 int ast_indicate(struct ast_channel *chan, int condition)
2697 return ast_indicate_data(chan, condition, NULL, 0);
2700 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2704 ast_channel_lock(chan);
2705 /* Stop if we're a zombie or need a soft hangup */
2706 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2707 ast_channel_unlock(chan);
2710 if (chan->tech->indicate)
2711 res = chan->tech->indicate(chan, condition, data, datalen);
2712 ast_channel_unlock(chan);
2713 if (!chan->tech->indicate || res) {
2715 * Device does not support (that) indication, lets fake
2716 * it by doing our own tone generation. (PM2002)
2719 ast_playtones_stop(chan);
2721 const struct ind_tone_zone_sound *ts = NULL;
2722 switch (condition) {
2723 case AST_CONTROL_RINGING:
2724 ts = ast_get_indication_tone(chan->zone, "ring");
2726 case AST_CONTROL_BUSY:
2727 ts = ast_get_indication_tone(chan->zone, "busy");
2729 case AST_CONTROL_CONGESTION:
2730 ts = ast_get_indication_tone(chan->zone, "congestion");
2733 if (ts && ts->data[0]) {
2734 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2735 ast_playtones_start(chan,0,ts->data, 1);
2737 chan->visible_indication = condition;
2738 } else if (condition == AST_CONTROL_PROGRESS) {
2739 /* ast_playtones_stop(chan); */
2740 } else if (condition == AST_CONTROL_PROCEEDING) {
2741 /* Do nothing, really */
2742 } else if (condition == AST_CONTROL_HOLD) {
2743 /* Do nothing.... */
2744 } else if (condition == AST_CONTROL_UNHOLD) {
2745 /* Do nothing.... */
2746 } else if (condition == AST_CONTROL_VIDUPDATE) {
2747 /* Do nothing.... */
2748 } else if (condition == AST_CONTROL_SRCUPDATE) {
2752 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2757 chan->visible_indication = condition;
2762 int ast_recvchar(struct ast_channel *chan, int timeout)
2765 char *buf = ast_recvtext(chan, timeout);
2767 return -1; /* error or timeout */
2768 c = *(unsigned char *)buf;
2773 char *ast_recvtext(struct ast_channel *chan, int timeout)
2779 struct ast_frame *f;
2780 if (ast_check_hangup(chan))
2782 res = ast_waitfor(chan, timeout);
2783 if (res <= 0) /* timeout or error */
2785 timeout = res; /* update timeout */
2788 break; /* no frame */
2789 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2790 done = 1; /* force a break */
2791 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2792 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2800 int ast_sendtext(struct ast_channel *chan, const char *text)
2803 /* Stop if we're a zombie or need a soft hangup */
2804 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2806 CHECK_BLOCKING(chan);
2807 if (chan->tech->send_text)
2808 res = chan->tech->send_text(chan, text);
2809 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2813 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2815 /* Device does not support DTMF tones, lets fake
2816 * it by doing our own generation. */
2817 static const char* dtmf_tones[] = {
2836 if (!chan->tech->send_digit_begin)
2839 if (!chan->tech->send_digit_begin(chan, digit))
2842 if (digit >= '0' && digit <='9')
2843 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2844 else if (digit >= 'A' && digit <= 'D')
2845 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2846 else if (digit == '*')
2847 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2848 else if (digit == '#')
2849 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2852 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2858 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2862 if (chan->tech->send_digit_end)
2863 res = chan->tech->send_digit_end(chan, digit, duration);
2865 if (res && chan->generator)
2866 ast_playtones_stop(chan);
2871 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2873 if (chan->tech->send_digit_begin) {
2874 ast_senddigit_begin(chan, digit);
2875 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2878 return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2881 int ast_prod(struct ast_channel *chan)
2883 struct ast_frame a = { AST_FRAME_VOICE };
2886 /* Send an empty audio frame to get things moving */
2887 if (chan->_state != AST_STATE_UP) {
2888 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2889 a.subclass = chan->rawwriteformat;
2890 a.data = nothing + AST_FRIENDLY_OFFSET;
2892 if (ast_write(chan, &a))
2893 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2898 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2901 if (!chan->tech->write_video)
2903 res = ast_write(chan, fr);
2909 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2912 struct ast_frame *f = NULL, *f2 = NULL;
2915 /*Deadlock avoidance*/
2916 while(ast_channel_trylock(chan)) {
2917 /*cannot goto done since the channel is not locked*/
2919 ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
2924 /* Stop if we're a zombie or need a soft hangup */
2925 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2928 /* Handle any pending masquerades */
2929 if (chan->masq && ast_do_masquerade(chan)) {
2930 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2934 res = 0; /* XXX explain, why 0 ? */
2937 if (chan->generatordata) {
2938 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2939 ast_deactivate_generator(chan);
2941 if (fr->frametype == AST_FRAME_DTMF_END) {
2942 /* There is a generator running while we're in the middle of a digit.
2943 * It's probably inband DTMF, so go ahead and pass it so it can
2944 * stop the generator */
2945 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2946 ast_channel_unlock(chan);
2947 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2948 ast_channel_lock(chan);
2949 CHECK_BLOCKING(chan);
2950 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2951 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2952 res = (chan->tech->indicate == NULL) ? 0 :
2953 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2955 res = 0; /* XXX explain, why 0 ? */
2959 /* High bit prints debugging */
2960 if (chan->fout & DEBUGCHAN_FLAG)
2961 ast_frame_dump(chan->name, fr, ">>");
2962 CHECK_BLOCKING(chan);
2963 switch (fr->frametype) {
2964 case AST_FRAME_CONTROL:
2965 res = (chan->tech->indicate == NULL) ? 0 :
2966 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2968 case AST_FRAME_DTMF_BEGIN:
2969 if (chan->audiohooks) {
2970 struct ast_frame *old_frame = fr;
2971 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2972 if (old_frame != fr)
2975 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2976 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2977 ast_channel_unlock(chan);
2978 res = ast_senddigit_begin(chan, fr->subclass);
2979 ast_channel_lock(chan);
2980 CHECK_BLOCKING(chan);
2982 case AST_FRAME_DTMF_END:
2983 if (chan->audiohooks) {
2984 struct ast_frame *old_frame = fr;
2985 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2986 if (old_frame != fr)
2989 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2990 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2991 ast_channel_unlock(chan);
2992 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2993 ast_channel_lock(chan);
2994 CHECK_BLOCKING(chan);
2996 case AST_FRAME_TEXT:
2997 if (fr->subclass == AST_FORMAT_T140) {
2998 res = (chan->tech->write_text == NULL) ? 0 :
2999 chan->tech->write_text(chan, fr);
3001 res = (chan->tech->send_text == NULL) ? 0 :
3002 chan->tech->send_text(chan, (char *) fr->data);
3005 case AST_FRAME_HTML:
3006 res = (chan->tech->send_html == NULL) ? 0 :
3007 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
3009 case AST_FRAME_VIDEO:
3010 /* XXX Handle translation of video codecs one day XXX */
3011 res = (chan->tech->write_video == NULL) ? 0 :
3012 chan->tech->write_video(chan, fr);
3014 case AST_FRAME_MODEM:
3015 res = (chan->tech->write == NULL) ? 0 :
3016 chan->tech->write(chan, fr);
3018 case AST_FRAME_VOICE:
3019 if (chan->tech->write == NULL)
3020 break; /*! \todo XXX should return 0 maybe ? */
3022 /* If audiohooks are present, write the frame out */
3023 if (chan->audiohooks) {
3024 struct ast_frame *old_frame = fr;
3025 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3026 if (old_frame != fr)
3030 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3031 if (fr->subclass == chan->rawwriteformat)
3034 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
3041 /* If Monitor is running on this channel, then we have to write frames out there too */
3042 if (chan->monitor && chan->monitor->write_stream) {
3043 /* XXX must explain this code */
3044 #ifndef MONITOR_CONSTANT_DELAY
3045 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
3047 jump = chan->insmpl - chan->outsmpl;
3048 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
3049 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3050 chan->outsmpl += jump + f->samples;
3052 chan->outsmpl += f->samples;
3054 int jump = chan->insmpl - chan->outsmpl;
3055 if (jump - MONITOR_DELAY >= 0) {
3056 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3057 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3058 chan->outsmpl += jump;
3060 chan->outsmpl += f->samples;
3062 if (chan->monitor->state == AST_MONITOR_RUNNING) {
3063 if (ast_writestream(chan->monitor->write_stream, f) < 0)
3064 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
3069 res = chan->tech->write(chan,f);
3073 case AST_FRAME_NULL:
3079 /* At this point, fr is the incoming frame and f is NULL. Channels do
3080 * not expect to get NULL as a frame pointer and will segfault. Hence,
3081 * we output the original frame passed in. */
3082 res = chan->tech->write(chan, fr);
3090 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3091 /* Consider a write failure to force a soft hangup */
3093 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3095 chan->fout = FRAMECOUNT_INC(chan->fout);
3098 ast_channel_unlock(chan);
3102 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
3103 struct ast_trans_pvt **trans, const int direction)
3108 /* Make sure we only consider audio */
3109 fmt &= AST_FORMAT_AUDIO_MASK;
3111 native = chan->nativeformats;
3113 if (!fmt || !native) /* No audio requested */
3114 return 0; /* Let's try a call without any sounds (video, text) */
3116 /* Find a translation path from the native format to one of the desired formats */
3119 res = ast_translator_best_choice(&fmt, &native);
3122 res = ast_translator_best_choice(&native, &fmt);
3125 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
3126 ast_getformatname(native), ast_getformatname(fmt));
3130 /* Now we have a good choice for both. */
3131 ast_channel_lock(chan);
3133 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
3134 /* the channel is already in these formats, so nothing to do */
3135 ast_channel_unlock(chan);
3139 *rawformat = native;
3140 /* User perspective is fmt */
3142 /* Free any read translation we have right now */
3144 ast_translator_free_path(*trans);
3145 /* Build a translation path from the raw format to the desired format */
3148 *trans = ast_translator_build_path(*format, *rawformat);
3151 *trans = ast_translator_build_path(*rawformat, *format);
3152 ast_channel_unlock(chan);
3153 ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
3154 direction ? "write" : "read", ast_getformatname(fmt));
3158 int ast_set_read_format(struct ast_channel *chan, int fmt)
3160 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
3161 &chan->readtrans, 0);
3164 int ast_set_write_format(struct ast_channel *chan, int fmt)
3166 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
3167 &chan->writetrans, 1);
3170 const char *ast_channel_reason2str(int reason)
3172 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
3175 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
3176 case AST_CONTROL_HANGUP:
3178 case AST_CONTROL_RING:
3179 return "Local Ring";
3180 case AST_CONTROL_RINGING:
3181 return "Remote end Ringing";
3182 case AST_CONTROL_ANSWER:
3183 return "Remote end has Answered";
3184 case AST_CONTROL_BUSY:
3185 return "Remote end is Busy";
3186 case AST_CONTROL_CONGESTION:
3187 return "Congestion (circuits busy)";
3189 return "Unknown Reason!!";
3193 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)
3197 struct ast_channel *chan;
3199 int last_subclass = 0;
3204 outstate = &dummy_outstate; /* make outstate always a valid pointer */
3206 chan = ast_request(type, format, data, &cause);
3208 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3209 /* compute error and return */
3210 if (cause == AST_CAUSE_BUSY)
3211 *outstate = AST_CONTROL_BUSY;
3212 else if (cause == AST_CAUSE_CONGESTION)
3213 *outstate = AST_CONTROL_CONGESTION;
3219 ast_set_variables(chan, oh->vars);
3220 /* XXX why is this necessary, for the parent_channel perhaps ? */
3221 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
3222 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
3223 if (oh->parent_channel) {
3224 ast_channel_inherit_variables(oh->parent_channel, chan);
3225 ast_channel_datastore_inherit(oh->parent_channel, chan);
3228 ast_cdr_setaccount(chan, oh->account);
3230 ast_set_callerid(chan, cid_num, cid_name, cid_num);
3234 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
3235 to keep from throwing off the basic order of the universe,
3236 we will try to keep this cdr from getting posted. */
3237 chan->cdr = ast_cdr_alloc();
3238 ast_cdr_init(chan->cdr, chan);
3239 ast_cdr_start(chan->cdr);
3241 if (ast_call(chan, data, 0)) { /* ast_call failed... */
3242 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3244 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
3245 while (timeout && chan->_state != AST_STATE_UP) {
3246 struct ast_frame *f;
3247 res = ast_waitfor(chan, timeout);
3248 if (res <= 0) /* error, timeout, or done */
3254 *outstate = AST_CONTROL_HANGUP;
3258 if (f->frametype == AST_FRAME_CONTROL) {
3259 switch (f->subclass) {
3260 case AST_CONTROL_RINGING: /* record but keep going */
3261 *outstate = f->subclass;
3264 case AST_CONTROL_BUSY:
3265 case AST_CONTROL_CONGESTION:
3266 case AST_CONTROL_ANSWER:
3267 *outstate = f->subclass;
3268 timeout = 0; /* trick to force exit from the while() */
3272 case AST_CONTROL_PROGRESS:
3273 case AST_CONTROL_PROCEEDING:
3274 case AST_CONTROL_HOLD:
3275 case AST_CONTROL_UNHOLD:
3276 case AST_CONTROL_VIDUPDATE:
3277 case AST_CONTROL_SRCUPDATE:
3278 case -1: /* Ignore -- just stopping indications */
3282 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3284 last_subclass = f->subclass;
3292 if (!ast_strlen_zero(oh->context))
3293 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3294 if (!ast_strlen_zero(oh->exten))
3295 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3297 chan->priority = oh->priority;
3299 if (chan->_state == AST_STATE_UP)
3300 *outstate = AST_CONTROL_ANSWER;
3303 if ( AST_CONTROL_RINGING == last_subclass )
3304 chan->hangupcause = AST_CAUSE_NO_ANSWER;
3305 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3306 ast_cdr_init(chan->cdr, chan);
3309 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3310 ast_cdr_setapp(chan->cdr,"Dial",tmp);
3311 ast_cdr_update(chan);
3312 ast_cdr_start(chan->cdr);
3313 ast_cdr_end(chan->cdr);
3314 /* If the cause wasn't handled properly */
3315 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3316 ast_cdr_failed(chan->cdr);
3324 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3326 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3329 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3331 struct chanlist *chan;
3332 struct ast_channel *c;
3337 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3338 int textformat = format & AST_FORMAT_TEXT_MASK;
3342 *cause = AST_CAUSE_NOTDEFINED;
3344 if (AST_RWLIST_RDLOCK(&channels)) {
3345 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3349 AST_LIST_TRAVERSE(&backends, chan, list) {
3350 if (strcasecmp(type, chan->tech->type))
3353 capabilities = chan->tech->capabilities;
3354 fmt = format & AST_FORMAT_AUDIO_MASK;
3356 /* We have audio - is it possible to connect the various calls to each other?
3357 (Avoid this check for calls without audio, like text+video calls)
3359 res = ast_translator_best_choice(&fmt, &capabilities);
3361 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type, chan->tech->capabilities, format);
3362 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3363 AST_RWLIST_UNLOCK(&channels);
3367 AST_RWLIST_UNLOCK(&channels);
3368 if (!chan->tech->requester)
3371 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
3374 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3378 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3379 *cause = AST_CAUSE_NOSUCHDRIVER;
3380 AST_RWLIST_UNLOCK(&channels);
3385 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3387 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3388 If the remote end does not answer within the timeout, then do NOT hang up, but
3391 /* Stop if we're a zombie or need a soft hangup */
3392 ast_channel_lock(chan);
3393 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3394 if (chan->tech->call)
3395 res = chan->tech->call(chan, addr, timeout);
3396 ast_set_flag(chan, AST_FLAG_OUTGOING);
3398 ast_channel_unlock(chan);
3403 \brief Transfer a call to dest, if the channel supports transfer
3407 \arg the manager interface
3409 int ast_transfer(struct ast_channel *chan, char *dest)
3413 /* Stop if we're a zombie or need a soft hangup */
3414 ast_channel_lock(chan);
3415 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3416 if (chan->tech->transfer) {
3417 res = chan->tech->transfer(chan, dest);
3423 ast_channel_unlock(chan);
3427 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3429 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3432 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3434 int pos = 0; /* index in the buffer where we accumulate digits */
3437 /* Stop if we're a zombie or need a soft hangup */
3438 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3445 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3449 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3451 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3463 if (!strchr(enders, d))
3465 if (strchr(enders, d) || (pos >= len)) {
3475 int ast_channel_supports_html(struct ast_channel *chan)
3477 return (chan->tech->send_html) ? 1 : 0;
3480 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3482 if (chan->tech->send_html)
3483 return chan->tech->send_html(chan, subclass, data, datalen);
3487 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3489 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3492 /*! \brief Set up translation from one channel to another */
3493 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3498 if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
3499 /* Already compatible! Moving on ... */
3503 /* Set up translation from the 'from' channel to the 'to' channel */
3504 src = from->nativeformats;
3505 dst = to->nativeformats;
3507 /* If there's no audio in this call, don't bother with trying to find a translation path */
3508 if ((src & AST_FORMAT_AUDIO_MASK) == 0 || (dst & AST_FORMAT_AUDIO_MASK) == 0)
3511 if (ast_translator_best_choice(&dst, &src) < 0) {
3512 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3516 /* if the best path is not 'pass through', then
3517 transcoding is needed; if desired, force transcode path
3518 to use SLINEAR between channels, but only if there is
3519 no direct conversion available */
3520 if ((src != dst) && ast_opt_transcode_via_slin &&
3521 (ast_translate_path_steps(dst, src) != 1))
3522 dst = AST_FORMAT_SLINEAR;
3523 if (ast_set_read_format(from, dst) < 0) {
3524 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3527 if (ast_set_write_format(to, dst) < 0) {
3528 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3534 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3536 /* Some callers do not check return code, and we must try to set all call legs correctly */
3539 /* Set up translation from the chan to the peer */
3540 rc = ast_channel_make_compatible_helper(chan, peer);
3545 /* Set up translation from the peer to the chan */
3546 rc = ast_channel_make_compatible_helper(peer, chan);
3551 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3554 struct ast_channel *final_orig, *final_clone, *base;