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 */
38 #include "asterisk/pbx.h"
39 #include "asterisk/frame.h"
40 #include "asterisk/sched.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/musiconhold.h"
43 #include "asterisk/say.h"
44 #include "asterisk/file.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/translate.h"
47 #include "asterisk/manager.h"
48 #include "asterisk/chanvars.h"
49 #include "asterisk/linkedlists.h"
50 #include "asterisk/indications.h"
51 #include "asterisk/monitor.h"
52 #include "asterisk/causes.h"
53 #include "asterisk/callerid.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/lock.h"
56 #include "asterisk/app.h"
57 #include "asterisk/transcap.h"
58 #include "asterisk/devicestate.h"
59 #include "asterisk/sha1.h"
60 #include "asterisk/threadstorage.h"
61 #include "asterisk/slinfactory.h"
62 #include "asterisk/audiohook.h"
63 #include "asterisk/timing.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_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
435 traced = ast_calloc(1, sizeof(*traced));
437 ast_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 (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
469 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* 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);
494 AST_RWLIST_UNLOCK(&channels);
498 /*! \brief returns number of active/allocated channels */
499 int ast_active_channels(void)
501 struct ast_channel *c;
503 AST_RWLIST_RDLOCK(&channels);
504 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
506 AST_RWLIST_UNLOCK(&channels);
510 /*! \brief Cancel a shutdown in progress */
511 void ast_cancel_shutdown(void)
516 /*! \brief Returns non-zero if Asterisk is being shut down */
517 int ast_shutting_down(void)
519 return shutting_down;
522 /*! \brief Set when to hangup channel */
523 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
525 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
526 ast_queue_frame(chan, &ast_null_frame);
530 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
532 struct timeval when = { offset, };
533 ast_channel_setwhentohangup_tv(chan, when);
536 /*! \brief Compare a offset with when to hangup channel */
537 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
539 struct timeval whentohangup;
541 if (ast_tvzero(chan->whentohangup))
542 return ast_tvzero(offset) ? 0 : -1;
544 if (ast_tvzero(offset))
547 whentohangup = ast_tvadd(offset, ast_tvnow());
549 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
552 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
554 struct timeval when = { offset, };
555 return ast_channel_cmpwhentohangup_tv(chan, when);
558 /*! \brief Register a new telephony channel in Asterisk */
559 int ast_channel_register(const struct ast_channel_tech *tech)
561 struct chanlist *chan;
563 AST_RWLIST_WRLOCK(&channels);
565 AST_LIST_TRAVERSE(&backends, chan, list) {
566 if (!strcasecmp(tech->type, chan->tech->type)) {
567 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
568 AST_RWLIST_UNLOCK(&channels);
573 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
574 AST_RWLIST_UNLOCK(&channels);
578 AST_LIST_INSERT_HEAD(&backends, chan, list);
580 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
582 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
584 AST_RWLIST_UNLOCK(&channels);
588 /*! \brief Unregister channel driver */
589 void ast_channel_unregister(const struct ast_channel_tech *tech)
591 struct chanlist *chan;
593 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
595 AST_RWLIST_WRLOCK(&channels);
597 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
598 if (chan->tech == tech) {
599 AST_LIST_REMOVE_CURRENT(list);
601 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
605 AST_LIST_TRAVERSE_SAFE_END;
607 AST_RWLIST_UNLOCK(&channels);
610 /*! \brief Get handle to channel driver based on name */
611 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
613 struct chanlist *chanls;
614 const struct ast_channel_tech *ret = NULL;
616 AST_RWLIST_RDLOCK(&channels);
618 AST_LIST_TRAVERSE(&backends, chanls, list) {
619 if (!strcasecmp(name, chanls->tech->type)) {
625 AST_RWLIST_UNLOCK(&channels);
630 /*! \brief Gives the string form of a given hangup cause */
631 const char *ast_cause2str(int cause)
635 for (x = 0; x < ARRAY_LEN(causes); x++) {
636 if (causes[x].cause == cause)
637 return causes[x].desc;
643 /*! \brief Convert a symbolic hangup cause to number */
644 int ast_str2cause(const char *name)
648 for (x = 0; x < ARRAY_LEN(causes); x++)
649 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
650 return causes[x].cause;
655 /*! \brief Gives the string form of a given channel state.
656 \note This function is not reentrant.
658 const char *ast_state2str(enum ast_channel_state state)
665 case AST_STATE_RESERVED:
667 case AST_STATE_OFFHOOK:
669 case AST_STATE_DIALING:
673 case AST_STATE_RINGING:
679 case AST_STATE_DIALING_OFFHOOK:
680 return "Dialing Offhook";
681 case AST_STATE_PRERING:
684 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
686 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
691 /*! \brief Gives the string form of a given transfer capability */
692 char *ast_transfercapability2str(int transfercapability)
694 switch (transfercapability) {
695 case AST_TRANS_CAP_SPEECH:
697 case AST_TRANS_CAP_DIGITAL:
699 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
700 return "RESTRICTED_DIGITAL";
701 case AST_TRANS_CAP_3_1K_AUDIO:
703 case AST_TRANS_CAP_DIGITAL_W_TONES:
704 return "DIGITAL_W_TONES";
705 case AST_TRANS_CAP_VIDEO:
712 /*! \brief Pick the best audio codec */
713 int ast_best_codec(int fmts)
715 /* This just our opinion, expressed in code. We are asked to choose
716 the best codec to use, given no information */
718 static const int prefs[] =
720 /*! Okay, ulaw is used by all telephony equipment, so start with it */
722 /*! Unless of course, you're a silly European, so then prefer ALAW */
724 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
726 /*! Okay, well, signed linear is easy to translate into other stuff */
727 AST_FORMAT_SLINEAR16,
729 /*! G.726 is standard ADPCM, in RFC3551 packing order */
731 /*! G.726 is standard ADPCM, in AAL2 packing order */
732 AST_FORMAT_G726_AAL2,
733 /*! ADPCM has great sound quality and is still pretty easy to translate */
735 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
736 translate and sounds pretty good */
738 /*! iLBC is not too bad */
740 /*! Speex is free, but computationally more expensive than GSM */
742 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
745 /*! G.729a is faster than 723 and slightly less expensive */
747 /*! Down to G.723.1 which is proprietary but at least designed for voice */
751 /* Strip out video */
752 fmts &= AST_FORMAT_AUDIO_MASK;
754 /* Find the first preferred codec in the format given */
755 for (x = 0; x < ARRAY_LEN(prefs); x++) {
760 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
765 static const struct ast_channel_tech null_tech = {
767 .description = "Null channel (should not see this)",
770 /*! \brief Create a new channel structure */
771 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, ...)
773 struct ast_channel *tmp;
776 struct varshead *headp;
779 /* If shutting down, don't allocate any new channels */
781 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
785 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
788 if (!(tmp->sched = sched_context_create())) {
789 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
794 if ((ast_string_field_init(tmp, 128))) {
795 sched_context_destroy(tmp->sched);
801 tmp->epfd = epoll_create(25);
804 for (x = 0; x < AST_MAX_FDS; x++) {
807 tmp->epfd_data[x] = NULL;
811 tmp->timingfd = ast_timer_open();
812 if (tmp->timingfd > -1) {
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 ast_timer_close(tmp->timingfd);
824 sched_context_destroy(tmp->sched);
825 ast_string_field_free_memory(tmp);
829 flags = fcntl(tmp->alertpipe[0], F_GETFL);
830 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
831 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
832 close(tmp->alertpipe[0]);
833 close(tmp->alertpipe[1]);
834 goto alertpipe_failed;
836 flags = fcntl(tmp->alertpipe[1], F_GETFL);
837 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
838 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
839 close(tmp->alertpipe[0]);
840 close(tmp->alertpipe[1]);
841 goto alertpipe_failed;
844 } else /* Make sure we've got it done right if they don't */
845 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
847 /* Always watch the alertpipe */
848 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
849 /* And timing pipe */
850 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
851 ast_string_field_set(tmp, name, "**Unknown**");
858 tmp->fin = global_fin;
859 tmp->fout = global_fout;
861 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
862 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
863 ast_atomic_fetchadd_int(&uniqueint, 1));
865 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
866 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
869 tmp->cid.cid_name = ast_strdup(cid_name);
870 tmp->cid.cid_num = ast_strdup(cid_num);
872 if (!ast_strlen_zero(name_fmt)) {
873 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
874 * And they all use slightly different formats for their name string.
875 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
876 * This means, that the stringfields must have a routine that takes the va_lists directly, and
877 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
878 * This new function was written so this can be accomplished.
880 va_start(ap1, name_fmt);
881 va_start(ap2, name_fmt);
882 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
887 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
889 /* These 4 variables need to be set up for the cdr_init() to work right */
891 tmp->amaflags = amaflag;
893 tmp->amaflags = ast_default_amaflags;
895 if (!ast_strlen_zero(acctcode))
896 ast_string_field_set(tmp, accountcode, acctcode);
898 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
900 if (!ast_strlen_zero(context))
901 ast_copy_string(tmp->context, context, sizeof(tmp->context));
903 strcpy(tmp->context, "default");
905 if (!ast_strlen_zero(exten))
906 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
908 strcpy(tmp->exten, "s");
912 tmp->cdr = ast_cdr_alloc();
913 ast_cdr_init(tmp->cdr, tmp);
914 ast_cdr_start(tmp->cdr);
916 headp = &tmp->varshead;
917 AST_LIST_HEAD_INIT_NOLOCK(headp);
919 ast_mutex_init(&tmp->lock_dont_use);
921 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
923 ast_string_field_set(tmp, language, defaultlanguage);
925 tmp->tech = &null_tech;
927 AST_RWLIST_WRLOCK(&channels);
928 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
929 AST_RWLIST_UNLOCK(&channels);
932 * and now, since the channel structure is built, and has its name, let's
933 * call the manager event generator with this Newchannel event. This is the
934 * proper and correct place to make this call, but you sure do have to pass
935 * a lot of data into this func to do it here!
937 if (!ast_strlen_zero(name_fmt)) {
938 manager_event(EVENT_FLAG_CALL, "Newchannel",
940 "ChannelState: %d\r\n"
941 "ChannelStateDesc: %s\r\n"
942 "CallerIDNum: %s\r\n"
943 "CallerIDName: %s\r\n"
944 "AccountCode: %s\r\n"
948 ast_state2str(state),
958 /*! \brief Queue an outgoing media frame */
959 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
962 struct ast_frame *cur;
966 /* Build us a copy and free the original one */
967 if (!(f = ast_frdup(fin))) {
968 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
971 ast_channel_lock(chan);
973 /* See if the last frame on the queue is a hangup, if so don't queue anything */
974 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
976 ast_channel_unlock(chan);
980 /* Count how many frames exist on the queue */
981 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
985 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
986 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
987 if (fin->frametype != AST_FRAME_VOICE) {
988 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
989 ast_assert(fin->frametype == AST_FRAME_VOICE);
991 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
993 ast_channel_unlock(chan);
997 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
998 if (chan->alertpipe[1] > -1) {
999 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
1000 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
1001 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
1002 } else if (chan->timingfd > -1) {
1003 ast_timer_enable_continuous(chan->timingfd);
1004 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1005 pthread_kill(chan->blocker, SIGURG);
1007 ast_channel_unlock(chan);
1011 /*! \brief Queue a hangup frame for channel */
1012 int ast_queue_hangup(struct ast_channel *chan)
1014 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1015 /* Yeah, let's not change a lock-critical value without locking */
1016 if (!ast_channel_trylock(chan)) {
1017 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1018 ast_channel_unlock(chan);
1020 return ast_queue_frame(chan, &f);
1023 /*! \brief Queue a hangup frame for channel */
1024 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1026 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1029 f.data.uint32 = cause;
1031 /* Yeah, let's not change a lock-critical value without locking */
1032 if (!ast_channel_trylock(chan)) {
1033 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1035 f.data.uint32 = chan->hangupcause;
1037 ast_channel_unlock(chan);
1040 return ast_queue_frame(chan, &f);
1043 /*! \brief Queue a control frame */
1044 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1046 struct ast_frame f = { AST_FRAME_CONTROL, };
1048 f.subclass = control;
1050 return ast_queue_frame(chan, &f);
1053 /*! \brief Queue a control frame with payload */
1054 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1055 const void *data, size_t datalen)
1057 struct ast_frame f = { AST_FRAME_CONTROL, };
1059 f.subclass = control;
1060 f.data.ptr = (void *) data;
1061 f.datalen = datalen;
1063 return ast_queue_frame(chan, &f);
1066 /*! \brief Set defer DTMF flag on channel */
1067 int ast_channel_defer_dtmf(struct ast_channel *chan)
1072 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1073 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1078 /*! \brief Unset defer DTMF flag on channel */
1079 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1082 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1086 * \brief Helper function to find channels.
1088 * It supports these modes:
1090 * prev != NULL : get channel next in list after prev
1091 * name != NULL : get channel with matching name
1092 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1093 * exten != NULL : get channel whose exten or macroexten matches
1094 * context != NULL && exten != NULL : get channel whose context or macrocontext
1096 * It returns with the channel's lock held. If getting the individual lock fails,
1097 * unlock and retry quickly up to 10 times, then give up.
1099 * \note XXX Note that this code has cost O(N) because of the need to verify
1100 * that the object is still on the global list.
1102 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1103 * can only be done with the lock held or someone could delete the
1104 * object while we work on it. This causes some ugliness in the code.
1105 * Note that removing the first ast_log() may be harmful, as it would
1106 * shorten the retry period and possibly cause failures.
1107 * We should definitely go for a better scheme that is deadlock-free.
1109 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1110 const char *name, const int namelen,
1111 const char *context, const char *exten)
1113 const char *msg = prev ? "deadlock" : "initial deadlock";
1115 struct ast_channel *c;
1116 const struct ast_channel *_prev = prev;
1118 for (retries = 0; retries < 200; retries++) {
1120 /* Reset prev on each retry. See note below for the reason. */
1122 AST_RWLIST_RDLOCK(&channels);
1123 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1124 if (prev) { /* look for last item, first, before any evaluation */
1125 if (c != prev) /* not this one */
1127 /* found, prepare to return c->next */
1128 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
1130 * We're done searching through the list for the previous item.
1131 * Any item after this point, we want to evaluate for a match.
1132 * If we didn't set prev to NULL here, then we would only
1133 * return matches for the first matching item (since the above
1134 * "if (c != prev)" would not permit any other potential
1135 * matches to reach the additional matching logic, below).
1136 * Instead, it would just iterate until it once again found the
1137 * original match, then iterate down to the end of the list and
1142 if (name) { /* want match by name */
1143 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
1144 (namelen && strncasecmp(c->name, name, namelen)))
1145 continue; /* name match failed */
1147 if (context && strcasecmp(c->context, context) &&
1148 strcasecmp(c->macrocontext, context))
1149 continue; /* context match failed */
1150 if (strcasecmp(c->exten, exten) &&
1151 strcasecmp(c->macroexten, exten))
1152 continue; /* exten match failed */
1154 /* if we get here, c points to the desired record */
1157 /* exit if chan not found or mutex acquired successfully */
1158 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1159 done = c == NULL || ast_channel_trylock(c) == 0;
1161 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
1162 if (retries == 199) {
1163 /* We are about to fail due to a deadlock, so report this
1164 * while we still have the list lock.
1166 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1167 /* As we have deadlocked, we will skip this channel and
1168 * see if there is another match.
1169 * NOTE: No point doing this for a full-name match,
1170 * as there can be no more matches.
1172 if (!(name && !namelen)) {
1178 AST_RWLIST_UNLOCK(&channels);
1181 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1182 * starting from the beginning of the list we can restore our saved pointer to the previous
1183 * channel and start from there.
1186 usleep(1); /* give other threads a chance before retrying */
1192 /*! \brief Browse channels in use */
1193 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1195 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1198 /*! \brief Get channel by name and lock it */
1199 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1201 return channel_find_locked(NULL, name, 0, NULL, NULL);
1204 /*! \brief Get channel by name prefix and lock it */
1205 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1207 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1210 /*! \brief Get next channel by name prefix and lock it */
1211 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1214 return channel_find_locked(chan, name, namelen, NULL, NULL);
1217 /*! \brief Get channel by exten (and optionally context) and lock it */
1218 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1220 return channel_find_locked(NULL, NULL, 0, context, exten);
1223 /*! \brief Get next channel by exten (and optionally context) and lock it */
1224 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1225 const char *context)
1227 return channel_find_locked(chan, NULL, 0, context, exten);
1230 /*! \brief Wait, look for hangups and condition arg */
1231 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1233 struct ast_frame *f;
1236 if (cond && ((*cond)(data) == 0))
1238 ms = ast_waitfor(chan, ms);
1251 /*! \brief Wait, look for hangups */
1252 int ast_safe_sleep(struct ast_channel *chan, int ms)
1254 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1257 static void free_cid(struct ast_callerid *cid)
1260 ast_free(cid->cid_dnid);
1262 ast_free(cid->cid_num);
1264 ast_free(cid->cid_name);
1266 ast_free(cid->cid_ani);
1268 ast_free(cid->cid_rdnis);
1269 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1272 /*! \brief Free a channel structure */
1273 void ast_channel_free(struct ast_channel *chan)
1279 struct ast_var_t *vardata;
1280 struct ast_frame *f;
1281 struct varshead *headp;
1282 struct ast_datastore *datastore = NULL;
1283 char name[AST_CHANNEL_NAME], *dashptr;
1285 headp=&chan->varshead;
1287 AST_RWLIST_WRLOCK(&channels);
1288 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1289 AST_RWLIST_UNLOCK(&channels);
1290 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1292 /* Lock and unlock the channel just to be sure nobody has it locked still
1293 due to a reference retrieved from the channel list. */
1294 ast_channel_lock(chan);
1295 ast_channel_unlock(chan);
1297 /* Get rid of each of the data stores on the channel */
1298 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1299 /* Free the data store */
1300 ast_datastore_free(datastore);
1302 /* Lock and unlock the channel just to be sure nobody has it locked still
1303 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1304 ast_channel_lock(chan);
1305 ast_channel_unlock(chan);
1307 if (chan->tech_pvt) {
1308 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1309 ast_free(chan->tech_pvt);
1313 sched_context_destroy(chan->sched);
1315 ast_copy_string(name, chan->name, sizeof(name));
1316 if ((dashptr = strrchr(name, '-'))) {
1320 /* Stop monitoring */
1322 chan->monitor->stop( chan, 0 );
1324 /* If there is native format music-on-hold state, free it */
1325 if (chan->music_state)
1326 ast_moh_cleanup(chan);
1328 /* Free translators */
1329 if (chan->readtrans)
1330 ast_translator_free_path(chan->readtrans);
1331 if (chan->writetrans)
1332 ast_translator_free_path(chan->writetrans);
1334 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1335 free_cid(&chan->cid);
1336 /* Close pipes if appropriate */
1337 if ((fd = chan->alertpipe[0]) > -1)
1339 if ((fd = chan->alertpipe[1]) > -1)
1341 if ((fd = chan->timingfd) > -1)
1342 ast_timer_close(fd);
1344 for (i = 0; i < AST_MAX_FDS; i++) {
1345 if (chan->epfd_data[i])
1346 free(chan->epfd_data[i]);
1350 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1353 /* loop over the variables list, freeing all data and deleting list items */
1354 /* no need to lock the list, as the channel is already locked */
1356 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1357 ast_var_delete(vardata);
1359 ast_app_group_discard(chan);
1361 /* Destroy the jitterbuffer */
1362 ast_jb_destroy(chan);
1365 ast_cdr_discard(chan->cdr);
1369 ast_mutex_destroy(&chan->lock_dont_use);
1371 ast_string_field_free_memory(chan);
1373 AST_RWLIST_UNLOCK(&channels);
1375 ast_devstate_changed_literal(AST_DEVICE_NOT_INUSE, name);
1378 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1380 return ast_datastore_alloc(info, uid);
1383 int ast_channel_datastore_free(struct ast_datastore *datastore)
1385 return ast_datastore_free(datastore);
1388 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1390 struct ast_datastore *datastore = NULL, *datastore2;
1392 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1393 if (datastore->inheritance > 0) {
1394 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1396 datastore2->data = datastore->info->duplicate(datastore->data);
1397 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1398 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1405 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1409 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1414 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1416 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1419 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1421 struct ast_datastore *datastore = NULL;
1426 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1427 if (datastore->info != info) {
1432 /* matched by type only */
1436 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
1437 /* Matched by type AND uid */
1441 AST_LIST_TRAVERSE_SAFE_END;
1446 /*! Set the file descriptor on the channel */
1447 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1450 struct epoll_event ev;
1451 struct ast_epoll_data *aed = NULL;
1453 if (chan->fds[which] > -1) {
1454 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1455 aed = chan->epfd_data[which];
1458 /* If this new fd is valid, add it to the epoll */
1460 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1463 chan->epfd_data[which] = aed;
1467 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1469 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1471 /* We don't have to keep around this epoll data structure now */
1473 chan->epfd_data[which] = NULL;
1476 chan->fds[which] = fd;
1480 /*! Add a channel to an optimized waitfor */
1481 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1484 struct epoll_event ev;
1487 if (chan0->epfd == -1)
1490 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1491 for (i = 0; i < AST_MAX_FDS; i++) {
1492 if (chan1->fds[i] == -1)
1494 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1495 ev.data.ptr = chan1->epfd_data[i];
1496 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1503 /*! Delete a channel from an optimized waitfor */
1504 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1507 struct epoll_event ev;
1510 if (chan0->epfd == -1)
1513 for (i = 0; i < AST_MAX_FDS; i++) {
1514 if (chan1->fds[i] == -1)
1516 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1523 /*! \brief Softly hangup a channel, don't lock */
1524 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1526 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1527 /* Inform channel driver that we need to be hung up, if it cares */
1528 chan->_softhangup |= cause;
1529 ast_queue_frame(chan, &ast_null_frame);
1530 /* Interrupt any poll call or such */
1531 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1532 pthread_kill(chan->blocker, SIGURG);
1536 /*! \brief Softly hangup a channel, lock */
1537 int ast_softhangup(struct ast_channel *chan, int cause)
1541 ast_channel_lock(chan);
1542 res = ast_softhangup_nolock(chan, cause);
1543 ast_channel_unlock(chan);
1548 static void free_translation(struct ast_channel *clonechan)
1550 if (clonechan->writetrans)
1551 ast_translator_free_path(clonechan->writetrans);
1552 if (clonechan->readtrans)
1553 ast_translator_free_path(clonechan->readtrans);
1554 clonechan->writetrans = NULL;
1555 clonechan->readtrans = NULL;
1556 clonechan->rawwriteformat = clonechan->nativeformats;
1557 clonechan->rawreadformat = clonechan->nativeformats;
1560 /*! \brief Hangup a channel */
1561 int ast_hangup(struct ast_channel *chan)
1565 /* Don't actually hang up a channel that will masquerade as someone else, or
1566 if someone is going to masquerade as us */
1567 ast_channel_lock(chan);
1569 if (chan->audiohooks) {
1570 ast_audiohook_detach_list(chan->audiohooks);
1571 chan->audiohooks = NULL;
1574 ast_autoservice_stop(chan);
1577 if (ast_do_masquerade(chan))
1578 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1582 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1583 ast_channel_unlock(chan);
1586 /* If this channel is one which will be masqueraded into something,
1587 mark it as a zombie already, so we know to free it later */
1589 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1590 ast_channel_unlock(chan);
1593 free_translation(chan);
1594 /* Close audio stream */
1596 ast_closestream(chan->stream);
1597 chan->stream = NULL;
1599 /* Close video stream */
1600 if (chan->vstream) {
1601 ast_closestream(chan->vstream);
1602 chan->vstream = NULL;
1605 sched_context_destroy(chan->sched);
1609 if (chan->generatordata) /* Clear any tone stuff remaining */
1610 if (chan->generator && chan->generator->release)
1611 chan->generator->release(chan, chan->generatordata);
1612 chan->generatordata = NULL;
1613 chan->generator = NULL;
1614 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1615 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1616 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1617 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1618 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1620 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1621 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1622 if (chan->tech->hangup)
1623 res = chan->tech->hangup(chan);
1625 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1628 ast_channel_unlock(chan);
1629 manager_event(EVENT_FLAG_CALL, "Hangup",
1632 "CallerIDNum: %s\r\n"
1633 "CallerIDName: %s\r\n"
1635 "Cause-txt: %s\r\n",
1638 S_OR(chan->cid.cid_num, "<unknown>"),
1639 S_OR(chan->cid.cid_name, "<unknown>"),
1641 ast_cause2str(chan->hangupcause)
1644 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
1645 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
1646 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
1648 ast_cdr_end(chan->cdr);
1649 ast_cdr_detach(chan->cdr);
1653 ast_channel_free(chan);
1658 #define ANSWER_WAIT_MS 500
1659 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1663 ast_channel_lock(chan);
1665 /* You can't answer an outbound call */
1666 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1667 ast_channel_unlock(chan);
1671 /* Stop if we're a zombie or need a soft hangup */
1672 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1673 ast_channel_unlock(chan);
1677 ast_channel_unlock(chan);
1679 switch (chan->_state) {
1680 case AST_STATE_RINGING:
1681 case AST_STATE_RING:
1682 ast_channel_lock(chan);
1683 if (chan->tech->answer) {
1684 res = chan->tech->answer(chan);
1686 ast_setstate(chan, AST_STATE_UP);
1687 ast_cdr_answer(chan->cdr);
1688 ast_channel_unlock(chan);
1690 ast_safe_sleep(chan, delay);
1692 struct ast_frame *f;
1693 int ms = ANSWER_WAIT_MS;
1695 /* 500 ms was the original delay here, so now
1696 * we cap our waiting at 500 ms
1698 ms = ast_waitfor(chan, ms);
1700 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
1705 ast_debug(2, "Didn't receive a voice frame from %s within %d ms of answering. Continuing anyway\n", chan->name, ANSWER_WAIT_MS);
1710 if (!f || (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)) {
1712 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
1715 if (f->frametype == AST_FRAME_VOICE) {
1728 chan->visible_indication = 0;
1733 int ast_answer(struct ast_channel *chan)
1735 return __ast_answer(chan, 0);
1738 void ast_deactivate_generator(struct ast_channel *chan)
1740 ast_channel_lock(chan);
1741 if (chan->generatordata) {
1742 if (chan->generator && chan->generator->release)
1743 chan->generator->release(chan, chan->generatordata);
1744 chan->generatordata = NULL;
1745 chan->generator = NULL;
1746 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1747 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1748 ast_settimeout(chan, 0, NULL, NULL);
1750 ast_channel_unlock(chan);
1753 static int generator_force(const void *data)
1755 /* Called if generator doesn't have data */
1758 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1759 struct ast_channel *chan = (struct ast_channel *)data;
1761 ast_channel_lock(chan);
1762 tmp = chan->generatordata;
1763 chan->generatordata = NULL;
1764 if (chan->generator)
1765 generate = chan->generator->generate;
1766 ast_channel_unlock(chan);
1768 if (!tmp || !generate)
1771 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1773 chan->generatordata = tmp;
1776 ast_debug(1, "Auto-deactivating generator\n");
1777 ast_deactivate_generator(chan);
1783 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1787 ast_channel_lock(chan);
1789 if (chan->generatordata) {
1790 if (chan->generator && chan->generator->release)
1791 chan->generator->release(chan, chan->generatordata);
1792 chan->generatordata = NULL;
1796 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1801 ast_settimeout(chan, 50, generator_force, chan);
1802 chan->generator = gen;
1805 ast_channel_unlock(chan);
1810 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1811 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1814 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1818 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1820 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1821 int *exception, int *outfd, int *ms)
1823 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1824 int *exception, int *outfd, int *ms)
1827 struct timeval start = { 0 , 0 };
1828 struct pollfd *pfds = NULL;
1833 struct timeval now = { 0, 0 };
1834 struct timeval whentohangup = { 0, 0 }, diff;
1835 struct ast_channel *winner = NULL;
1841 if ((sz = n * AST_MAX_FDS + nfds)) {
1842 pfds = alloca(sizeof(*pfds) * sz);
1843 fdmap = alloca(sizeof(*fdmap) * sz);
1851 /* Perform any pending masquerades */
1852 for (x = 0; x < n; x++) {
1853 ast_channel_lock(c[x]);
1854 if (c[x]->masq && ast_do_masquerade(c[x])) {
1855 ast_log(LOG_WARNING, "Masquerade failed\n");
1857 ast_channel_unlock(c[x]);
1860 if (!ast_tvzero(c[x]->whentohangup)) {
1861 if (ast_tvzero(whentohangup))
1863 diff = ast_tvsub(c[x]->whentohangup, now);
1864 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
1865 /* Should already be hungup */
1866 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1867 ast_channel_unlock(c[x]);
1870 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
1871 whentohangup = diff;
1873 ast_channel_unlock(c[x]);
1875 /* Wait full interval */
1877 if (!ast_tvzero(whentohangup)) {
1878 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
1879 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1883 * Build the pollfd array, putting the channels' fds first,
1884 * followed by individual fds. Order is important because
1885 * individual fd's must have priority over channel fds.
1888 for (x = 0; x < n; x++) {
1889 for (y = 0; y < AST_MAX_FDS; y++) {
1890 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1891 fdmap[max].chan = x; /* channel x is linked to this pfds */
1892 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1894 CHECK_BLOCKING(c[x]);
1896 /* Add the individual fds */
1897 for (x = 0; x < nfds; x++) {
1898 fdmap[max].chan = -1;
1899 max += ast_add_fd(&pfds[max], fds[x]);
1903 start = ast_tvnow();
1905 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1910 res = poll(pfds, max, kbrms);
1913 } while (!res && (rms > 0));
1915 res = poll(pfds, max, rms);
1917 for (x = 0; x < n; x++)
1918 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1919 if (res < 0) { /* Simulate a timeout if we were interrupted */
1924 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
1926 for (x = 0; x < n; x++) {
1927 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
1928 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1934 if (res == 0) { /* no fd ready, reset timeout and done */
1935 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1939 * Then check if any channel or fd has a pending event.
1940 * Remember to check channels first and fds last, as they
1941 * must have priority on setting 'winner'
1943 for (x = 0; x < max; x++) {
1944 res = pfds[x].revents;
1947 if (fdmap[x].chan >= 0) { /* this is a channel */
1948 winner = c[fdmap[x].chan]; /* override previous winners */
1950 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1952 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1953 winner->fdno = fdmap[x].fdno;
1954 } else { /* this is an fd */
1956 *outfd = pfds[x].fd;
1958 *exception = (res & POLLPRI) ? -1 : 0;
1963 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1971 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1973 struct timeval start = { 0 , 0 };
1975 struct epoll_event ev[1];
1976 long diff, rms = *ms;
1977 struct ast_channel *winner = NULL;
1978 struct ast_epoll_data *aed = NULL;
1980 ast_channel_lock(chan);
1982 /* See if this channel needs to be masqueraded */
1983 if (chan->masq && ast_do_masquerade(chan)) {
1984 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1986 ast_channel_unlock(chan);
1990 /* Figure out their timeout */
1991 if (!ast_tvzero(chan->whentohangup)) {
1992 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
1993 /* They should already be hungup! */
1994 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1995 ast_channel_unlock(chan);
1998 /* If this value is smaller then the current one... make it priority */
2003 ast_channel_unlock(chan);
2005 /* Time to make this channel block... */
2006 CHECK_BLOCKING(chan);
2009 start = ast_tvnow();
2011 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2012 res = epoll_wait(chan->epfd, ev, 1, rms);
2015 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2017 /* Simulate a timeout if we were interrupted */
2024 /* If this channel has a timeout see if it expired */
2025 if (!ast_tvzero(chan->whentohangup)) {
2026 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2027 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2032 /* No fd ready, reset timeout and be done for now */
2038 /* See what events are pending */
2039 aed = ev[0].data.ptr;
2040 chan->fdno = aed->which;
2041 if (ev[0].events & EPOLLPRI)
2042 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2044 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2047 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2055 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2057 struct timeval start = { 0 , 0 };
2059 struct epoll_event ev[25] = { { 0, } };
2060 struct timeval now = { 0, 0 };
2061 long whentohangup = 0, diff = 0, rms = *ms;
2062 struct ast_channel *winner = NULL;
2064 for (i = 0; i < n; i++) {
2065 ast_channel_lock(c[i]);
2066 if (c[i]->masq && ast_do_masquerade(c[i])) {
2067 ast_log(LOG_WARNING, "Masquerade failed\n");
2069 ast_channel_unlock(c[i]);
2072 if (!ast_tvzero(c[i]->whentohangup)) {
2073 if (whentohangup == 0)
2075 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2076 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2077 ast_channel_unlock(c[i]);
2080 if (!whentohangup || whentohangup > diff)
2081 whentohangup = diff;
2083 ast_channel_unlock(c[i]);
2084 CHECK_BLOCKING(c[i]);
2090 if (*ms >= 0 && *ms < rms)
2095 start = ast_tvnow();
2097 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2099 for (i = 0; i < n; i++)
2100 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2110 for (i = 0; i < n; i++) {
2111 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2112 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2124 for (i = 0; i < res; i++) {
2125 struct ast_epoll_data *aed = ev[i].data.ptr;
2127 if (!ev[i].events || !aed)
2131 if (ev[i].events & EPOLLPRI)
2132 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2134 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2135 winner->fdno = aed->which;
2139 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2147 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2148 int *exception, int *outfd, int *ms)
2150 /* Clear all provided values in one place. */
2156 /* If no epoll file descriptor is available resort to classic nandfds */
2157 if (!n || nfds || c[0]->epfd == -1)
2158 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2159 else if (!nfds && n == 1)
2160 return ast_waitfor_nandfds_simple(c[0], ms);
2162 return ast_waitfor_nandfds_complex(c, n, ms);
2166 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2168 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2171 int ast_waitfor(struct ast_channel *c, int ms)
2173 int oldms = ms; /* -1 if no timeout */
2175 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2176 if ((ms < 0) && (oldms < 0))
2181 /* XXX never to be called with ms = -1 */
2182 int ast_waitfordigit(struct ast_channel *c, int ms)
2184 return ast_waitfordigit_full(c, ms, -1, -1);
2187 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2190 unsigned int real_rate = rate, max_rate;
2192 if (c->timingfd == -1) {
2201 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timingfd))) {
2202 real_rate = max_rate;
2205 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2207 res = ast_timer_set_rate(c->timingfd, real_rate);
2209 c->timingfunc = func;
2210 c->timingdata = data;
2215 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2217 /* Stop if we're a zombie or need a soft hangup */
2218 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2221 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2222 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2224 /* Wait for a digit, no more than ms milliseconds total. */
2227 struct ast_channel *rchan;
2231 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2233 if (!rchan && outfd < 0 && ms) {
2234 if (errno == 0 || errno == EINTR)
2236 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2237 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2239 } else if (outfd > -1) {
2240 /* The FD we were watching has something waiting */
2241 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2242 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2246 struct ast_frame *f = ast_read(c);
2250 switch (f->frametype) {
2251 case AST_FRAME_DTMF_BEGIN:
2253 case AST_FRAME_DTMF_END:
2256 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2258 case AST_FRAME_CONTROL:
2259 switch (f->subclass) {
2260 case AST_CONTROL_HANGUP:
2262 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2264 case AST_CONTROL_RINGING:
2265 case AST_CONTROL_ANSWER:
2266 case AST_CONTROL_SRCUPDATE:
2270 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2274 case AST_FRAME_VOICE:
2275 /* Write audio if appropriate */
2277 write(audiofd, f->data.ptr, f->datalen);
2286 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2288 return 0; /* Time is up */
2291 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2293 manager_event(EVENT_FLAG_DTMF,
2301 chan->name, chan->uniqueid, digit, direction, begin, end);
2304 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2306 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2307 void *tmp = chan->generatordata;
2308 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2312 if (chan->timingfunc) {
2313 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2314 ast_settimeout(chan, 0, NULL, NULL);
2317 chan->generatordata = NULL; /* reset, to let writes go through */
2319 if (f->subclass != chan->writeformat) {
2321 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
2322 samples = (int) ( ((float) f->samples) * factor );
2324 samples = f->samples;
2327 if (chan->generator->generate) {
2328 generate = chan->generator->generate;
2330 /* This unlock is here based on two assumptions that hold true at this point in the
2331 * code. 1) this function is only called from within __ast_read() and 2) all generators
2332 * call ast_write() in their generate callback.
2334 * The reason this is added is so that when ast_write is called, the lock that occurs
2335 * there will not recursively lock the channel. Doing this will cause intended deadlock
2336 * avoidance not to work in deeper functions
2338 ast_channel_unlock(chan);
2339 res = generate(chan, tmp, f->datalen, samples);
2340 ast_channel_lock(chan);
2341 chan->generatordata = tmp;
2343 ast_debug(1, "Auto-deactivating generator\n");
2344 ast_deactivate_generator(chan);
2347 } else if (f->frametype == AST_FRAME_CNG) {
2348 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2349 ast_debug(1, "Generator got CNG, switching to timed mode\n");
2350 ast_settimeout(chan, 50, generator_force, chan);
2355 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2357 struct ast_frame *f = NULL; /* the return value */
2360 int count = 0, cause = 0;
2362 /* this function is very long so make sure there is only one return
2363 * point at the end (there are only two exceptions to this).
2365 while(ast_channel_trylock(chan)) {
2367 /*cannot goto done since the channel is not locked*/
2368 return &ast_null_frame;
2373 if (ast_do_masquerade(chan))
2374 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2376 f = &ast_null_frame;
2380 /* Stop if we're a zombie or need a soft hangup */
2381 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2382 if (chan->generator)
2383 ast_deactivate_generator(chan);
2386 prestate = chan->_state;
2388 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2389 !ast_strlen_zero(chan->dtmfq) &&
2390 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2391 /* We have DTMF that has been deferred. Return it now */
2392 chan->dtmff.subclass = chan->dtmfq[0];
2393 /* Drop first digit from the buffer */
2394 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2396 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2397 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2398 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2400 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);
2401 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2402 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2403 chan->emulate_dtmf_digit = f->subclass;
2404 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2406 chan->dtmf_tv = ast_tvnow();
2410 /* Read and ignore anything on the alertpipe, but read only
2411 one sizeof(blah) per frame that we send from it */
2412 if (chan->alertpipe[0] > -1) {
2413 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2414 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2415 * which immediately causes a deadlock scenario. Detect and prevent this. */
2416 if ((flags & O_NONBLOCK) == 0) {
2417 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2418 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2419 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2420 f = &ast_null_frame;
2424 read(chan->alertpipe[0], &blah, sizeof(blah));
2427 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
2428 enum ast_timing_event res;
2430 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2432 res = ast_timer_get_event(chan->timingfd);
2435 case AST_TIMING_EVENT_EXPIRED:
2436 ast_timer_ack(chan->timingfd, 1);
2438 if (chan->timingfunc) {
2439 /* save a copy of func/data before unlocking the channel */
2440 int (*func)(const void *) = chan->timingfunc;
2441 void *data = chan->timingdata;
2442 ast_channel_unlock(chan);
2445 ast_timer_set_rate(chan->timingfd, 0);
2446 ast_channel_unlock(chan);
2449 /* cannot 'goto done' because the channel is already unlocked */
2450 return &ast_null_frame;
2452 case AST_TIMING_EVENT_CONTINUOUS:
2453 if (AST_LIST_EMPTY(&chan->readq) ||
2454 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2455 ast_timer_disable_continuous(chan->timingfd);
2460 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2461 /* if the AST_GENERATOR_FD is set, call the generator with args
2462 * set to -1 so it can do whatever it needs to.
2464 void *tmp = chan->generatordata;
2465 chan->generatordata = NULL; /* reset to let ast_write get through */
2466 chan->generator->generate(chan, tmp, -1, -1);
2467 chan->generatordata = tmp;
2468 f = &ast_null_frame;
2472 /* Check for pending read queue */
2473 if (!AST_LIST_EMPTY(&chan->readq)) {
2474 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2475 /* Interpret hangup and return NULL */
2476 /* XXX why not the same for frames from the channel ? */
2477 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2478 cause = f->data.uint32;
2483 chan->blocker = pthread_self();
2484 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2485 if (chan->tech->exception)
2486 f = chan->tech->exception(chan);
2488 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2489 f = &ast_null_frame;
2491 /* Clear the exception flag */
2492 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2493 } else if (chan->tech->read)
2494 f = chan->tech->read(chan);
2496 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2500 /* if the channel driver returned more than one frame, stuff the excess
2501 into the readq for the next ast_read call (note that we can safely assume
2502 that the readq is empty, because otherwise we would not have called into
2503 the channel driver and f would be only a single frame)
2505 if (AST_LIST_NEXT(f, frame_list)) {
2506 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2507 AST_LIST_NEXT(f, frame_list) = NULL;
2510 switch (f->frametype) {
2511 case AST_FRAME_CONTROL:
2512 if (f->subclass == AST_CONTROL_ANSWER) {
2513 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2514 ast_debug(1, "Ignoring answer on an inbound call!\n");
2516 f = &ast_null_frame;
2517 } else if (prestate == AST_STATE_UP) {
2518 ast_debug(1, "Dropping duplicate answer!\n");
2520 f = &ast_null_frame;
2522 /* Answer the CDR */
2523 ast_setstate(chan, AST_STATE_UP);
2524 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2528 case AST_FRAME_DTMF_END:
2529 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2530 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2531 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2532 * However, only let emulation be forced if the other end cares about BEGIN frames */
2533 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2534 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2535 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2536 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2537 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2539 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2541 f = &ast_null_frame;
2542 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2543 if (!ast_tvzero(chan->dtmf_tv) &&
2544 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2545 /* If it hasn't been long enough, defer this digit */
2546 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2547 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2548 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2550 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2552 f = &ast_null_frame;
2554 /* There was no begin, turn this into a begin and send the end later */
2555 f->frametype = AST_FRAME_DTMF_BEGIN;
2556 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2557 chan->emulate_dtmf_digit = f->subclass;
2558 chan->dtmf_tv = ast_tvnow();
2560 if (f->len > AST_MIN_DTMF_DURATION)
2561 chan->emulate_dtmf_duration = f->len;
2563 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2565 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2566 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2568 if (chan->audiohooks) {
2569 struct ast_frame *old_frame = f;
2571 * \todo XXX It is possible to write a digit to the audiohook twice
2572 * if the digit was originally read while the channel was in autoservice. */
2573 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2575 ast_frfree(old_frame);
2578 struct timeval now = ast_tvnow();
2579 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2580 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2581 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2583 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2584 } else if (!f->len) {
2585 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2586 f->len = AST_MIN_DTMF_DURATION;
2588 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2589 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);
2590 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2591 chan->emulate_dtmf_digit = f->subclass;
2592 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2594 f = &ast_null_frame;
2596 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2597 if (f->len < AST_MIN_DTMF_DURATION) {
2598 f->len = AST_MIN_DTMF_DURATION;
2600 chan->dtmf_tv = now;
2602 if (chan->audiohooks) {
2603 struct ast_frame *old_frame = f;
2604 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2606 ast_frfree(old_frame);
2610 case AST_FRAME_DTMF_BEGIN:
2611 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2612 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2613 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2614 (!ast_tvzero(chan->dtmf_tv) &&
2615 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2616 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2618 f = &ast_null_frame;
2620 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2621 chan->dtmf_tv = ast_tvnow();
2622 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2625 case AST_FRAME_NULL:
2626 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2627 * is reached , because we want to make sure we pass at least one
2628 * voice frame through before starting the next digit, to ensure a gap
2629 * between DTMF digits. */
2630 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2631 struct timeval now = ast_tvnow();
2632 if (!chan->emulate_dtmf_duration) {
2633 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2634 chan->emulate_dtmf_digit = 0;
2635 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2636 chan->emulate_dtmf_duration = 0;
2639 f->frametype = AST_FRAME_DTMF_END;
2640 f->subclass = chan->emulate_dtmf_digit;
2641 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2642 chan->dtmf_tv = now;
2643 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2644 chan->emulate_dtmf_digit = 0;
2645 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2649 case AST_FRAME_VOICE:
2650 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2651 * is reached , because we want to make sure we pass at least one
2652 * voice frame through before starting the next digit, to ensure a gap
2653 * between DTMF digits. */
2654 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2655 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2656 chan->emulate_dtmf_digit = 0;
2659 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2661 ast_read_generator_actions(chan, f);
2663 f = &ast_null_frame;
2666 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2667 struct timeval now = ast_tvnow();
2668 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2669 chan->emulate_dtmf_duration = 0;
2672 f->frametype = AST_FRAME_DTMF_END;
2673 f->subclass = chan->emulate_dtmf_digit;
2674 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2675 chan->dtmf_tv = now;
2676 if (chan->audiohooks) {
2677 struct ast_frame *old_frame = f;
2678 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2680 ast_frfree(old_frame);
2682 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2684 /* Drop voice frames while we're still in the middle of the digit */
2686 f = &ast_null_frame;
2688 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2689 /* This frame is not one of the current native formats -- drop it on the floor */
2691 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2692 chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2694 f = &ast_null_frame;
2695 } else if ((f->frametype == AST_FRAME_VOICE)) {
2696 /* Send frame to audiohooks if present */
2697 if (chan->audiohooks) {
2698 struct ast_frame *old_frame = f;
2699 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2701 ast_frfree(old_frame);
2703 if (chan->monitor && chan->monitor->read_stream ) {
2704 /* XXX what does this do ? */
2705 #ifndef MONITOR_CONSTANT_DELAY
2706 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2708 jump = chan->outsmpl - chan->insmpl;
2709 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2710 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2711 chan->insmpl += jump + f->samples;
2713 chan->insmpl+= f->samples;
2715 int jump = chan->outsmpl - chan->insmpl;
2716 if (jump - MONITOR_DELAY >= 0) {
2717 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2718 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2719 chan->insmpl += jump;
2721 chan->insmpl += f->samples;
2723 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2724 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2725 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2729 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2730 f = &ast_null_frame;
2732 /* Run generator sitting on the line if timing device not available
2733 * and synchronous generation of outgoing frames is necessary */
2734 ast_read_generator_actions(chan, f);
2737 /* Just pass it on! */
2741 /* Make sure we always return NULL in the future */
2742 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2744 chan->hangupcause = cause;
2745 if (chan->generator)
2746 ast_deactivate_generator(chan);
2747 /* We no longer End the CDR here */
2750 /* High bit prints debugging */
2751 if (chan->fin & DEBUGCHAN_FLAG)
2752 ast_frame_dump(chan->name, f, "<<");
2753 chan->fin = FRAMECOUNT_INC(chan->fin);
2756 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2757 chan->generator->digit(chan, f->subclass);
2759 ast_channel_unlock(chan);
2763 int ast_internal_timing_enabled(struct ast_channel *chan)
2765 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2766 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2770 struct ast_frame *ast_read(struct ast_channel *chan)
2772 return __ast_read(chan, 0);
2775 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2777 return __ast_read(chan, 1);
2780 int ast_indicate(struct ast_channel *chan, int condition)
2782 return ast_indicate_data(chan, condition, NULL, 0);
2785 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2789 ast_channel_lock(chan);
2790 /* Stop if we're a zombie or need a soft hangup */
2791 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2792 ast_channel_unlock(chan);
2795 if (chan->tech->indicate)
2796 res = chan->tech->indicate(chan, condition, data, datalen);
2797 ast_channel_unlock(chan);
2798 if (!chan->tech->indicate || res) {
2800 * Device does not support (that) indication, lets fake
2801 * it by doing our own tone generation. (PM2002)
2804 ast_playtones_stop(chan);
2806 const struct ind_tone_zone_sound *ts = NULL;
2807 switch (condition) {
2808 case AST_CONTROL_RINGING:
2809 ts = ast_get_indication_tone(chan->zone, "ring");
2811 case AST_CONTROL_BUSY:
2812 ts = ast_get_indication_tone(chan->zone, "busy");
2814 case AST_CONTROL_CONGESTION:
2815 ts = ast_get_indication_tone(chan->zone, "congestion");
2818 if (ts && ts->data[0]) {
2819 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2820 ast_playtones_start(chan,0,ts->data, 1);
2822 chan->visible_indication = condition;
2823 } else if (condition == AST_CONTROL_PROGRESS) {
2824 /* ast_playtones_stop(chan); */
2825 } else if (condition == AST_CONTROL_PROCEEDING) {
2826 /* Do nothing, really */
2827 } else if (condition == AST_CONTROL_HOLD) {
2828 /* Do nothing.... */
2829 } else if (condition == AST_CONTROL_UNHOLD) {
2830 /* Do nothing.... */
2831 } else if (condition == AST_CONTROL_VIDUPDATE) {
2832 /* Do nothing.... */
2833 } else if (condition == AST_CONTROL_SRCUPDATE) {
2837 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2842 chan->visible_indication = condition;
2847 int ast_recvchar(struct ast_channel *chan, int timeout)
2850 char *buf = ast_recvtext(chan, timeout);
2852 return -1; /* error or timeout */
2853 c = *(unsigned char *)buf;
2858 char *ast_recvtext(struct ast_channel *chan, int timeout)
2864 struct ast_frame *f;
2865 if (ast_check_hangup(chan))
2867 res = ast_waitfor(chan, timeout);
2868 if (res <= 0) /* timeout or error */
2870 timeout = res; /* update timeout */
2873 break; /* no frame */
2874 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2875 done = 1; /* force a break */
2876 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2877 buf = ast_strndup((char *) f->data.ptr, f->datalen); /* dup and break */
2885 int ast_sendtext(struct ast_channel *chan, const char *text)
2888 /* Stop if we're a zombie or need a soft hangup */
2889 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2891 CHECK_BLOCKING(chan);
2892 if (chan->tech->send_text)
2893 res = chan->tech->send_text(chan, text);
2894 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2898 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2900 /* Device does not support DTMF tones, lets fake
2901 * it by doing our own generation. */
2902 static const char* dtmf_tones[] = {
2921 if (!chan->tech->send_digit_begin)
2924 if (!chan->tech->send_digit_begin(chan, digit))
2927 if (digit >= '0' && digit <='9')
2928 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2929 else if (digit >= 'A' && digit <= 'D')
2930 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2931 else if (digit == '*')
2932 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2933 else if (digit == '#')
2934 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2937 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2943 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2947 if (chan->tech->send_digit_end)
2948 res = chan->tech->send_digit_end(chan, digit, duration);
2950 if (res && chan->generator)
2951 ast_playtones_stop(chan);
2956 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2958 if (chan->tech->send_digit_begin) {
2959 ast_senddigit_begin(chan, digit);
2960 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2963 return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2966 int ast_prod(struct ast_channel *chan)
2968 struct ast_frame a = { AST_FRAME_VOICE };
2971 /* Send an empty audio frame to get things moving */
2972 if (chan->_state != AST_STATE_UP) {
2973 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2974 a.subclass = chan->rawwriteformat;
2975 a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
2977 if (ast_write(chan, &a))
2978 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2983 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2986 if (!chan->tech->write_video)
2988 res = ast_write(chan, fr);
2994 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2997 struct ast_frame *f = NULL, *f2 = NULL;
3000 /*Deadlock avoidance*/
3001 while(ast_channel_trylock(chan)) {
3002 /*cannot goto done since the channel is not locked*/
3004 ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
3009 /* Stop if we're a zombie or need a soft hangup */
3010 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
3013 /* Handle any pending masquerades */
3014 if (chan->masq && ast_do_masquerade(chan)) {
3015 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3019 res = 0; /* XXX explain, why 0 ? */
3022 if (chan->generatordata) {
3023 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
3024 ast_deactivate_generator(chan);
3026 if (fr->frametype == AST_FRAME_DTMF_END) {
3027 /* There is a generator running while we're in the middle of a digit.
3028 * It's probably inband DTMF, so go ahead and pass it so it can
3029 * stop the generator */
3030 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3031 ast_channel_unlock(chan);
3032 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3033 ast_channel_lock(chan);
3034 CHECK_BLOCKING(chan);
3035 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
3036 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
3037 res = (chan->tech->indicate == NULL) ? 0 :
3038 chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
3040 res = 0; /* XXX explain, why 0 ? */
3044 /* High bit prints debugging */
3045 if (chan->fout & DEBUGCHAN_FLAG)
3046 ast_frame_dump(chan->name, fr, ">>");
3047 CHECK_BLOCKING(chan);
3048 switch (fr->frametype) {
3049 case AST_FRAME_CONTROL:
3050 res = (chan->tech->indicate == NULL) ? 0 :
3051 chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
3053 case AST_FRAME_DTMF_BEGIN:
3054 if (chan->audiohooks) {
3055 struct ast_frame *old_frame = fr;
3056 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3057 if (old_frame != fr)
3060 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
3061 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3062 ast_channel_unlock(chan);
3063 res = ast_senddigit_begin(chan, fr->subclass);
3064 ast_channel_lock(chan);
3065 CHECK_BLOCKING(chan);
3067 case AST_FRAME_DTMF_END:
3068 if (chan->audiohooks) {
3069 struct ast_frame *old_frame = fr;
3070 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3071 if (old_frame != fr)
3074 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
3075 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3076 ast_channel_unlock(chan);
3077 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3078 ast_channel_lock(chan);
3079 CHECK_BLOCKING(chan);
3081 case AST_FRAME_TEXT:
3082 if (fr->subclass == AST_FORMAT_T140) {
3083 res = (chan->tech->write_text == NULL) ? 0 :
3084 chan->tech->write_text(chan, fr);
3086 res = (chan->tech->send_text == NULL) ? 0 :
3087 chan->tech->send_text(chan, (char *) fr->data.ptr);