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
);
1364 ast_mutex_destroy(&chan
->lock_dont_use
);
1366 ast_string_field_free_memory(chan
);
1368 AST_RWLIST_UNLOCK(&channels
);
1370 ast_devstate_changed_literal(AST_DEVICE_NOT_INUSE
, name
);
1373 struct ast_datastore
*ast_channel_datastore_alloc(const struct ast_datastore_info
*info
, const char *uid
)
1375 return ast_datastore_alloc(info
, uid
);
1378 int ast_channel_datastore_free(struct ast_datastore
*datastore
)
1380 return ast_datastore_free(datastore
);
1383 int ast_channel_datastore_inherit(struct ast_channel
*from
, struct ast_channel
*to
)
1385 struct ast_datastore
*datastore
= NULL
, *datastore2
;
1387 AST_LIST_TRAVERSE(&from
->datastores
, datastore
, entry
) {
1388 if (datastore
->inheritance
> 0) {
1389 datastore2
= ast_datastore_alloc(datastore
->info
, datastore
->uid
);
1391 datastore2
->data
= datastore
->info
->duplicate(datastore
->data
);
1392 datastore2
->inheritance
= datastore
->inheritance
== DATASTORE_INHERIT_FOREVER
? DATASTORE_INHERIT_FOREVER
: datastore
->inheritance
- 1;
1393 AST_LIST_INSERT_TAIL(&to
->datastores
, datastore2
, entry
);
1400 int ast_channel_datastore_add(struct ast_channel
*chan
, struct ast_datastore
*datastore
)
1404 AST_LIST_INSERT_HEAD(&chan
->datastores
, datastore
, entry
);
1409 int ast_channel_datastore_remove(struct ast_channel
*chan
, struct ast_datastore
*datastore
)
1411 return AST_LIST_REMOVE(&chan
->datastores
, datastore
, entry
) ? 0 : -1;
1414 struct ast_datastore
*ast_channel_datastore_find(struct ast_channel
*chan
, const struct ast_datastore_info
*info
, const char *uid
)
1416 struct ast_datastore
*datastore
= NULL
;
1421 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan
->datastores
, datastore
, entry
) {
1422 if (datastore
->info
!= info
) {
1427 /* matched by type only */
1431 if ((datastore
->uid
!= NULL
) && !strcasecmp(uid
, datastore
->uid
)) {
1432 /* Matched by type AND uid */
1436 AST_LIST_TRAVERSE_SAFE_END
;
1441 /*! Set the file descriptor on the channel */
1442 void ast_channel_set_fd(struct ast_channel
*chan
, int which
, int fd
)
1445 struct epoll_event ev
;
1446 struct ast_epoll_data
*aed
= NULL
;
1448 if (chan
->fds
[which
] > -1) {
1449 epoll_ctl(chan
->epfd
, EPOLL_CTL_DEL
, chan
->fds
[which
], &ev
);
1450 aed
= chan
->epfd_data
[which
];
1453 /* If this new fd is valid, add it to the epoll */
1455 if (!aed
&& (!(aed
= ast_calloc(1, sizeof(*aed
)))))
1458 chan
->epfd_data
[which
] = aed
;
1462 ev
.events
= EPOLLIN
| EPOLLPRI
| EPOLLERR
| EPOLLHUP
;
1464 epoll_ctl(chan
->epfd
, EPOLL_CTL_ADD
, fd
, &ev
);
1466 /* We don't have to keep around this epoll data structure now */
1468 chan
->epfd_data
[which
] = NULL
;
1471 chan
->fds
[which
] = fd
;
1475 /*! Add a channel to an optimized waitfor */
1476 void ast_poll_channel_add(struct ast_channel
*chan0
, struct ast_channel
*chan1
)
1479 struct epoll_event ev
;
1482 if (chan0
->epfd
== -1)
1485 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1486 for (i
= 0; i
< AST_MAX_FDS
; i
++) {
1487 if (chan1
->fds
[i
] == -1)
1489 ev
.events
= EPOLLIN
| EPOLLPRI
| EPOLLERR
| EPOLLHUP
;
1490 ev
.data
.ptr
= chan1
->epfd_data
[i
];
1491 epoll_ctl(chan0
->epfd
, EPOLL_CTL_ADD
, chan1
->fds
[i
], &ev
);
1498 /*! Delete a channel from an optimized waitfor */
1499 void ast_poll_channel_del(struct ast_channel
*chan0
, struct ast_channel
*chan1
)
1502 struct epoll_event ev
;
1505 if (chan0
->epfd
== -1)
1508 for (i
= 0; i
< AST_MAX_FDS
; i
++) {
1509 if (chan1
->fds
[i
] == -1)
1511 epoll_ctl(chan0
->epfd
, EPOLL_CTL_DEL
, chan1
->fds
[i
], &ev
);
1518 /*! \brief Softly hangup a channel, don't lock */
1519 int ast_softhangup_nolock(struct ast_channel
*chan
, int cause
)
1521 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan
->name
);
1522 /* Inform channel driver that we need to be hung up, if it cares */
1523 chan
->_softhangup
|= cause
;
1524 ast_queue_frame(chan
, &ast_null_frame
);
1525 /* Interrupt any poll call or such */
1526 if (ast_test_flag(chan
, AST_FLAG_BLOCKING
))
1527 pthread_kill(chan
->blocker
, SIGURG
);
1531 /*! \brief Softly hangup a channel, lock */
1532 int ast_softhangup(struct ast_channel
*chan
, int cause
)
1536 ast_channel_lock(chan
);
1537 res
= ast_softhangup_nolock(chan
, cause
);
1538 ast_channel_unlock(chan
);
1543 static void free_translation(struct ast_channel
*clonechan
)
1545 if (clonechan
->writetrans
)
1546 ast_translator_free_path(clonechan
->writetrans
);
1547 if (clonechan
->readtrans
)
1548 ast_translator_free_path(clonechan
->readtrans
);
1549 clonechan
->writetrans
= NULL
;
1550 clonechan
->readtrans
= NULL
;
1551 clonechan
->rawwriteformat
= clonechan
->nativeformats
;
1552 clonechan
->rawreadformat
= clonechan
->nativeformats
;
1555 /*! \brief Hangup a channel */
1556 int ast_hangup(struct ast_channel
*chan
)
1560 /* Don't actually hang up a channel that will masquerade as someone else, or
1561 if someone is going to masquerade as us */
1562 ast_channel_lock(chan
);
1564 if (chan
->audiohooks
) {
1565 ast_audiohook_detach_list(chan
->audiohooks
);
1566 chan
->audiohooks
= NULL
;
1569 ast_autoservice_stop(chan
);
1572 if (ast_do_masquerade(chan
))
1573 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
1577 ast_log(LOG_WARNING
, "%s getting hung up, but someone is trying to masq into us?!?\n", chan
->name
);
1578 ast_channel_unlock(chan
);
1581 /* If this channel is one which will be masqueraded into something,
1582 mark it as a zombie already, so we know to free it later */
1584 ast_set_flag(chan
, AST_FLAG_ZOMBIE
);
1585 ast_channel_unlock(chan
);
1588 free_translation(chan
);
1589 /* Close audio stream */
1591 ast_closestream(chan
->stream
);
1592 chan
->stream
= NULL
;
1594 /* Close video stream */
1595 if (chan
->vstream
) {
1596 ast_closestream(chan
->vstream
);
1597 chan
->vstream
= NULL
;
1600 sched_context_destroy(chan
->sched
);
1604 if (chan
->generatordata
) /* Clear any tone stuff remaining */
1605 if (chan
->generator
&& chan
->generator
->release
)
1606 chan
->generator
->release(chan
, chan
->generatordata
);
1607 chan
->generatordata
= NULL
;
1608 chan
->generator
= NULL
;
1609 if (ast_test_flag(chan
, AST_FLAG_BLOCKING
)) {
1610 ast_log(LOG_WARNING
, "Hard hangup called by thread %ld on %s, while fd "
1611 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1612 (long)pthread_self(), chan
->name
, (long)chan
->blocker
, chan
->blockproc
);
1613 ast_assert(ast_test_flag(chan
, AST_FLAG_BLOCKING
) == 0);
1615 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
)) {
1616 ast_debug(1, "Hanging up channel '%s'\n", chan
->name
);
1617 if (chan
->tech
->hangup
)
1618 res
= chan
->tech
->hangup(chan
);
1620 ast_debug(1, "Hanging up zombie '%s'\n", chan
->name
);
1623 ast_channel_unlock(chan
);
1624 manager_event(EVENT_FLAG_CALL
, "Hangup",
1627 "CallerIDNum: %s\r\n"
1628 "CallerIDName: %s\r\n"
1630 "Cause-txt: %s\r\n",
1633 S_OR(chan
->cid
.cid_num
, "<unknown>"),
1634 S_OR(chan
->cid
.cid_name
, "<unknown>"),
1636 ast_cause2str(chan
->hangupcause
)
1639 if (chan
->cdr
&& !ast_test_flag(chan
->cdr
, AST_CDR_FLAG_BRIDGED
) &&
1640 !ast_test_flag(chan
->cdr
, AST_CDR_FLAG_POST_DISABLED
) &&
1641 (chan
->cdr
->disposition
!= AST_CDR_NULL
|| ast_test_flag(chan
->cdr
, AST_CDR_FLAG_DIALED
))) {
1643 ast_cdr_end(chan
->cdr
);
1644 ast_cdr_detach(chan
->cdr
);
1647 ast_channel_free(chan
);
1652 #define ANSWER_WAIT_MS 500
1653 int __ast_answer(struct ast_channel
*chan
, unsigned int delay
)
1657 ast_channel_lock(chan
);
1659 /* You can't answer an outbound call */
1660 if (ast_test_flag(chan
, AST_FLAG_OUTGOING
)) {
1661 ast_channel_unlock(chan
);
1665 /* Stop if we're a zombie or need a soft hangup */
1666 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
1667 ast_channel_unlock(chan
);
1671 switch (chan
->_state
) {
1672 case AST_STATE_RINGING
:
1673 case AST_STATE_RING
:
1674 if (chan
->tech
->answer
)
1675 res
= chan
->tech
->answer(chan
);
1676 ast_setstate(chan
, AST_STATE_UP
);
1677 ast_cdr_answer(chan
->cdr
);
1679 ast_safe_sleep(chan
, delay
);
1681 struct ast_frame
*f
;
1682 int ms
= ANSWER_WAIT_MS
;
1684 /* 500 ms was the original delay here, so now
1685 * we cap our waiting at 500 ms
1687 ms
= ast_waitfor(chan
, ms
);
1689 ast_log(LOG_WARNING
, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan
->name
, strerror(errno
));
1694 ast_debug(2, "Didn't receive a voice frame from %s within %d ms of answering. Continuing anyway\n", chan
->name
, ANSWER_WAIT_MS
);
1699 if (!f
|| (f
->frametype
== AST_FRAME_CONTROL
&& f
->subclass
== AST_CONTROL_HANGUP
)) {
1701 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan
->name
);
1704 if (f
->frametype
== AST_FRAME_VOICE
) {
1716 chan
->visible_indication
= 0;
1717 ast_channel_unlock(chan
);
1722 int ast_answer(struct ast_channel
*chan
)
1724 return __ast_answer(chan
, 0);
1727 void ast_deactivate_generator(struct ast_channel
*chan
)
1729 ast_channel_lock(chan
);
1730 if (chan
->generatordata
) {
1731 if (chan
->generator
&& chan
->generator
->release
)
1732 chan
->generator
->release(chan
, chan
->generatordata
);
1733 chan
->generatordata
= NULL
;
1734 chan
->generator
= NULL
;
1735 ast_channel_set_fd(chan
, AST_GENERATOR_FD
, -1);
1736 ast_clear_flag(chan
, AST_FLAG_WRITE_INT
);
1737 ast_settimeout(chan
, 0, NULL
, NULL
);
1739 ast_channel_unlock(chan
);
1742 static int generator_force(const void *data
)
1744 /* Called if generator doesn't have data */
1747 int (*generate
)(struct ast_channel
*chan
, void *tmp
, int datalen
, int samples
) = NULL
;
1748 struct ast_channel
*chan
= (struct ast_channel
*)data
;
1750 ast_channel_lock(chan
);
1751 tmp
= chan
->generatordata
;
1752 chan
->generatordata
= NULL
;
1753 if (chan
->generator
)
1754 generate
= chan
->generator
->generate
;
1755 ast_channel_unlock(chan
);
1757 if (!tmp
|| !generate
)
1760 res
= generate(chan
, tmp
, 0, ast_format_rate(chan
->writeformat
& AST_FORMAT_AUDIO_MASK
) / 50);
1762 chan
->generatordata
= tmp
;
1765 ast_debug(1, "Auto-deactivating generator\n");
1766 ast_deactivate_generator(chan
);
1772 int ast_activate_generator(struct ast_channel
*chan
, struct ast_generator
*gen
, void *params
)
1776 ast_channel_lock(chan
);
1778 if (chan
->generatordata
) {
1779 if (chan
->generator
&& chan
->generator
->release
)
1780 chan
->generator
->release(chan
, chan
->generatordata
);
1781 chan
->generatordata
= NULL
;
1785 if (gen
->alloc
&& !(chan
->generatordata
= gen
->alloc(chan
, params
))) {
1790 ast_settimeout(chan
, 50, generator_force
, chan
);
1791 chan
->generator
= gen
;
1794 ast_channel_unlock(chan
);
1799 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1800 int ast_waitfor_n_fd(int *fds
, int n
, int *ms
, int *exception
)
1803 ast_waitfor_nandfds(NULL
, 0, fds
, n
, exception
, &winner
, ms
);
1807 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1809 static struct ast_channel
*ast_waitfor_nandfds_classic(struct ast_channel
**c
, int n
, int *fds
, int nfds
,
1810 int *exception
, int *outfd
, int *ms
)
1812 struct ast_channel
*ast_waitfor_nandfds(struct ast_channel
**c
, int n
, int *fds
, int nfds
,
1813 int *exception
, int *outfd
, int *ms
)
1816 struct timeval start
= { 0 , 0 };
1817 struct pollfd
*pfds
= NULL
;
1822 struct timeval now
= { 0, 0 };
1823 struct timeval whentohangup
= { 0, 0 }, diff
;
1824 struct ast_channel
*winner
= NULL
;
1830 if ((sz
= n
* AST_MAX_FDS
+ nfds
)) {
1831 pfds
= alloca(sizeof(*pfds
) * sz
);
1832 fdmap
= alloca(sizeof(*fdmap
) * sz
);
1840 /* Perform any pending masquerades */
1841 for (x
= 0; x
< n
; x
++) {
1842 ast_channel_lock(c
[x
]);
1843 if (c
[x
]->masq
&& ast_do_masquerade(c
[x
])) {
1844 ast_log(LOG_WARNING
, "Masquerade failed\n");
1846 ast_channel_unlock(c
[x
]);
1849 if (!ast_tvzero(c
[x
]->whentohangup
)) {
1850 if (ast_tvzero(whentohangup
))
1852 diff
= ast_tvsub(c
[x
]->whentohangup
, now
);
1853 if (diff
.tv_sec
< 0 || ast_tvzero(diff
)) {
1854 /* Should already be hungup */
1855 c
[x
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
1856 ast_channel_unlock(c
[x
]);
1859 if (ast_tvzero(whentohangup
) || ast_tvcmp(diff
, whentohangup
) < 0)
1860 whentohangup
= diff
;
1862 ast_channel_unlock(c
[x
]);
1864 /* Wait full interval */
1866 if (!ast_tvzero(whentohangup
)) {
1867 rms
= whentohangup
.tv_sec
* 1000 + whentohangup
.tv_usec
/ 1000; /* timeout in milliseconds */
1868 if (*ms
>= 0 && *ms
< rms
) /* original *ms still smaller */
1872 * Build the pollfd array, putting the channels' fds first,
1873 * followed by individual fds. Order is important because
1874 * individual fd's must have priority over channel fds.
1877 for (x
= 0; x
< n
; x
++) {
1878 for (y
= 0; y
< AST_MAX_FDS
; y
++) {
1879 fdmap
[max
].fdno
= y
; /* fd y is linked to this pfds */
1880 fdmap
[max
].chan
= x
; /* channel x is linked to this pfds */
1881 max
+= ast_add_fd(&pfds
[max
], c
[x
]->fds
[y
]);
1883 CHECK_BLOCKING(c
[x
]);
1885 /* Add the individual fds */
1886 for (x
= 0; x
< nfds
; x
++) {
1887 fdmap
[max
].chan
= -1;
1888 max
+= ast_add_fd(&pfds
[max
], fds
[x
]);
1892 start
= ast_tvnow();
1894 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1899 res
= poll(pfds
, max
, kbrms
);
1902 } while (!res
&& (rms
> 0));
1904 res
= poll(pfds
, max
, rms
);
1906 for (x
= 0; x
< n
; x
++)
1907 ast_clear_flag(c
[x
], AST_FLAG_BLOCKING
);
1908 if (res
< 0) { /* Simulate a timeout if we were interrupted */
1913 if (!ast_tvzero(whentohangup
)) { /* if we have a timeout, check who expired */
1915 for (x
= 0; x
< n
; x
++) {
1916 if (!ast_tvzero(c
[x
]->whentohangup
) && ast_tvcmp(c
[x
]->whentohangup
, now
) <= 0) {
1917 c
[x
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
1923 if (res
== 0) { /* no fd ready, reset timeout and done */
1924 *ms
= 0; /* XXX use 0 since we may not have an exact timeout. */
1928 * Then check if any channel or fd has a pending event.
1929 * Remember to check channels first and fds last, as they
1930 * must have priority on setting 'winner'
1932 for (x
= 0; x
< max
; x
++) {
1933 res
= pfds
[x
].revents
;
1936 if (fdmap
[x
].chan
>= 0) { /* this is a channel */
1937 winner
= c
[fdmap
[x
].chan
]; /* override previous winners */
1939 ast_set_flag(winner
, AST_FLAG_EXCEPTION
);
1941 ast_clear_flag(winner
, AST_FLAG_EXCEPTION
);
1942 winner
->fdno
= fdmap
[x
].fdno
;
1943 } else { /* this is an fd */
1945 *outfd
= pfds
[x
].fd
;
1947 *exception
= (res
& POLLPRI
) ? -1 : 0;
1952 *ms
-= ast_tvdiff_ms(ast_tvnow(), start
);
1960 static struct ast_channel
*ast_waitfor_nandfds_simple(struct ast_channel
*chan
, int *ms
)
1962 struct timeval start
= { 0 , 0 };
1964 struct epoll_event ev
[1];
1965 long diff
, rms
= *ms
;
1966 struct ast_channel
*winner
= NULL
;
1967 struct ast_epoll_data
*aed
= NULL
;
1969 ast_channel_lock(chan
);
1971 /* See if this channel needs to be masqueraded */
1972 if (chan
->masq
&& ast_do_masquerade(chan
)) {
1973 ast_log(LOG_WARNING
, "Failed to perform masquerade on %s\n", chan
->name
);
1975 ast_channel_unlock(chan
);
1979 /* Figure out their timeout */
1980 if (!ast_tvzero(chan
->whentohangup
)) {
1981 if ((diff
= ast_tvdiff_ms(chan
->whentohangup
, ast_tvnow())) < 0) {
1982 /* They should already be hungup! */
1983 chan
->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
1984 ast_channel_unlock(chan
);
1987 /* If this value is smaller then the current one... make it priority */
1992 ast_channel_unlock(chan
);
1994 /* Time to make this channel block... */
1995 CHECK_BLOCKING(chan
);
1998 start
= ast_tvnow();
2000 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2001 res
= epoll_wait(chan
->epfd
, ev
, 1, rms
);
2004 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2006 /* Simulate a timeout if we were interrupted */
2013 /* If this channel has a timeout see if it expired */
2014 if (!ast_tvzero(chan
->whentohangup
)) {
2015 if (ast_tvdiff_ms(ast_tvnow(), chan
->whentohangup
) >= 0) {
2016 chan
->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
2021 /* No fd ready, reset timeout and be done for now */
2027 /* See what events are pending */
2028 aed
= ev
[0].data
.ptr
;
2029 chan
->fdno
= aed
->which
;
2030 if (ev
[0].events
& EPOLLPRI
)
2031 ast_set_flag(chan
, AST_FLAG_EXCEPTION
);
2033 ast_clear_flag(chan
, AST_FLAG_EXCEPTION
);
2036 *ms
-= ast_tvdiff_ms(ast_tvnow(), start
);
2044 static struct ast_channel
*ast_waitfor_nandfds_complex(struct ast_channel
**c
, int n
, int *ms
)
2046 struct timeval start
= { 0 , 0 };
2048 struct epoll_event ev
[25] = { { 0, } };
2049 struct timeval now
= { 0, 0 };
2050 long whentohangup
= 0, diff
= 0, rms
= *ms
;
2051 struct ast_channel
*winner
= NULL
;
2053 for (i
= 0; i
< n
; i
++) {
2054 ast_channel_lock(c
[i
]);
2055 if (c
[i
]->masq
&& ast_do_masquerade(c
[i
])) {
2056 ast_log(LOG_WARNING
, "Masquerade failed\n");
2058 ast_channel_unlock(c
[i
]);
2061 if (!ast_tvzero(c
[i
]->whentohangup
)) {
2062 if (whentohangup
== 0)
2064 if ((diff
= ast_tvdiff_ms(c
[i
]->whentohangup
, now
)) < 0) {
2065 c
[i
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
2066 ast_channel_unlock(c
[i
]);
2069 if (!whentohangup
|| whentohangup
> diff
)
2070 whentohangup
= diff
;
2072 ast_channel_unlock(c
[i
]);
2073 CHECK_BLOCKING(c
[i
]);
2079 if (*ms
>= 0 && *ms
< rms
)
2084 start
= ast_tvnow();
2086 res
= epoll_wait(c
[0]->epfd
, ev
, 25, rms
);
2088 for (i
= 0; i
< n
; i
++)
2089 ast_clear_flag(c
[i
], AST_FLAG_BLOCKING
);
2099 for (i
= 0; i
< n
; i
++) {
2100 if (!ast_tvzero(c
[i
]->whentohangup
) && ast_tvdiff_ms(now
, c
[i
]->whentohangup
) >= 0) {
2101 c
[i
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
2113 for (i
= 0; i
< res
; i
++) {
2114 struct ast_epoll_data
*aed
= ev
[i
].data
.ptr
;
2116 if (!ev
[i
].events
|| !aed
)
2120 if (ev
[i
].events
& EPOLLPRI
)
2121 ast_set_flag(winner
, AST_FLAG_EXCEPTION
);
2123 ast_clear_flag(winner
, AST_FLAG_EXCEPTION
);
2124 winner
->fdno
= aed
->which
;
2128 *ms
-= ast_tvdiff_ms(ast_tvnow(), start
);
2136 struct ast_channel
*ast_waitfor_nandfds(struct ast_channel
**c
, int n
, int *fds
, int nfds
,
2137 int *exception
, int *outfd
, int *ms
)
2139 /* Clear all provided values in one place. */
2145 /* If no epoll file descriptor is available resort to classic nandfds */
2146 if (!n
|| nfds
|| c
[0]->epfd
== -1)
2147 return ast_waitfor_nandfds_classic(c
, n
, fds
, nfds
, exception
, outfd
, ms
);
2148 else if (!nfds
&& n
== 1)
2149 return ast_waitfor_nandfds_simple(c
[0], ms
);
2151 return ast_waitfor_nandfds_complex(c
, n
, ms
);
2155 struct ast_channel
*ast_waitfor_n(struct ast_channel
**c
, int n
, int *ms
)
2157 return ast_waitfor_nandfds(c
, n
, NULL
, 0, NULL
, NULL
, ms
);
2160 int ast_waitfor(struct ast_channel
*c
, int ms
)
2162 int oldms
= ms
; /* -1 if no timeout */
2164 ast_waitfor_nandfds(&c
, 1, NULL
, 0, NULL
, NULL
, &ms
);
2165 if ((ms
< 0) && (oldms
< 0))
2170 /* XXX never to be called with ms = -1 */
2171 int ast_waitfordigit(struct ast_channel
*c
, int ms
)
2173 return ast_waitfordigit_full(c
, ms
, -1, -1);
2176 int ast_settimeout(struct ast_channel
*c
, unsigned int rate
, int (*func
)(const void *data
), void *data
)
2179 unsigned int real_rate
= rate
, max_rate
;
2181 if (c
->timingfd
== -1) {
2190 if (rate
&& rate
> (max_rate
= ast_timer_get_max_rate(c
->timingfd
))) {
2191 real_rate
= max_rate
;
2194 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate
, real_rate
);
2196 res
= ast_timer_set_rate(c
->timingfd
, real_rate
);
2198 c
->timingfunc
= func
;
2199 c
->timingdata
= data
;
2204 int ast_waitfordigit_full(struct ast_channel
*c
, int ms
, int audiofd
, int cmdfd
)
2206 /* Stop if we're a zombie or need a soft hangup */
2207 if (ast_test_flag(c
, AST_FLAG_ZOMBIE
) || ast_check_hangup(c
))
2210 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2211 ast_set_flag(c
, AST_FLAG_END_DTMF_ONLY
);
2213 /* Wait for a digit, no more than ms milliseconds total. */
2216 struct ast_channel
*rchan
;
2220 rchan
= ast_waitfor_nandfds(&c
, 1, &cmdfd
, (cmdfd
> -1) ? 1 : 0, NULL
, &outfd
, &ms
);
2222 if (!rchan
&& outfd
< 0 && ms
) {
2223 if (errno
== 0 || errno
== EINTR
)
2225 ast_log(LOG_WARNING
, "Wait failed (%s)\n", strerror(errno
));
2226 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
2228 } else if (outfd
> -1) {
2229 /* The FD we were watching has something waiting */
2230 ast_log(LOG_WARNING
, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2231 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
2235 struct ast_frame
*f
= ast_read(c
);
2239 switch (f
->frametype
) {
2240 case AST_FRAME_DTMF_BEGIN
:
2242 case AST_FRAME_DTMF_END
:
2245 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
2247 case AST_FRAME_CONTROL
:
2248 switch (f
->subclass
) {
2249 case AST_CONTROL_HANGUP
:
2251 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
2253 case AST_CONTROL_RINGING
:
2254 case AST_CONTROL_ANSWER
:
2255 case AST_CONTROL_SRCUPDATE
:
2259 ast_log(LOG_WARNING
, "Unexpected control subclass '%d'\n", f
->subclass
);
2263 case AST_FRAME_VOICE
:
2264 /* Write audio if appropriate */
2266 write(audiofd
, f
->data
.ptr
, f
->datalen
);
2275 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
2277 return 0; /* Time is up */
2280 static void send_dtmf_event(const struct ast_channel
*chan
, const char *direction
, const char digit
, const char *begin
, const char *end
)
2282 manager_event(EVENT_FLAG_DTMF
,
2290 chan
->name
, chan
->uniqueid
, digit
, direction
, begin
, end
);
2293 static void ast_read_generator_actions(struct ast_channel
*chan
, struct ast_frame
*f
)
2295 if (chan
->generatordata
&& !ast_internal_timing_enabled(chan
)) {
2296 void *tmp
= chan
->generatordata
;
2297 int (*generate
)(struct ast_channel
*chan
, void *tmp
, int datalen
, int samples
) = NULL
;
2301 if (chan
->timingfunc
) {
2302 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2303 ast_settimeout(chan
, 0, NULL
, NULL
);
2306 chan
->generatordata
= NULL
; /* reset, to let writes go through */
2308 if (f
->subclass
!= chan
->writeformat
) {
2310 factor
= ((float) ast_format_rate(chan
->writeformat
)) / ((float) ast_format_rate(f
->subclass
));
2311 samples
= (int) ( ((float) f
->samples
) * factor
);
2313 samples
= f
->samples
;
2316 if (chan
->generator
->generate
) {
2317 generate
= chan
->generator
->generate
;
2319 /* This unlock is here based on two assumptions that hold true at this point in the
2320 * code. 1) this function is only called from within __ast_read() and 2) all generators
2321 * call ast_write() in their generate callback.
2323 * The reason this is added is so that when ast_write is called, the lock that occurs
2324 * there will not recursively lock the channel. Doing this will cause intended deadlock
2325 * avoidance not to work in deeper functions
2327 ast_channel_unlock(chan
);
2328 res
= generate(chan
, tmp
, f
->datalen
, samples
);
2329 ast_channel_lock(chan
);
2330 chan
->generatordata
= tmp
;
2332 ast_debug(1, "Auto-deactivating generator\n");
2333 ast_deactivate_generator(chan
);
2336 } else if (f
->frametype
== AST_FRAME_CNG
) {
2337 if (chan
->generator
&& !chan
->timingfunc
&& (chan
->timingfd
> -1)) {
2338 ast_debug(1, "Generator got CNG, switching to timed mode\n");
2339 ast_settimeout(chan
, 50, generator_force
, chan
);
2344 static struct ast_frame
*__ast_read(struct ast_channel
*chan
, int dropaudio
)
2346 struct ast_frame
*f
= NULL
; /* the return value */
2349 int count
= 0, cause
= 0;
2351 /* this function is very long so make sure there is only one return
2352 * point at the end (there are only two exceptions to this).
2354 while(ast_channel_trylock(chan
)) {
2356 /*cannot goto done since the channel is not locked*/
2357 return &ast_null_frame
;
2362 if (ast_do_masquerade(chan
))
2363 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
2365 f
= &ast_null_frame
;
2369 /* Stop if we're a zombie or need a soft hangup */
2370 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
2371 if (chan
->generator
)
2372 ast_deactivate_generator(chan
);
2375 prestate
= chan
->_state
;
2377 if (!ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
| AST_FLAG_EMULATE_DTMF
| AST_FLAG_IN_DTMF
) &&
2378 !ast_strlen_zero(chan
->dtmfq
) &&
2379 (ast_tvzero(chan
->dtmf_tv
) || ast_tvdiff_ms(ast_tvnow(), chan
->dtmf_tv
) > AST_MIN_DTMF_GAP
) ) {
2380 /* We have DTMF that has been deferred. Return it now */
2381 chan
->dtmff
.subclass
= chan
->dtmfq
[0];
2382 /* Drop first digit from the buffer */
2383 memmove(chan
->dtmfq
, chan
->dtmfq
+ 1, sizeof(chan
->dtmfq
) - 1);
2385 if (ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
)) {
2386 ast_log(LOG_DTMF
, "DTMF end emulation of '%c' queued on %s\n", f
->subclass
, chan
->name
);
2387 chan
->dtmff
.frametype
= AST_FRAME_DTMF_END
;
2389 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
);
2390 chan
->dtmff
.frametype
= AST_FRAME_DTMF_BEGIN
;
2391 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2392 chan
->emulate_dtmf_digit
= f
->subclass
;
2393 chan
->emulate_dtmf_duration
= AST_DEFAULT_EMULATE_DTMF_DURATION
;
2395 chan
->dtmf_tv
= ast_tvnow();
2399 /* Read and ignore anything on the alertpipe, but read only
2400 one sizeof(blah) per frame that we send from it */
2401 if (chan
->alertpipe
[0] > -1) {
2402 int flags
= fcntl(chan
->alertpipe
[0], F_GETFL
);
2403 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2404 * which immediately causes a deadlock scenario. Detect and prevent this. */
2405 if ((flags
& O_NONBLOCK
) == 0) {
2406 ast_log(LOG_ERROR
, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan
->name
);
2407 if (fcntl(chan
->alertpipe
[0], F_SETFL
, flags
| O_NONBLOCK
) < 0) {
2408 ast_log(LOG_WARNING
, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno
, strerror(errno
));
2409 f
= &ast_null_frame
;
2413 read(chan
->alertpipe
[0], &blah
, sizeof(blah
));
2416 if (chan
->timingfd
> -1 && chan
->fdno
== AST_TIMING_FD
) {
2417 enum ast_timing_event res
;
2419 ast_clear_flag(chan
, AST_FLAG_EXCEPTION
);
2421 res
= ast_timer_get_event(chan
->timingfd
);
2424 case AST_TIMING_EVENT_EXPIRED
:
2425 ast_timer_ack(chan
->timingfd
, 1);
2427 if (chan
->timingfunc
) {
2428 /* save a copy of func/data before unlocking the channel */
2429 int (*func
)(const void *) = chan
->timingfunc
;
2430 void *data
= chan
->timingdata
;
2431 ast_channel_unlock(chan
);
2434 ast_timer_set_rate(chan
->timingfd
, 0);
2435 ast_channel_unlock(chan
);
2438 /* cannot 'goto done' because the channel is already unlocked */
2439 return &ast_null_frame
;
2441 case AST_TIMING_EVENT_CONTINUOUS
:
2442 if (AST_LIST_EMPTY(&chan
->readq
) ||
2443 !AST_LIST_NEXT(AST_LIST_FIRST(&chan
->readq
), frame_list
)) {
2444 ast_timer_disable_continuous(chan
->timingfd
);
2449 } else if (chan
->fds
[AST_GENERATOR_FD
] > -1 && chan
->fdno
== AST_GENERATOR_FD
) {
2450 /* if the AST_GENERATOR_FD is set, call the generator with args
2451 * set to -1 so it can do whatever it needs to.
2453 void *tmp
= chan
->generatordata
;
2454 chan
->generatordata
= NULL
; /* reset to let ast_write get through */
2455 chan
->generator
->generate(chan
, tmp
, -1, -1);
2456 chan
->generatordata
= tmp
;
2457 f
= &ast_null_frame
;
2461 /* Check for pending read queue */
2462 if (!AST_LIST_EMPTY(&chan
->readq
)) {
2463 f
= AST_LIST_REMOVE_HEAD(&chan
->readq
, frame_list
);
2464 /* Interpret hangup and return NULL */
2465 /* XXX why not the same for frames from the channel ? */
2466 if (f
->frametype
== AST_FRAME_CONTROL
&& f
->subclass
== AST_CONTROL_HANGUP
) {
2467 cause
= f
->data
.uint32
;
2472 chan
->blocker
= pthread_self();
2473 if (ast_test_flag(chan
, AST_FLAG_EXCEPTION
)) {
2474 if (chan
->tech
->exception
)
2475 f
= chan
->tech
->exception(chan
);
2477 ast_log(LOG_WARNING
, "Exception flag set on '%s', but no exception handler\n", chan
->name
);
2478 f
= &ast_null_frame
;
2480 /* Clear the exception flag */
2481 ast_clear_flag(chan
, AST_FLAG_EXCEPTION
);
2482 } else if (chan
->tech
->read
)
2483 f
= chan
->tech
->read(chan
);
2485 ast_log(LOG_WARNING
, "No read routine on channel %s\n", chan
->name
);
2489 /* if the channel driver returned more than one frame, stuff the excess
2490 into the readq for the next ast_read call (note that we can safely assume
2491 that the readq is empty, because otherwise we would not have called into
2492 the channel driver and f would be only a single frame)
2494 if (AST_LIST_NEXT(f
, frame_list
)) {
2495 AST_LIST_HEAD_SET_NOLOCK(&chan
->readq
, AST_LIST_NEXT(f
, frame_list
));
2496 AST_LIST_NEXT(f
, frame_list
) = NULL
;
2499 switch (f
->frametype
) {
2500 case AST_FRAME_CONTROL
:
2501 if (f
->subclass
== AST_CONTROL_ANSWER
) {
2502 if (!ast_test_flag(chan
, AST_FLAG_OUTGOING
)) {
2503 ast_debug(1, "Ignoring answer on an inbound call!\n");
2505 f
= &ast_null_frame
;
2506 } else if (prestate
== AST_STATE_UP
) {
2507 ast_debug(1, "Dropping duplicate answer!\n");
2509 f
= &ast_null_frame
;
2511 /* Answer the CDR */
2512 ast_setstate(chan
, AST_STATE_UP
);
2513 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2517 case AST_FRAME_DTMF_END
:
2518 send_dtmf_event(chan
, "Received", f
->subclass
, "No", "Yes");
2519 ast_log(LOG_DTMF
, "DTMF end '%c' received on %s, duration %ld ms\n", f
->subclass
, chan
->name
, f
->len
);
2520 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2521 * However, only let emulation be forced if the other end cares about BEGIN frames */
2522 if ( ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
) ||
2523 (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
)) ) {
2524 if (strlen(chan
->dtmfq
) < sizeof(chan
->dtmfq
) - 2) {
2525 ast_log(LOG_DTMF
, "DTMF end '%c' put into dtmf queue on %s\n", f
->subclass
, chan
->name
);
2526 chan
->dtmfq
[strlen(chan
->dtmfq
)] = f
->subclass
;
2528 ast_log(LOG_WARNING
, "Dropping deferred DTMF digits on %s\n", chan
->name
);
2530 f
= &ast_null_frame
;
2531 } else if (!ast_test_flag(chan
, AST_FLAG_IN_DTMF
| AST_FLAG_END_DTMF_ONLY
)) {
2532 if (!ast_tvzero(chan
->dtmf_tv
) &&
2533 ast_tvdiff_ms(ast_tvnow(), chan
->dtmf_tv
) < AST_MIN_DTMF_GAP
) {
2534 /* If it hasn't been long enough, defer this digit */
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
;
2543 /* There was no begin, turn this into a begin and send the end later */
2544 f
->frametype
= AST_FRAME_DTMF_BEGIN
;
2545 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2546 chan
->emulate_dtmf_digit
= f
->subclass
;
2547 chan
->dtmf_tv
= ast_tvnow();
2549 if (f
->len
> AST_MIN_DTMF_DURATION
)
2550 chan
->emulate_dtmf_duration
= f
->len
;
2552 chan
->emulate_dtmf_duration
= AST_MIN_DTMF_DURATION
;
2554 chan
->emulate_dtmf_duration
= AST_DEFAULT_EMULATE_DTMF_DURATION
;
2555 ast_log(LOG_DTMF
, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f
->subclass
, chan
->emulate_dtmf_duration
, chan
->name
);
2557 if (chan
->audiohooks
) {
2558 struct ast_frame
*old_frame
= f
;
2560 * \todo XXX It is possible to write a digit to the audiohook twice
2561 * if the digit was originally read while the channel was in autoservice. */
2562 f
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_READ
, f
);
2564 ast_frfree(old_frame
);
2567 struct timeval now
= ast_tvnow();
2568 if (ast_test_flag(chan
, AST_FLAG_IN_DTMF
)) {
2569 ast_log(LOG_DTMF
, "DTMF end accepted with begin '%c' on %s\n", f
->subclass
, chan
->name
);
2570 ast_clear_flag(chan
, AST_FLAG_IN_DTMF
);
2572 f
->len
= ast_tvdiff_ms(now
, chan
->dtmf_tv
);
2573 } else if (!f
->len
) {
2574 ast_log(LOG_DTMF
, "DTMF end accepted without begin '%c' on %s\n", f
->subclass
, chan
->name
);
2575 f
->len
= AST_MIN_DTMF_DURATION
;
2577 if (f
->len
< AST_MIN_DTMF_DURATION
&& !ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
)) {
2578 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
);
2579 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2580 chan
->emulate_dtmf_digit
= f
->subclass
;
2581 chan
->emulate_dtmf_duration
= AST_MIN_DTMF_DURATION
- f
->len
;
2583 f
= &ast_null_frame
;
2585 ast_log(LOG_DTMF
, "DTMF end passthrough '%c' on %s\n", f
->subclass
, chan
->name
);
2586 if (f
->len
< AST_MIN_DTMF_DURATION
) {
2587 f
->len
= AST_MIN_DTMF_DURATION
;
2589 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
);
2599 case AST_FRAME_DTMF_BEGIN
:
2600 send_dtmf_event(chan
, "Received", f
->subclass
, "Yes", "No");
2601 ast_log(LOG_DTMF
, "DTMF begin '%c' received on %s\n", f
->subclass
, chan
->name
);
2602 if ( ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
| AST_FLAG_END_DTMF_ONLY
| AST_FLAG_EMULATE_DTMF
) ||
2603 (!ast_tvzero(chan
->dtmf_tv
) &&
2604 ast_tvdiff_ms(ast_tvnow(), chan
->dtmf_tv
) < AST_MIN_DTMF_GAP
) ) {
2605 ast_log(LOG_DTMF
, "DTMF begin ignored '%c' on %s\n", f
->subclass
, chan
->name
);
2607 f
= &ast_null_frame
;
2609 ast_set_flag(chan
, AST_FLAG_IN_DTMF
);
2610 chan
->dtmf_tv
= ast_tvnow();
2611 ast_log(LOG_DTMF
, "DTMF begin passthrough '%c' on %s\n", f
->subclass
, chan
->name
);
2614 case AST_FRAME_NULL
:
2615 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2616 * is reached , because we want to make sure we pass at least one
2617 * voice frame through before starting the next digit, to ensure a gap
2618 * between DTMF digits. */
2619 if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
)) {
2620 struct timeval now
= ast_tvnow();
2621 if (!chan
->emulate_dtmf_duration
) {
2622 ast_clear_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2623 chan
->emulate_dtmf_digit
= 0;
2624 } else if (ast_tvdiff_ms(now
, chan
->dtmf_tv
) >= chan
->emulate_dtmf_duration
) {
2625 chan
->emulate_dtmf_duration
= 0;
2628 f
->frametype
= AST_FRAME_DTMF_END
;
2629 f
->subclass
= chan
->emulate_dtmf_digit
;
2630 f
->len
= ast_tvdiff_ms(now
, chan
->dtmf_tv
);
2631 chan
->dtmf_tv
= now
;
2632 ast_clear_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2633 chan
->emulate_dtmf_digit
= 0;
2634 ast_log(LOG_DTMF
, "DTMF end emulation of '%c' queued on %s\n", f
->subclass
, chan
->name
);
2638 case AST_FRAME_VOICE
:
2639 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2640 * is reached , because we want to make sure we pass at least one
2641 * voice frame through before starting the next digit, to ensure a gap
2642 * between DTMF digits. */
2643 if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !chan
->emulate_dtmf_duration
) {
2644 ast_clear_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2645 chan
->emulate_dtmf_digit
= 0;
2648 if (dropaudio
|| ast_test_flag(chan
, AST_FLAG_IN_DTMF
)) {
2650 ast_read_generator_actions(chan
, f
);
2652 f
= &ast_null_frame
;
2655 if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !ast_test_flag(chan
, AST_FLAG_IN_DTMF
)) {
2656 struct timeval now
= ast_tvnow();
2657 if (ast_tvdiff_ms(now
, chan
->dtmf_tv
) >= chan
->emulate_dtmf_duration
) {
2658 chan
->emulate_dtmf_duration
= 0;
2661 f
->frametype
= AST_FRAME_DTMF_END
;
2662 f
->subclass
= chan
->emulate_dtmf_digit
;
2663 f
->len
= ast_tvdiff_ms(now
, chan
->dtmf_tv
);
2664 chan
->dtmf_tv
= now
;
2665 if (chan
->audiohooks
) {
2666 struct ast_frame
*old_frame
= f
;
2667 f
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_READ
, f
);
2669 ast_frfree(old_frame
);
2671 ast_log(LOG_DTMF
, "DTMF end emulation of '%c' queued on %s\n", f
->subclass
, chan
->name
);
2673 /* Drop voice frames while we're still in the middle of the digit */
2675 f
= &ast_null_frame
;
2677 } else if ((f
->frametype
== AST_FRAME_VOICE
) && !(f
->subclass
& chan
->nativeformats
)) {
2678 /* This frame is not one of the current native formats -- drop it on the floor */
2680 ast_log(LOG_NOTICE
, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2681 chan
->name
, ast_getformatname(f
->subclass
), ast_getformatname_multiple(to
, sizeof(to
), chan
->nativeformats
));
2683 f
= &ast_null_frame
;
2684 } else if ((f
->frametype
== AST_FRAME_VOICE
)) {
2685 /* Send frame to audiohooks if present */
2686 if (chan
->audiohooks
) {
2687 struct ast_frame
*old_frame
= f
;
2688 f
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_READ
, f
);
2690 ast_frfree(old_frame
);
2692 if (chan
->monitor
&& chan
->monitor
->read_stream
) {
2693 /* XXX what does this do ? */
2694 #ifndef MONITOR_CONSTANT_DELAY
2695 int jump
= chan
->outsmpl
- chan
->insmpl
- 4 * f
->samples
;
2697 jump
= chan
->outsmpl
- chan
->insmpl
;
2698 if (ast_seekstream(chan
->monitor
->read_stream
, jump
, SEEK_FORCECUR
) == -1)
2699 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2700 chan
->insmpl
+= jump
+ f
->samples
;
2702 chan
->insmpl
+= f
->samples
;
2704 int jump
= chan
->outsmpl
- chan
->insmpl
;
2705 if (jump
- MONITOR_DELAY
>= 0) {
2706 if (ast_seekstream(chan
->monitor
->read_stream
, jump
- f
->samples
, SEEK_FORCECUR
) == -1)
2707 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2708 chan
->insmpl
+= jump
;
2710 chan
->insmpl
+= f
->samples
;
2712 if (chan
->monitor
->state
== AST_MONITOR_RUNNING
) {
2713 if (ast_writestream(chan
->monitor
->read_stream
, f
) < 0)
2714 ast_log(LOG_WARNING
, "Failed to write data to channel monitor read stream\n");
2718 if (chan
->readtrans
&& (f
= ast_translate(chan
->readtrans
, f
, 1)) == NULL
)
2719 f
= &ast_null_frame
;
2721 /* Run generator sitting on the line if timing device not available
2722 * and synchronous generation of outgoing frames is necessary */
2723 ast_read_generator_actions(chan
, f
);
2726 /* Just pass it on! */
2730 /* Make sure we always return NULL in the future */
2731 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
2733 chan
->hangupcause
= cause
;
2734 if (chan
->generator
)
2735 ast_deactivate_generator(chan
);
2736 /* We no longer End the CDR here */
2739 /* High bit prints debugging */
2740 if (chan
->fin
& DEBUGCHAN_FLAG
)
2741 ast_frame_dump(chan
->name
, f
, "<<");
2742 chan
->fin
= FRAMECOUNT_INC(chan
->fin
);
2745 if (chan
->music_state
&& chan
->generator
&& chan
->generator
->digit
&& f
&& f
->frametype
== AST_FRAME_DTMF_END
)
2746 chan
->generator
->digit(chan
, f
->subclass
);
2748 ast_channel_unlock(chan
);
2752 int ast_internal_timing_enabled(struct ast_channel
*chan
)
2754 int ret
= ast_opt_internal_timing
&& chan
->timingfd
> -1;
2755 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret
? "enabled": "disabled", ast_opt_internal_timing
, chan
->timingfd
);
2759 struct ast_frame
*ast_read(struct ast_channel
*chan
)
2761 return __ast_read(chan
, 0);
2764 struct ast_frame
*ast_read_noaudio(struct ast_channel
*chan
)
2766 return __ast_read(chan
, 1);
2769 int ast_indicate(struct ast_channel
*chan
, int condition
)
2771 return ast_indicate_data(chan
, condition
, NULL
, 0);
2774 int ast_indicate_data(struct ast_channel
*chan
, int condition
, const void *data
, size_t datalen
)
2778 ast_channel_lock(chan
);
2779 /* Stop if we're a zombie or need a soft hangup */
2780 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
2781 ast_channel_unlock(chan
);
2784 if (chan
->tech
->indicate
)
2785 res
= chan
->tech
->indicate(chan
, condition
, data
, datalen
);
2786 ast_channel_unlock(chan
);
2787 if (!chan
->tech
->indicate
|| res
) {
2789 * Device does not support (that) indication, lets fake
2790 * it by doing our own tone generation. (PM2002)
2793 ast_playtones_stop(chan
);
2795 const struct ind_tone_zone_sound
*ts
= NULL
;
2796 switch (condition
) {
2797 case AST_CONTROL_RINGING
:
2798 ts
= ast_get_indication_tone(chan
->zone
, "ring");
2800 case AST_CONTROL_BUSY
:
2801 ts
= ast_get_indication_tone(chan
->zone
, "busy");
2803 case AST_CONTROL_CONGESTION
:
2804 ts
= ast_get_indication_tone(chan
->zone
, "congestion");
2807 if (ts
&& ts
->data
[0]) {
2808 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan
->name
, condition
);
2809 ast_playtones_start(chan
,0,ts
->data
, 1);
2811 chan
->visible_indication
= condition
;
2812 } else if (condition
== AST_CONTROL_PROGRESS
) {
2813 /* ast_playtones_stop(chan); */
2814 } else if (condition
== AST_CONTROL_PROCEEDING
) {
2815 /* Do nothing, really */
2816 } else if (condition
== AST_CONTROL_HOLD
) {
2817 /* Do nothing.... */
2818 } else if (condition
== AST_CONTROL_UNHOLD
) {
2819 /* Do nothing.... */
2820 } else if (condition
== AST_CONTROL_VIDUPDATE
) {
2821 /* Do nothing.... */
2822 } else if (condition
== AST_CONTROL_SRCUPDATE
) {
2826 ast_log(LOG_WARNING
, "Unable to handle indication %d for '%s'\n", condition
, chan
->name
);
2831 chan
->visible_indication
= condition
;
2836 int ast_recvchar(struct ast_channel
*chan
, int timeout
)
2839 char *buf
= ast_recvtext(chan
, timeout
);
2841 return -1; /* error or timeout */
2842 c
= *(unsigned char *)buf
;
2847 char *ast_recvtext(struct ast_channel
*chan
, int timeout
)
2853 struct ast_frame
*f
;
2854 if (ast_check_hangup(chan
))
2856 res
= ast_waitfor(chan
, timeout
);
2857 if (res
<= 0) /* timeout or error */
2859 timeout
= res
; /* update timeout */
2862 break; /* no frame */
2863 if (f
->frametype
== AST_FRAME_CONTROL
&& f
->subclass
== AST_CONTROL_HANGUP
)
2864 done
= 1; /* force a break */
2865 else if (f
->frametype
== AST_FRAME_TEXT
) { /* what we want */
2866 buf
= ast_strndup((char *) f
->data
.ptr
, f
->datalen
); /* dup and break */
2874 int ast_sendtext(struct ast_channel
*chan
, const char *text
)
2877 /* Stop if we're a zombie or need a soft hangup */
2878 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
))
2880 CHECK_BLOCKING(chan
);
2881 if (chan
->tech
->send_text
)
2882 res
= chan
->tech
->send_text(chan
, text
);
2883 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2887 int ast_senddigit_begin(struct ast_channel
*chan
, char digit
)
2889 /* Device does not support DTMF tones, lets fake
2890 * it by doing our own generation. */
2891 static const char* dtmf_tones
[] = {
2910 if (!chan
->tech
->send_digit_begin
)
2913 if (!chan
->tech
->send_digit_begin(chan
, digit
))
2916 if (digit
>= '0' && digit
<='9')
2917 ast_playtones_start(chan
, 0, dtmf_tones
[digit
-'0'], 0);
2918 else if (digit
>= 'A' && digit
<= 'D')
2919 ast_playtones_start(chan
, 0, dtmf_tones
[digit
-'A'+10], 0);
2920 else if (digit
== '*')
2921 ast_playtones_start(chan
, 0, dtmf_tones
[14], 0);
2922 else if (digit
== '#')
2923 ast_playtones_start(chan
, 0, dtmf_tones
[15], 0);
2926 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit
, chan
->name
);
2932 int ast_senddigit_end(struct ast_channel
*chan
, char digit
, unsigned int duration
)
2936 if (chan
->tech
->send_digit_end
)
2937 res
= chan
->tech
->send_digit_end(chan
, digit
, duration
);
2939 if (res
&& chan
->generator
)
2940 ast_playtones_stop(chan
);
2945 int ast_senddigit(struct ast_channel
*chan
, char digit
, unsigned int duration
)
2947 if (chan
->tech
->send_digit_begin
) {
2948 ast_senddigit_begin(chan
, digit
);
2949 ast_safe_sleep(chan
, (duration
>= AST_DEFAULT_EMULATE_DTMF_DURATION
? duration
: AST_DEFAULT_EMULATE_DTMF_DURATION
));
2952 return ast_senddigit_end(chan
, digit
, (duration
>= AST_DEFAULT_EMULATE_DTMF_DURATION
? duration
: AST_DEFAULT_EMULATE_DTMF_DURATION
));
2955 int ast_prod(struct ast_channel
*chan
)
2957 struct ast_frame a
= { AST_FRAME_VOICE
};
2960 /* Send an empty audio frame to get things moving */
2961 if (chan
->_state
!= AST_STATE_UP
) {
2962 ast_debug(1, "Prodding channel '%s'\n", chan
->name
);
2963 a
.subclass
= chan
->rawwriteformat
;
2964 a
.data
.ptr
= nothing
+ AST_FRIENDLY_OFFSET
;
2966 if (ast_write(chan
, &a
))
2967 ast_log(LOG_WARNING
, "Prodding channel '%s' failed\n", chan
->name
);
2972 int ast_write_video(struct ast_channel
*chan
, struct ast_frame
*fr
)
2975 if (!chan
->tech
->write_video
)
2977 res
= ast_write(chan
, fr
);
2983 int ast_write(struct ast_channel
*chan
, struct ast_frame
*fr
)
2986 struct ast_frame
*f
= NULL
, *f2
= NULL
;
2989 /*Deadlock avoidance*/
2990 while(ast_channel_trylock(chan
)) {
2991 /*cannot goto done since the channel is not locked*/
2993 ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan
->name
);
2998 /* Stop if we're a zombie or need a soft hangup */
2999 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
))
3002 /* Handle any pending masquerades */
3003 if (chan
->masq
&& ast_do_masquerade(chan
)) {
3004 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
3008 res
= 0; /* XXX explain, why 0 ? */
3011 if (chan
->generatordata
) {
3012 if (ast_test_flag(chan
, AST_FLAG_WRITE_INT
))
3013 ast_deactivate_generator(chan
);
3015 if (fr
->frametype
== AST_FRAME_DTMF_END
) {
3016 /* There is a generator running while we're in the middle of a digit.
3017 * It's probably inband DTMF, so go ahead and pass it so it can
3018 * stop the generator */
3019 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
3020 ast_channel_unlock(chan
);
3021 res
= ast_senddigit_end(chan
, fr
->subclass
, fr
->len
);
3022 ast_channel_lock(chan
);
3023 CHECK_BLOCKING(chan
);
3024 } else if (fr
->frametype
== AST_FRAME_CONTROL
&& fr
->subclass
== AST_CONTROL_UNHOLD
) {
3025 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
3026 res
= (chan
->tech
->indicate
== NULL
) ? 0 :
3027 chan
->tech
->indicate(chan
, fr
->subclass
, fr
->data
.ptr
, fr
->datalen
);
3029 res
= 0; /* XXX explain, why 0 ? */
3033 /* High bit prints debugging */
3034 if (chan
->fout
& DEBUGCHAN_FLAG
)
3035 ast_frame_dump(chan
->name
, fr
, ">>");
3036 CHECK_BLOCKING(chan
);
3037 switch (fr
->frametype
) {
3038 case AST_FRAME_CONTROL
:
3039 res
= (chan
->tech
->indicate
== NULL
) ? 0 :
3040 chan
->tech
->indicate(chan
, fr
->subclass
, fr
->data
.ptr
, fr
->datalen
);
3042 case AST_FRAME_DTMF_BEGIN
:
3043 if (chan
->audiohooks
) {
3044 struct ast_frame
*old_frame
= fr
;
3045 fr
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_WRITE
, fr
);
3046 if (old_frame
!= fr
)
3049 send_dtmf_event(chan
, "Sent", fr
->subclass
, "Yes", "No");
3050 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
3051 ast_channel_unlock(chan
);
3052 res
= ast_senddigit_begin(chan
, fr
->subclass
);
3053 ast_channel_lock(chan
);
3054 CHECK_BLOCKING(chan
);
3056 case AST_FRAME_DTMF_END
:
3057 if (chan
->audiohooks
) {
3058 struct ast_frame
*old_frame
= fr
;
3059 fr
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_WRITE
, fr
);
3060 if (old_frame
!= fr
)
3063 send_dtmf_event(chan
, "Sent", fr
->subclass
, "No", "Yes");
3064 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
3065 ast_channel_unlock(chan
);
3066 res
= ast_senddigit_end(chan
, fr
->subclass
, fr
->len
);
3067 ast_channel_lock(chan
);
3068 CHECK_BLOCKING(chan
);
3070 case AST_FRAME_TEXT
:
3071 if (fr
->subclass
== AST_FORMAT_T140
) {
3072 res
= (chan
->tech
->write_text
== NULL
) ? 0 :
3073 chan
->tech
->write_text(chan
, fr
);
3075 res
= (chan
->tech
->send_text
== NULL
) ? 0 :
3076 chan
->tech
->send_text(chan
, (char *) fr
->data
.ptr
);
3079 case AST_FRAME_HTML
:
3080 res
= (chan
->tech
->send_html
== NULL
) ? 0 :
3081 chan
->tech
->send_html(chan
, fr
->subclass
, (char *) fr
->data
.ptr
, fr
->datalen
);
3083 case AST_FRAME_VIDEO
:
3084 /* XXX Handle translation of video codecs one day XXX */
3085 res
= (chan
->tech
->write_video
== NULL
) ? 0 :
3086 chan
->tech
->write_video(chan
, fr
);
3088 case AST_FRAME_MODEM
:
3089 res
= (chan
->tech
->write
== NULL
) ? 0 :
3090 chan
->tech
->write(chan
, fr
);
3092 case AST_FRAME_VOICE
:
3093 if (chan
->tech
->write
== NULL
)
3094 break; /*! \todo XXX should return 0 maybe ? */
3096 /* If audiohooks are present, write the frame out */
3097 if (chan
->audiohooks
) {
3098 struct ast_frame
*old_frame
= fr
;
3099 fr
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_WRITE
, fr
);
3100 if (old_frame
!= fr
)
3104 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3105 if (fr
->subclass
== chan
->rawwriteformat
)
3108 f
= (chan
->writetrans
) ? ast_translate(chan
->writetrans
, fr
, 0) : fr
;
3115 /* If Monitor is running on this channel, then we have to write frames out there too */
3116 if (chan
->monitor
&& chan
->monitor
->write_stream
) {
3117 /* XXX must explain this code */
3118 #ifndef MONITOR_CONSTANT_DELAY
3119 int jump
= chan
->insmpl
- chan
->outsmpl
- 4 * f
->samples
;
3121 jump
= chan
->insmpl
- chan
->outsmpl
;
3122 if (ast_seekstream(chan
->monitor
->write_stream
, jump
, SEEK_FORCECUR
) == -1)
3123 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3124 chan
->outsmpl
+= jump
+ f
->samples
;
3126 chan
->outsmpl
+= f
->samples
;
3128 int jump
= chan
->insmpl
- chan
->outsmpl
;
3129 if (jump
- MONITOR_DELAY
>= 0) {
3130 if (ast_seekstream(chan
->monitor
->write_stream
, jump
- f
->samples
, SEEK_FORCECUR
) == -1)
3131 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3132 chan
->outsmpl
+= jump
;
3134 chan
->outsmpl
+= f
->samples
;
3136 if (chan
->monitor
->state
== AST_MONITOR_RUNNING
) {
3137 if (ast_writestream(chan
->monitor
->write_stream
, f
) < 0)
3138 ast_log(LOG_WARNING
, "Failed to write data to channel monitor write stream\n");
3143 res
= chan
->tech
->write(chan
,f
);
3147 case AST_FRAME_NULL
:
3153 /* At this point, fr is the incoming frame and f is NULL. Channels do
3154 * not expect to get NULL as a frame pointer and will segfault. Hence,
3155 * we output the original frame passed in. */
3156 res
= chan
->tech
->write(chan
, fr
);
3164 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
3165 /* Consider a write failure to force a soft hangup */
3167 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
3169 chan
->fout
= FRAMECOUNT_INC(chan
->fout
);
3172 ast_channel_unlock(chan
);
3176 static int set_format(struct ast_channel
*chan
, int fmt
, int *rawformat
, int *format
,
3177 struct ast_trans_pvt
**trans
, const int direction
)
3181 char from
[200], to
[200];
3183 /* Make sure we only consider audio */
3184 fmt
&= AST_FORMAT_AUDIO_MASK
;
3186 native
= chan
->nativeformats
;
3188 if (!fmt
|| !native
) /* No audio requested */
3189 return 0; /* Let's try a call without any sounds (video, text) */
3191 /* Find a translation path from the native format to one of the desired formats */
3194 res
= ast_translator_best_choice(&fmt
, &native
);
3197 res
= ast_translator_best_choice(&native
, &fmt
);
3200 ast_log(LOG_WARNING
, "Unable to find a codec translation path from %s to %s\n",
3201 ast_getformatname_multiple(from
, sizeof(from
), native
),
3202 ast_getformatname_multiple(to
, sizeof(to
), fmt
));
3206 /* Now we have a good choice for both. */
3207 ast_channel_lock(chan
);
3209 if ((*rawformat
== native
) && (*format
== fmt
) && ((*rawformat
== *format
) || (*trans
))) {
3210 /* the channel is already in these formats, so nothing to do */
3211 ast_channel_unlock(chan
);
3215 *rawformat
= native
;
3216 /* User perspective is fmt */
3218 /* Free any read translation we have right now */
3220 ast_translator_free_path(*trans
);
3221 /* Build a translation path from the raw format to the desired format */
3224 *trans
= ast_translator_build_path(*format
, *rawformat
);
3227 *trans
= ast_translator_build_path(*rawformat
, *format
);
3228 ast_channel_unlock(chan
);
3229 ast_debug(1, "Set channel %s to %s format %s\n", chan
->name
,
3230 direction
? "write" : "read", ast_getformatname(fmt
));
3234 int ast_set_read_format(struct ast_channel
*chan
, int fmt
)
3236 return set_format(chan
, fmt
, &chan
->rawreadformat
, &chan
->readformat
,
3237 &chan
->readtrans
, 0);
3240 int ast_set_write_format(struct ast_channel
*chan
, int fmt
)
3242 return set_format(chan
, fmt
, &chan
->rawwriteformat
, &chan
->writeformat
,
3243 &chan
->writetrans
, 1);
3246 const char *ast_channel_reason2str(int reason
)
3248 switch (reason
) /* the following appear to be the only ones actually returned by request_and_dial */
3251 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
3252 case AST_CONTROL_HANGUP
:
3254 case AST_CONTROL_RING
:
3255 return "Local Ring";
3256 case AST_CONTROL_RINGING
:
3257 return "Remote end Ringing";
3258 case AST_CONTROL_ANSWER
:
3259 return "Remote end has Answered";
3260 case AST_CONTROL_BUSY
:
3261 return "Remote end is Busy";
3262 case AST_CONTROL_CONGESTION
:
3263 return "Congestion (circuits busy)";
3265 return "Unknown Reason!!";
3269 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
)
3273 struct ast_channel
*chan
;
3275 int last_subclass
= 0;
3280 outstate
= &dummy_outstate
; /* make outstate always a valid pointer */
3282 chan
= ast_request(type
, format
, data
, &cause
);
3284 ast_log(LOG_NOTICE
, "Unable to request channel %s/%s\n", type
, (char *)data
);
3285 /* compute error and return */
3286 if (cause
== AST_CAUSE_BUSY
)
3287 *outstate
= AST_CONTROL_BUSY
;
3288 else if (cause
== AST_CAUSE_CONGESTION
)
3289 *outstate
= AST_CONTROL_CONGESTION
;
3295 ast_set_variables(chan
, oh
->vars
);
3296 /* XXX why is this necessary, for the parent_channel perhaps ? */
3297 if (!ast_strlen_zero(oh
->cid_num
) && !ast_strlen_zero(oh
->cid_name
))
3298 ast_set_callerid(chan
, oh
->cid_num
, oh
->cid_name
, oh
->cid_num
);
3299 if (oh
->parent_channel
) {
3300 ast_channel_inherit_variables(oh
->parent_channel
, chan
);
3301 ast_channel_datastore_inherit(oh
->parent_channel
, chan
);
3304 ast_cdr_setaccount(chan
, oh
->account
);
3306 ast_set_callerid(chan
, cid_num
, cid_name
, cid_num
);
3308 if (ast_call(chan
, data
, 0)) { /* ast_call failed... */
3309 ast_log(LOG_NOTICE
, "Unable to call channel %s/%s\n", type
, (char *)data
);
3311 res
= 1; /* mark success in case chan->_state is already AST_STATE_UP */
3312 while (timeout
&& chan
->_state
!= AST_STATE_UP
) {
3313 struct ast_frame
*f
;
3314 res
= ast_waitfor(chan
, timeout
);
3315 if (res
<= 0) /* error, timeout, or done */
3321 *outstate
= AST_CONTROL_HANGUP
;
3325 if (f
->frametype
== AST_FRAME_CONTROL
) {
3326 switch (f
->subclass
) {
3327 case AST_CONTROL_RINGING
: /* record but keep going */
3328 *outstate
= f
->subclass
;
3331 case AST_CONTROL_BUSY
:
3332 case AST_CONTROL_CONGESTION
:
3333 case AST_CONTROL_ANSWER
:
3334 *outstate
= f
->subclass
;
3335 timeout
= 0; /* trick to force exit from the while() */
3339 case AST_CONTROL_PROGRESS
:
3340 case AST_CONTROL_PROCEEDING
:
3341 case AST_CONTROL_HOLD
:
3342 case AST_CONTROL_UNHOLD
:
3343 case AST_CONTROL_VIDUPDATE
:
3344 case AST_CONTROL_SRCUPDATE
:
3345 case -1: /* Ignore -- just stopping indications */
3349 ast_log(LOG_NOTICE
, "Don't know what to do with control frame %d\n", f
->subclass
);
3351 last_subclass
= f
->subclass
;
3359 if (!ast_strlen_zero(oh
->context
))
3360 ast_copy_string(chan
->context
, oh
->context
, sizeof(chan
->context
));
3361 if (!ast_strlen_zero(oh
->exten
))
3362 ast_copy_string(chan
->exten
, oh
->exten
, sizeof(chan
->exten
));
3364 chan
->priority
= oh
->priority
;
3366 if (chan
->_state
== AST_STATE_UP
)
3367 *outstate
= AST_CONTROL_ANSWER
;
3370 if ( AST_CONTROL_RINGING
== last_subclass
)
3371 chan
->hangupcause
= AST_CAUSE_NO_ANSWER
;
3372 if (!chan
->cdr
&& (chan
->cdr
= ast_cdr_alloc()))
3373 ast_cdr_init(chan
->cdr
, chan
);
3376 snprintf(tmp
, sizeof(tmp
), "%s/%s", type
, (char *)data
);
3377 ast_cdr_setapp(chan
->cdr
,"Dial",tmp
);
3378 ast_cdr_update(chan
);
3379 ast_cdr_start(chan
->cdr
);
3380 ast_cdr_end(chan
->cdr
);
3381 /* If the cause wasn't handled properly */
3382 if (ast_cdr_disposition(chan
->cdr
,chan
->hangupcause
))
3383 ast_cdr_failed(chan
->cdr
);
3391 struct ast_channel
*ast_request_and_dial(const char *type
, int format
, void *data
, int timeout
, int *outstate
, const char *cidnum
, const char *cidname
)
3393 return __ast_request_and_dial(type
, format
, data
, timeout
, outstate
, cidnum
, cidname
, NULL
);
3396 struct ast_channel
*ast_request(const char *type
, int format
, void *data
, int *cause
)
3398 struct chanlist
*chan
;
3399 struct ast_channel
*c
;
3404 int videoformat
= format
& AST_FORMAT_VIDEO_MASK
;
3405 int textformat
= format
& AST_FORMAT_TEXT_MASK
;
3409 *cause
= AST_CAUSE_NOTDEFINED
;
3411 if (AST_RWLIST_RDLOCK(&channels
)) {
3412 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
3416 AST_LIST_TRAVERSE(&backends
, chan
, list
) {
3417 if (strcasecmp(type
, chan
->tech
->type
))
3420 capabilities
= chan
->tech
->capabilities
;
3421 fmt
= format
& AST_FORMAT_AUDIO_MASK
;
3423 /* We have audio - is it possible to connect the various calls to each other?
3424 (Avoid this check for calls without audio, like text+video calls)
3426 res
= ast_translator_best_choice(&fmt
, &capabilities
);
3428 ast_log(LOG_WARNING
, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type
, chan
->tech
->capabilities
, format
);
3429 *cause
= AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
;
3430 AST_RWLIST_UNLOCK(&channels
);
3434 AST_RWLIST_UNLOCK(&channels
);
3435 if (!chan
->tech
->requester
)
3438 if (!(c
= chan
->tech
->requester(type
, capabilities
| videoformat
| textformat
, data
, cause
)))
3441 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3445 ast_log(LOG_WARNING
, "No channel type registered for '%s'\n", type
);
3446 *cause
= AST_CAUSE_NOSUCHDRIVER
;
3447 AST_RWLIST_UNLOCK(&channels
);
3452 int ast_call(struct ast_channel
*chan
, char *addr
, int timeout
)
3454 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3455 If the remote end does not answer within the timeout, then do NOT hang up, but
3458 /* Stop if we're a zombie or need a soft hangup */
3459 ast_channel_lock(chan
);
3460 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
) && !ast_check_hangup(chan
)) {
3462 ast_set_flag(chan
->cdr
, AST_CDR_FLAG_DIALED
);
3463 if (chan
->tech
->call
)
3464 res
= chan
->tech
->call(chan
, addr
, timeout
);
3465 ast_set_flag(chan
, AST_FLAG_OUTGOING
);
3467 ast_channel_unlock(chan
);
3472 \brief Transfer a call to dest, if the channel supports transfer
3476 \arg the manager interface
3478 int ast_transfer(struct ast_channel
*chan
, char *dest
)
3482 /* Stop if we're a zombie or need a soft hangup */
3483 ast_channel_lock(chan
);
3484 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
) && !ast_check_hangup(chan
)) {
3485 if (chan
->tech
->transfer
) {
3486 res
= chan
->tech
->transfer(chan
, dest
);
3492 ast_channel_unlock(chan
);
3496 int ast_readstring(struct ast_channel
*c
, char *s
, int len
, int timeout
, int ftimeout
, char *enders
)
3498 return ast_readstring_full(c
, s
, len
, timeout
, ftimeout
, enders
, -1, -1);
3501 int ast_readstring_full(struct ast_channel
*c
, char *s
, int len
, int timeout
, int ftimeout
, char *enders
, int audiofd
, int ctrlfd
)
3503 int pos
= 0; /* index in the buffer where we accumulate digits */
3506 /* Stop if we're a zombie or need a soft hangup */
3507 if (ast_test_flag(c
, AST_FLAG_ZOMBIE
) || ast_check_hangup(c
))
3514 d
= ast_waitstream_full(c
, AST_DIGIT_ANY
, audiofd
, ctrlfd
);
3518 d
= ast_waitfordigit_full(c
, to
, audiofd
, ctrlfd
);
3520 d
= ast_waitfordigit_full(c
, to
, audiofd
, ctrlfd
);
3532 if (!strchr(enders
, d
))
3534 if (strchr(enders
, d
) || (pos
>= len
)) {
3544 int ast_channel_supports_html(struct ast_channel
*chan
)
3546 return (chan
->tech
->send_html
) ? 1 : 0;
3549 int ast_channel_sendhtml(struct ast_channel
*chan
, int subclass
, const char *data
, int datalen
)
3551 if (chan
->tech
->send_html
)
3552 return chan
->tech
->send_html(chan
, subclass
, data
, datalen
);
3556 int ast_channel_sendurl(struct ast_channel
*chan
, const char *url
)
3558 return ast_channel_sendhtml(chan
, AST_HTML_URL
, url
, strlen(url
) + 1);
3561 /*! \brief Set up translation from one channel to another */
3562 static int ast_channel_make_compatible_helper(struct ast_channel
*from
, struct ast_channel
*to
)
3567 if (from
->readformat
== to
->writeformat
&& from
->writeformat
== to
->readformat
) {
3568 /* Already compatible! Moving on ... */
3572 /* Set up translation from the 'from' channel to the 'to' channel */
3573 src
= from
->nativeformats
;
3574 dst
= to
->nativeformats
;
3576 /* If there's no audio in this call, don't bother with trying to find a translation path */
3577 if ((src
& AST_FORMAT_AUDIO_MASK
) == 0 || (dst
& AST_FORMAT_AUDIO_MASK
) == 0)
3580 if (ast_translator_best_choice(&dst
, &src
) < 0) {
3581 ast_log(LOG_WARNING
, "No path to translate from %s(%d) to %s(%d)\n", from
->name
, src
, to
->name
, dst
);
3585 /* if the best path is not 'pass through', then
3586 transcoding is needed; if desired, force transcode path
3587 to use SLINEAR between channels, but only if there is
3588 no direct conversion available */
3589 if ((src
!= dst
) && ast_opt_transcode_via_slin
&&
3590 (ast_translate_path_steps(dst
, src
) != 1))
3591 dst
= AST_FORMAT_SLINEAR
;
3592 if (ast_set_read_format(from
, dst
) < 0) {
3593 ast_log(LOG_WARNING
, "Unable to set read format on channel %s to %d\n", from
->name
, dst
);
3596 if (ast_set_write_format(to
, dst
) < 0) {
3597 ast_log(LOG_WARNING
, "Unable to set write format on channel %s to %d\n", to
->name
, dst
);
3603 int ast_channel_make_compatible(struct ast_channel
*chan
, struct ast_channel
*peer
)
3605 /* Some callers do not check return code, and we must try to set all call legs correctly */
3608 /* Set up translation from the chan to the peer */
3609 rc
= ast_channel_make_compatible_helper(chan
, peer
);
3614 /* Set up translation from the peer to the chan */
3615 rc
= ast_channel_make_compatible_helper(peer
, chan
);
3620 int ast_channel_masquerade(struct ast_channel
*original
, struct ast_channel
*clonechan
)
3623 struct ast_channel
*final_orig
, *final_clone
, *base
;
3626 final_orig
= original
;
3627 final_clone
= clonechan
;
3629 ast_channel_lock(original
);
3630 while (ast_channel_trylock(clonechan
)) {
3631 ast_channel_unlock(original
);
3633 ast_channel_lock(original
);
3636 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3637 and if so, we don't really want to masquerade it, but its proxy */
3638 if (original
->_bridge
&& (original
->_bridge
!= ast_bridged_channel(original
)) && (original
->_bridge
->_bridge
!= original
))
3639 final_orig
= original
->_bridge
;
3641 if (clonechan
->_bridge
&& (clonechan
->_bridge
!= ast_bridged_channel(clonechan
)) && (clonechan
->_bridge
->_bridge
!= clonechan
))
3642 final_clone
= clonechan
->_bridge
;
3644 if (final_clone
->tech
->get_base_channel
&& (base
= final_clone
->tech
->get_base_channel(final_clone
))) {
3648 if ((final_orig
!= original
) || (final_clone
!= clonechan
)) {
3649 /* Lots and lots of deadlock avoidance. The main one we're competing with
3650 * is ast_write(), which locks channels recursively, when working with a
3652 if (ast_channel_trylock(final_orig
)) {
3653 ast_channel_unlock(clonechan
);
3654 ast_channel_unlock(original
);
3657 if (ast_channel_trylock(final_clone
)) {
3658 ast_channel_unlock(final_orig
);
3659 ast_channel_unlock(clonechan
);
3660 ast_channel_unlock(original
);
3663 ast_channel_unlock(clonechan
);
3664 ast_channel_unlock(original
);
3665 original
= final_orig
;
3666 clonechan
= final_clone
;
3669 if (original
== clonechan
) {
3670 ast_log(LOG_WARNING
, "Can't masquerade channel '%s' into itself!\n", original
->name
);
3671 ast_channel_unlock(clonechan
);
3672 ast_channel_unlock(original
);
3676 ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
3677 clonechan
->name
, original
->name
);
3678 if (original
->masq
) {
3679 ast_log(LOG_WARNING
, "%s is already going to masquerade as %s\n",
3680 original
->masq
->name
, original
->name
);
3681 } else if (clonechan
->masqr
) {
3682 ast_log(LOG_WARNING
, "%s is already going to masquerade as %s\n",
3683 clonechan
->name
, clonechan
->masqr
->name
);
3685 original
->masq
= clonechan
;
3686 clonechan
->masqr
= original
;
3687 ast_queue_frame(original
, &ast_null_frame
);
3688 ast_queue_frame(clonechan
, &ast_null_frame
);
3689 ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clonechan
->name
, original
->name
);
3693 ast_channel_unlock(clonechan
);
3694 ast_channel_unlock(original
);
3699 void ast_change_name(struct ast_channel
*chan
, char *newname
)
3701 manager_event(EVENT_FLAG_CALL
, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan
->name
, newname
, chan
->uniqueid
);
3702 ast_string_field_set(chan
, name
, newname
);
3705 void ast_channel_inherit_variables(const struct ast_channel
*parent
, struct ast_channel
*child
)
3707 struct ast_var_t
*current
, *newvar
;
3708 const char *varname
;
3710 AST_LIST_TRAVERSE(&parent
->varshead
, current
, entries
) {
3713 varname
= ast_var_full_name(current
);
3717 if (varname
[0] == '_') {
3719 if (varname
[1] == '_')
3725 newvar
= ast_var_assign(&varname
[1], ast_var_value(current
));
3727 AST_LIST_INSERT_TAIL(&child
->varshead
, newvar
, entries
);
3728 ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar
));
3732 newvar
= ast_var_assign(varname
, ast_var_value(current
));
3734 AST_LIST_INSERT_TAIL(&child
->varshead
, newvar
, entries
);
3735 ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar
));
3739 ast_debug(1, "Not copying variable %s.\n", ast_var_name(current
));
3746 \brief Clone channel variables from 'clone' channel into 'original' channel
3748 All variables except those related to app_groupcount are cloned.
3749 Variables are actually _removed_ from 'clone' channel, presumably
3750 because it will subsequently be destroyed.
3752 \note Assumes locks will be in place on both channels when called.
3754 static void clone_variables(struct ast_channel
*original
, struct ast_channel
*clonechan
)
3756 struct ast_var_t
*current
, *newvar
;
3757 /* Append variables from clone channel into original channel */
3758 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3759 if (AST_LIST_FIRST(&clonechan
->varshead
))
3760 AST_LIST_APPEND_LIST(&original
->varshead
, &clonechan
->varshead
, entries
);
3762 /* then, dup the varshead list into the clone */
3764 AST_LIST_TRAVERSE(&original
->varshead
, current
, entries
) {
3765 newvar
= ast_var_assign(current
->name
, current
->value
);
3767 AST_LIST_INSERT_TAIL(&clonechan
->varshead
, newvar
, entries
);
3772 \brief Masquerade a channel
3774 \note Assumes channel will be locked when called
3776 int ast_do_masquerade(struct ast_channel
*original
)
3781 struct ast_frame
*current
;
3782 const struct ast_channel_tech
*t
;
3784 struct ast_callerid tmpcid
;
3785 struct ast_channel
*clonechan
= original
->masq
;
3786 struct ast_cdr
*cdr
;
3787 int rformat
= original
->readformat
;
3788 int wformat
= original
->writeformat
;
3789 char newn
[AST_CHANNEL_NAME
];
3790 char orig
[AST_CHANNEL_NAME
];
3791 char masqn
[AST_CHANNEL_NAME
];
3792 char zombn
[AST_CHANNEL_NAME
];
3794 ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3795 clonechan
->name
, clonechan
->_state
, original
->name
, original
->_state
);
3797 manager_event(EVENT_FLAG_CALL
, "Masquerade", "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
3798 clonechan
->name
, ast_state2str(clonechan
->_state
), original
->name
, ast_state2str(original
->_state
));
3800 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3801 the clone channel into the original channel. Start by killing off the original
3802 channel's backend. I'm not sure we're going to keep this function, because
3803 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3805 /* We need the clone's lock, too */
3806 ast_channel_lock(clonechan
);
3808 ast_debug(2, "Got clone lock for masquerade on '%s' at %p\n", clonechan
->name
, &clonechan
->lock_dont_use
);
3810 /* Having remembered the original read/write formats, we turn off any translation on either
3812 free_translation(clonechan
);
3813 free_translation(original
);
3816 /* Unlink the masquerade */
3817 original
->masq
= NULL
;
3818 clonechan
->masqr
= NULL
;
3820 /* Save the original name */
3821 ast_copy_string(orig
, original
->name
, sizeof(orig
));
3822 /* Save the new name */
3823 ast_copy_string(newn
, clonechan
->name
, sizeof(newn
));
3824 /* Create the masq name */
3825 snprintf(masqn
, sizeof(masqn
), "%s<MASQ>", newn
);
3827 /* Copy the name from the clone channel */
3828 ast_string_field_set(original
, name
, newn
);
3830 /* Mangle the name of the clone channel */
3831 ast_string_field_set(clonechan
, name
, masqn
);
3833 /* Notify any managers of the change, first the masq then the other */
3834 manager_event(EVENT_FLAG_CALL
, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn
, masqn
, clonechan
->uniqueid
);
3835 manager_event(EVENT_FLAG_CALL
, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig
, newn
, original
->uniqueid
);
3837 /* Swap the technologies */
3839 original
->tech
= clonechan
->tech
;
3840 clonechan
->tech
= t
;
3843 cdr
= original
->cdr
;
3844 original
->cdr
= clonechan
->cdr
;
3845 clonechan
->cdr
= cdr
;
3847 t_pvt
= original
->tech_pvt
;
3848 original
->tech_pvt
= clonechan
->tech_pvt
;
3849 clonechan
->tech_pvt
= t_pvt
;
3851 /* Swap the alertpipes */
3852 for (i
= 0; i
< 2; i
++) {
3853 x
= original
->alertpipe
[i
];
3854 original
->alertpipe
[i
] = clonechan
->alertpipe
[i
];
3855 clonechan
->alertpipe
[i
] = x
;
3859 * Swap the readq's. The end result should be this:
3861 * 1) All frames should be on the new (original) channel.
3862 * 2) Any frames that were already on the new channel before this
3863 * masquerade need to be at the end of the readq, after all of the
3864 * frames on the old (clone) channel.
3865 * 3) The alertpipe needs to get poked for every frame that was already
3866 * on the new channel, since we are now using the alert pipe from the
3867 * old (clone) channel.
3870 AST_LIST_HEAD_NOLOCK(, ast_frame
) tmp_readq
;
3871 AST_LIST_HEAD_SET_NOLOCK(&tmp_readq
, NULL
);
3873 AST_LIST_APPEND_LIST(&tmp_readq
, &original
->readq
, frame_list
);
3874 AST_LIST_APPEND_LIST(&original
->readq
, &clonechan
->readq
, frame_list
);
3876 while ((current
= AST_LIST_REMOVE_HEAD(&tmp_readq
, frame_list
))) {
3877 AST_LIST_INSERT_TAIL(&original
->readq
, current
, frame_list
);
3878 if (original
->alertpipe
[1] > -1) {
3880 write(original
->alertpipe
[1], &poke
, sizeof(poke
));
3885 /* Swap the raw formats */
3886 x
= original
->rawreadformat
;
3887 original
->rawreadformat
= clonechan
->rawreadformat
;
3888 clonechan
->rawreadformat
= x
;
3889 x
= original
->rawwriteformat
;
3890 original
->rawwriteformat
= clonechan
->rawwriteformat
;
3891 clonechan
->rawwriteformat
= x
;
3893 clonechan
->_softhangup
= AST_SOFTHANGUP_DEV
;
3895 /* And of course, so does our current state. Note we need not
3896 call ast_setstate since the event manager doesn't really consider
3897 these separate. We do this early so that the clone has the proper
3898 state of the original channel. */
3899 origstate
= original
->_state
;
3900 original
->_state
= clonechan
->_state
;
3901 clonechan
->_state
= origstate
;
3903 if (clonechan
->tech
->fixup
){
3904 res
= clonechan
->tech
->fixup(original
, clonechan
);
3906 ast_log(LOG_WARNING
, "Fixup failed on channel %s, strange things may happen.\n", clonechan
->name
);
3909 /* Start by disconnecting the original's physical side */
3910 if (clonechan
->tech
->hangup
)
3911 res
= clonechan
->tech
->hangup(clonechan
);
3913 ast_log(LOG_WARNING
, "Hangup failed! Strange things may happen!\n");
3914 ast_channel_unlock(clonechan
);
3918 snprintf(zombn
, sizeof(zombn
), "%s<ZOMBIE>", orig
);
3919 /* Mangle the name of the clone channel */
3920 ast_string_field_set(clonechan
, name
, zombn
);
3921 manager_event(EVENT_FLAG_CALL
, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn
, zombn
, clonechan
->uniqueid
);
3923 /* Update the type. */
3924 t_pvt
= original
->monitor
;
3925 original
->monitor
= clonechan
->monitor
;
3926 clonechan
->monitor
= t_pvt
;
3928 /* Keep the same language. */
3929 ast_string_field_set(original
, language
, clonechan
->language
);
3930 /* Copy the FD's other than the generator fd */
3931 for (x
= 0; x
< AST_MAX_FDS
; x
++) {
3932 if (x
!= AST_GENERATOR_FD
)
3933 ast_channel_set_fd(original
, x
, clonechan
->fds
[x
]);
3936 ast_app_group_update(clonechan
, original
);
3938 /* Move data stores over */
3939 if (AST_LIST_FIRST(&clonechan
->datastores
)) {
3940 struct ast_datastore
*ds
;
3941 AST_LIST_APPEND_LIST(&original
->datastores
, &clonechan
->datastores
, entry
);
3942 AST_LIST_TRAVERSE(&original
->datastores
, ds
, entry
) {
3943 if (ds
->info
->chan_fixup
)
3944 ds
->info
->chan_fixup(ds
->data
, clonechan
, original
);
3948 clone_variables(original
, clonechan
);
3949 /* Presense of ADSI capable CPE follows clone */
3950 original
->adsicpe
= clonechan
->adsicpe
;
3951 /* Bridge remains the same */
3952 /* CDR fields remain the same */
3953 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3954 /* Application and data remain the same */
3955 /* Clone exception becomes real one, as with fdno */
3956 ast_copy_flags(original
, clonechan
, AST_FLAG_EXCEPTION
);
3957 original
->fdno
= clonechan
->fdno
;
3958 /* Schedule context remains the same */
3959 /* Stream stuff stays the same */
3960 /* Keep the original state. The fixup code will need to work with it most likely */
3962 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3964 tmpcid
= original
->cid
;
3965 original
->cid
= clonechan
->cid
;
3966 clonechan
->cid
= tmpcid
;
3968 /* Restore original timing file descriptor */
3969 ast_channel_set_fd(original
, AST_TIMING_FD
, original
->timingfd
);
3971 /* Our native formats are different now */
3972 original
->nativeformats
= clonechan
->nativeformats
;
3974 /* Context, extension, priority, app data, jump table, remain the same */
3975 /* pvt switches. pbx stays the same, as does next */
3977 /* Set the write format */
3978 ast_set_write_format(original
, wformat
);
3980 /* Set the read format */
3981 ast_set_read_format(original
, rformat
);
3983 /* Copy the music class */
3984 ast_string_field_set(original
, musicclass
, clonechan
->musicclass
);
3986 ast_debug(1, "Putting channel %s in %d/%d formats\n", original
->name
, wformat
, rformat
);
3988 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3989 can fix up everything as best as possible */
3990 if (original
->tech
->fixup
) {
3991 res
= original
->tech
->fixup(clonechan
, original
);
3993 ast_log(LOG_WARNING
, "Channel for type '%s' could not fixup channel %s\n",
3994 original
->tech
->type
, original
->name
);
3995 ast_channel_unlock(clonechan
);
3999 ast_log(LOG_WARNING
, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
4000 original
->tech
->type
, original
->name
);
4002 /* If an indication is currently playing maintain it on the channel that is taking the place of original */
4003 if (original
->visible_indication
)
4004 ast_indicate(original
, original
->visible_indication
);
4006 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
4007 a zombie so nothing tries to touch it. If it's already been marked as a
4008 zombie, then free it now (since it already is considered invalid). */
4009 if (ast_test_flag(clonechan
, AST_FLAG_ZOMBIE
)) {
4010 ast_debug(1, "Destroying channel clone '%s'\n", clonechan
->name
);
4011 ast_channel_unlock(clonechan
);
4012 manager_event(EVENT_FLAG_CALL
, "Hangup",
4016 "Cause-txt: %s\r\n",
4018 clonechan
->uniqueid
,
4019 clonechan
->hangupcause
,
4020 ast_cause2str(clonechan
->hangupcause
)
4022 ast_channel_free(clonechan
);
4024 ast_debug(1, "Released clone lock on '%s'\n", clonechan
->name
);
4025 ast_set_flag(clonechan
, AST_FLAG_ZOMBIE
);
4026 ast_queue_frame(clonechan
, &ast_null_frame
);
4027 ast_channel_unlock(clonechan
);
4030 /* Signal any blocker */
4031 if (ast_test_flag(original
, AST_FLAG_BLOCKING
))
4032 pthread_kill(original
->blocker
, SIGURG
);
4033 ast_debug(1, "Done Masquerading %s (%d)\n", original
->name
, original
->_state
);
4037 void ast_set_callerid(struct ast_channel
*chan
, const char *cid_num
, const char *cid_name
, const char *cid_ani
)
4039 ast_channel_lock(chan
);
4042 if (chan
->cid
.cid_num
)
4043 ast_free(chan
->cid
.cid_num
);
4044 chan
->cid
.cid_num
= ast_strdup(cid_num
);
4047 if (chan
->cid
.cid_name
)
4048 ast_free(chan
->cid
.cid_name
);
4049 chan
->cid
.cid_name
= ast_strdup(cid_name
);
4052 if (chan
->cid
.cid_ani
)
4053 ast_free(chan
->cid
.cid_ani
);
4054 chan
->cid
.cid_ani
= ast_strdup(cid_ani
);
4056 manager_event(EVENT_FLAG_CALL
, "NewCallerid",
4058 "CallerIDNum: %s\r\n"
4059 "CallerIDName: %s\r\n"
4061 "CID-CallingPres: %d (%s)\r\n",
4063 S_OR(chan
->cid
.cid_num
, ""),
4064 S_OR(chan
->cid
.cid_name
, ""),
4067 ast_describe_caller_presentation(chan
->cid
.cid_pres
)
4070 ast_channel_unlock(chan
);
4073 int ast_setstate(struct ast_channel
*chan
, enum ast_channel_state state
)
4075 int oldstate
= chan
->_state
;
4076 char name
[AST_CHANNEL_NAME
], *dashptr
;
4078 if (oldstate
== state
)
4081 ast_copy_string(name
, chan
->name
, sizeof(name
));
4082 if ((dashptr
= strrchr(name
, '-'))) {
4086 chan
->_state
= state
;
4087 ast_devstate_changed_literal(ast_state_chan2dev(state
), name
);
4088 /* setstate used to conditionally report Newchannel; this is no more */
4089 manager_event(EVENT_FLAG_CALL
,
4092 "ChannelState: %d\r\n"
4093 "ChannelStateDesc: %s\r\n"
4094 "CallerIDNum: %s\r\n"
4095 "CallerIDName: %s\r\n"
4097 chan
->name
, chan
->_state
, ast_state2str(chan
->_state
),
4098 S_OR(chan
->cid
.cid_num
, ""),
4099 S_OR(chan
->cid
.cid_name
, ""),
4105 /*! \brief Find bridged channel */
4106 struct ast_channel
*ast_bridged_channel(struct ast_channel
*chan
)
4108 struct ast_channel
*bridged
;
4109 bridged
= chan
->_bridge
;
4110 if (bridged
&& bridged
->tech
->bridged_channel
)
4111 bridged
= bridged
->tech
->bridged_channel(chan
, bridged
);
4115 static void bridge_playfile(struct ast_channel
*chan
, struct ast_channel
*peer
, const char *sound
, int remain
)
4117 int min
= 0, sec
= 0, check
;
4119 check
= ast_autoservice_start(peer
);
4124 if (remain
/ 60 > 1) {
4132 if (!strcmp(sound
,"timeleft")) { /* Queue support */
4133 ast_stream_and_wait(chan
, "vm-youhave", "");
4135 ast_say_number(chan
, min
, AST_DIGIT_ANY
, chan
->language
, NULL
);
4136 ast_stream_and_wait(chan
, "queue-minutes", "");
4139 ast_say_number(chan
, sec
, AST_DIGIT_ANY
, chan
->language
, NULL
);
4140 ast_stream_and_wait(chan
, "queue-seconds", "");
4143 ast_stream_and_wait(chan
, sound
, "");
4146 ast_autoservice_stop(peer
);
4149 static enum ast_bridge_result
ast_generic_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
,
4150 struct ast_bridge_config
*config
, struct ast_frame
**fo
,
4151 struct ast_channel
**rc
, struct timeval bridge_end
)
4153 /* Copy voice back and forth between the two channels. */
4154 struct ast_channel
*cs
[3];
4155 struct ast_frame
*f
;
4156 enum ast_bridge_result res
= AST_BRIDGE_COMPLETE
;
4157 int o0nativeformats
;
4158 int o1nativeformats
;
4162 /* Indicates whether a frame was queued into a jitterbuffer */
4163 int frame_put_in_jb
= 0;
4169 pvt0
= c0
->tech_pvt
;
4170 pvt1
= c1
->tech_pvt
;
4171 o0nativeformats
= c0
->nativeformats
;
4172 o1nativeformats
= c1
->nativeformats
;
4173 watch_c0_dtmf
= config
->flags
& AST_BRIDGE_DTMF_CHANNEL_0
;
4174 watch_c1_dtmf
= config
->flags
& AST_BRIDGE_DTMF_CHANNEL_1
;
4176 /* Check the need of a jitterbuffer for each channel */
4177 jb_in_use
= ast_jb_do_usecheck(c0
, c1
);
4179 ast_jb_empty_and_reset(c0
, c1
);
4181 ast_poll_channel_add(c0
, c1
);
4184 struct ast_channel
*who
, *other
;
4186 if ((c0
->tech_pvt
!= pvt0
) || (c1
->tech_pvt
!= pvt1
) ||
4187 (o0nativeformats
!= c0
->nativeformats
) ||
4188 (o1nativeformats
!= c1
->nativeformats
)) {
4189 /* Check for Masquerade, codec changes, etc */
4190 res
= AST_BRIDGE_RETRY
;
4193 if (bridge_end
.tv_sec
) {
4194 to
= ast_tvdiff_ms(bridge_end
, ast_tvnow());
4196 if (config
->timelimit
)
4197 res
= AST_BRIDGE_RETRY
;
4199 res
= AST_BRIDGE_COMPLETE
;
4204 /* Calculate the appropriate max sleep interval - in general, this is the time,
4205 left to the closest jb delivery moment */
4207 to
= ast_jb_get_when_to_wakeup(c0
, c1
, to
);
4208 who
= ast_waitfor_n(cs
, 2, &to
);
4210 /* No frame received within the specified timeout - check if we have to deliver now */
4212 ast_jb_get_and_deliver(c0
, c1
);
4213 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
) {
4214 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4215 c0
->_softhangup
= 0;
4216 if (c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4217 c1
->_softhangup
= 0;
4227 ast_debug(1, "Didn't get a frame from channel: %s\n",who
->name
);
4231 other
= (who
== c0
) ? c1
: c0
; /* the 'other' channel */
4232 /* Try add the frame info the who's bridged channel jitterbuff */
4234 frame_put_in_jb
= !ast_jb_put(other
, f
);
4236 if ((f
->frametype
== AST_FRAME_CONTROL
) && !(config
->flags
& AST_BRIDGE_IGNORE_SIGS
)) {
4237 int bridge_exit
= 0;
4239 switch (f
->subclass
) {
4240 case AST_CONTROL_HOLD
:
4241 case AST_CONTROL_UNHOLD
:
4242 case AST_CONTROL_VIDUPDATE
:
4243 case AST_CONTROL_SRCUPDATE
:
4244 ast_indicate_data(other
, f
->subclass
, f
->data
.ptr
, f
->datalen
);
4246 ast_jb_empty_and_reset(c0
, c1
);
4253 ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f
->subclass
, who
->name
);
4259 if ((f
->frametype
== AST_FRAME_VOICE
) ||
4260 (f
->frametype
== AST_FRAME_DTMF_BEGIN
) ||
4261 (f
->frametype
== AST_FRAME_DTMF
) ||
4262 (f
->frametype
== AST_FRAME_VIDEO
) ||
4263 (f
->frametype
== AST_FRAME_IMAGE
) ||
4264 (f
->frametype
== AST_FRAME_HTML
) ||
4265 (f
->frametype
== AST_FRAME_MODEM
) ||
4266 (f
->frametype
== AST_FRAME_TEXT
)) {
4267 /* monitored dtmf causes exit from bridge */
4268 int monitored_source
= (who
== c0
) ? watch_c0_dtmf
: watch_c1_dtmf
;
4270 if (monitored_source
&&
4271 (f
->frametype
== AST_FRAME_DTMF_END
||
4272 f
->frametype
== AST_FRAME_DTMF_BEGIN
)) {
4275 ast_debug(1, "Got DTMF %s on channel (%s)\n",
4276 f
->frametype
== AST_FRAME_DTMF_END
? "end" : "begin",
4280 /* Write immediately frames, not passed through jb */
4281 if (!frame_put_in_jb
)
4282 ast_write(other
, f
);
4284 /* Check if we have to deliver now */
4286 ast_jb_get_and_deliver(c0
, c1
);
4288 /* XXX do we want to pass on also frames not matched above ? */
4292 /* Swap who gets priority */
4299 ast_poll_channel_del(c0
, c1
);
4304 /*! \brief Bridge two channels together (early) */
4305 int ast_channel_early_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
)
4307 /* Make sure we can early bridge, if not error out */
4308 if (!c0
->tech
->early_bridge
|| (c1
&& (!c1
->tech
->early_bridge
|| c0
->tech
->early_bridge
!= c1
->tech
->early_bridge
)))
4311 return c0
->tech
->early_bridge(c0
, c1
);
4314 /*! \brief Send manager event for bridge link and unlink events.
4315 * \param onoff Link/Unlinked
4316 * \param type 1 for core, 2 for native
4317 * \param c0 first channel in bridge
4318 * \param c1 second channel in bridge
4320 static void manager_bridge_event(int onoff
, int type
, struct ast_channel
*c0
, struct ast_channel
*c1
)
4322 manager_event(EVENT_FLAG_CALL
, "Bridge",
4323 "Bridgestate: %s\r\n"
4324 "Bridgetype: %s\r\n"
4330 "CallerID2: %s\r\n",
4331 onoff
? "Link" : "Unlink",
4332 type
== 1 ? "core" : "native",
4333 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
,
4334 S_OR(c0
->cid
.cid_num
, ""),
4335 S_OR(c1
->cid
.cid_num
, ""));
4338 /*! \brief Bridge two channels together */
4339 enum ast_bridge_result
ast_channel_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
,
4340 struct ast_bridge_config
*config
, struct ast_frame
**fo
, struct ast_channel
**rc
)
4342 struct ast_channel
*who
= NULL
;
4343 enum ast_bridge_result res
= AST_BRIDGE_COMPLETE
;
4346 int o0nativeformats
;
4347 int o1nativeformats
;
4348 long time_left_ms
=0;
4349 struct timeval nexteventts
= { 0, };
4350 char caller_warning
= 0;
4351 char callee_warning
= 0;
4354 ast_log(LOG_WARNING
, "%s is already in a bridge with %s\n",
4355 c0
->name
, c0
->_bridge
->name
);
4359 ast_log(LOG_WARNING
, "%s is already in a bridge with %s\n",
4360 c1
->name
, c1
->_bridge
->name
);
4364 /* Stop if we're a zombie or need a soft hangup */
4365 if (ast_test_flag(c0
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c0
) ||
4366 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c1
))
4370 firstpass
= config
->firstpass
;
4371 config
->firstpass
= 0;
4373 if (ast_tvzero(config
->start_time
))
4374 config
->start_time
= ast_tvnow();
4375 time_left_ms
= config
->timelimit
;
4377 caller_warning
= ast_test_flag(&config
->features_caller
, AST_FEATURE_PLAY_WARNING
);
4378 callee_warning
= ast_test_flag(&config
->features_callee
, AST_FEATURE_PLAY_WARNING
);
4380 if (config
->start_sound
&& firstpass
) {
4382 bridge_playfile(c0
, c1
, config
->start_sound
, time_left_ms
/ 1000);
4384 bridge_playfile(c1
, c0
, config
->start_sound
, time_left_ms
/ 1000);
4387 /* Keep track of bridge */
4392 o0nativeformats
= c0
->nativeformats
;
4393 o1nativeformats
= c1
->nativeformats
;
4395 if (config
->feature_timer
) {
4396 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->feature_timer
, 1000));
4397 } else if (config
->timelimit
) {
4398 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->timelimit
, 1000));
4399 if (caller_warning
|| callee_warning
)
4400 nexteventts
= ast_tvsub(nexteventts
, ast_samp2tv(config
->play_warning
, 1000));
4403 if (!c0
->tech
->send_digit_begin
)
4404 ast_set_flag(c1
, AST_FLAG_END_DTMF_ONLY
);
4405 if (!c1
->tech
->send_digit_begin
)
4406 ast_set_flag(c0
, AST_FLAG_END_DTMF_ONLY
);
4407 manager_bridge_event(1, 1, c0
, c1
);
4409 /* Before we enter in and bridge these two together tell them both the source of audio has changed */
4410 ast_indicate(c0
, AST_CONTROL_SRCUPDATE
);
4411 ast_indicate(c1
, AST_CONTROL_SRCUPDATE
);
4413 for (/* ever */;;) {
4414 struct timeval now
= { 0, };
4416 const char *bridge_play_sound
= NULL
;
4420 if (!ast_tvzero(nexteventts
)) {
4422 to
= ast_tvdiff_ms(nexteventts
, now
);
4424 if (!config
->timelimit
) {
4425 res
= AST_BRIDGE_COMPLETE
;
4432 if (config
->timelimit
) {
4433 time_left_ms
= config
->timelimit
- ast_tvdiff_ms(now
, config
->start_time
);
4434 if (time_left_ms
< to
)
4437 if (time_left_ms
<= 0) {
4438 if (caller_warning
&& config
->end_sound
)
4439 bridge_playfile(c0
, c1
, config
->end_sound
, 0);
4440 if (callee_warning
&& config
->end_sound
)
4441 bridge_playfile(c1
, c0
, config
->end_sound
, 0);
4450 if (time_left_ms
>= 5000 && config
->warning_sound
&& config
->play_warning
) {
4451 int t
= (time_left_ms
+ 500) / 1000; /* round to nearest second */
4453 bridge_playfile(c0
, c1
, config
->warning_sound
, t
);
4455 bridge_playfile(c1
, c0
, config
->warning_sound
, t
);
4457 if (config
->warning_freq
&& (time_left_ms
> (config
->warning_freq
+ 5000)))
4458 nexteventts
= ast_tvadd(nexteventts
, ast_samp2tv(config
->warning_freq
, 1000));
4460 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->timelimit
, 1000));
4464 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
) {
4465 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4466 c0
->_softhangup
= 0;
4467 if (c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4468 c1
->_softhangup
= 0;
4471 ast_debug(1, "Unbridge signal received. Ending native bridge.\n");
4475 /* Stop if we're a zombie or need a soft hangup */
4476 if (ast_test_flag(c0
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c0
) ||
4477 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c1
)) {
4482 ast_debug(1, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
4484 ast_test_flag(c0
, AST_FLAG_ZOMBIE
) ? "Yes" : "No",
4485 ast_check_hangup(c0
) ? "Yes" : "No",
4486 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) ? "Yes" : "No",
4487 ast_check_hangup(c1
) ? "Yes" : "No");
4491 /* See if the BRIDGEPEER variable needs to be updated */
4492 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0
, "BRIDGEPEER")))
4493 pbx_builtin_setvar_helper(c0
, "BRIDGEPEER", c1
->name
);
4494 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1
, "BRIDGEPEER")))
4495 pbx_builtin_setvar_helper(c1
, "BRIDGEPEER", c0
->name
);
4496 if (c0
->tech
->get_pvt_uniqueid
)
4497 pbx_builtin_setvar_helper(c1
, "BRIDGEPVTCALLID", c0
->tech
->get_pvt_uniqueid(c0
));
4498 if (c1
->tech
->get_pvt_uniqueid
)
4499 pbx_builtin_setvar_helper(c0
, "BRIDGEPVTCALLID", c1
->tech
->get_pvt_uniqueid(c1
));
4501 /* See if we need to play an audio file to any side of the bridge */
4502 if ((bridge_play_sound
= pbx_builtin_getvar_helper(c0
, "BRIDGE_PLAY_SOUND"))) {
4503 bridge_playfile(c0
, c1
, bridge_play_sound
, 0);
4504 pbx_builtin_setvar_helper(c0
, "BRIDGE_PLAY_SOUND", NULL
);
4506 if ((bridge_play_sound
= pbx_builtin_getvar_helper(c1
, "BRIDGE_PLAY_SOUND"))) {
4507 bridge_playfile(c1
, c0
, bridge_play_sound
, 0);
4508 pbx_builtin_setvar_helper(c1
, "BRIDGE_PLAY_SOUND", NULL
);
4511 if (c0
->tech
->bridge
&&
4512 (c0
->tech
->bridge
== c1
->tech
->bridge
) &&
4513 !nativefailed
&& !c0
->monitor
&& !c1
->monitor
&&
4514 !c0
->audiohooks
&& !c1
->audiohooks
&&
4515 !c0
->masq
&& !c0
->masqr
&& !c1
->masq
&& !c1
->masqr
) {
4516 /* Looks like they share a bridge method and nothing else is in the way */
4517 ast_set_flag(c0
, AST_FLAG_NBRIDGE
);
4518 ast_set_flag(c1
, AST_FLAG_NBRIDGE
);
4519 if ((res
= c0
->tech
->bridge(c0
, c1
, config
->flags
, fo
, rc
, to
)) == AST_BRIDGE_COMPLETE
) {
4520 /* \todo XXX here should check that cid_num is not NULL */
4521 manager_event(EVENT_FLAG_CALL
, "Unlink",
4527 "CallerID2: %s\r\n",
4528 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4529 ast_debug(1, "Returning from native bridge, channels: %s, %s\n", c0
->name
, c1
->name
);
4531 ast_clear_flag(c0
, AST_FLAG_NBRIDGE
);
4532 ast_clear_flag(c1
, AST_FLAG_NBRIDGE
);
4534 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4542 ast_clear_flag(c0
, AST_FLAG_NBRIDGE
);
4543 ast_clear_flag(c1
, AST_FLAG_NBRIDGE
);
4546 case AST_BRIDGE_RETRY
:
4549 ast_verb(3, "Native bridging %s and %s ended\n", c0
->name
, c1
->name
);
4551 case AST_BRIDGE_FAILED_NOWARN
:
4557 if (((c0
->writeformat
!= c1
->readformat
) || (c0
->readformat
!= c1
->writeformat
) ||
4558 (c0
->nativeformats
!= o0nativeformats
) || (c1
->nativeformats
!= o1nativeformats
)) &&
4559 !(c0
->generator
|| c1
->generator
)) {
4560 if (ast_channel_make_compatible(c0
, c1
)) {
4561 ast_log(LOG_WARNING
, "Can't make %s and %s compatible\n", c0
->name
, c1
->name
);
4562 manager_bridge_event(0, 1, c0
, c1
);
4563 return AST_BRIDGE_FAILED
;
4565 o0nativeformats
= c0
->nativeformats
;
4566 o1nativeformats
= c1
->nativeformats
;
4569 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0
, "BRIDGEPEER")))
4570 pbx_builtin_setvar_helper(c0
, "BRIDGEPEER", c1
->name
);
4571 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1
, "BRIDGEPEER")))
4572 pbx_builtin_setvar_helper(c1
, "BRIDGEPEER", c0
->name
);
4574 res
= ast_generic_bridge(c0
, c1
, config
, fo
, rc
, nexteventts
);
4575 if (res
!= AST_BRIDGE_RETRY
)
4579 ast_clear_flag(c0
, AST_FLAG_END_DTMF_ONLY
);
4580 ast_clear_flag(c1
, AST_FLAG_END_DTMF_ONLY
);
4582 /* Now that we have broken the bridge the source will change yet again */
4583 ast_indicate(c0
, AST_CONTROL_SRCUPDATE
);
4584 ast_indicate(c1
, AST_CONTROL_SRCUPDATE
);
4589 /* \todo XXX here should check that cid_num is not NULL */
4590 manager_event(EVENT_FLAG_CALL
, "Unlink",
4596 "CallerID2: %s\r\n",
4597 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4598 ast_debug(1, "Bridge stops bridging channels %s and %s\n", c0
->name
, c1
->name
);
4603 /*! \brief Sets an option on a channel */
4604 int ast_channel_setoption(struct ast_channel
*chan
, int option
, void *data
, int datalen
, int block
)
4606 if (!chan
->tech
->setoption
) {
4612 ast_log(LOG_ERROR
, "XXX Blocking not implemented yet XXX\n");
4614 return chan
->tech
->setoption(chan
, option
, data
, datalen
);
4617 int ast_channel_queryoption(struct ast_channel
*chan
, int option
, void *data
, int *datalen
, int block
)
4619 if (!chan
->tech
->queryoption
) {
4625 ast_log(LOG_ERROR
, "XXX Blocking not implemented yet XXX\n");
4627 return chan
->tech
->queryoption(chan
, option
, data
, datalen
);
4630 struct tonepair_def
{
4637 struct tonepair_state
{
4651 unsigned char offset
[AST_FRIENDLY_OFFSET
];
4655 static void tonepair_release(struct ast_channel
*chan
, void *params
)
4657 struct tonepair_state
*ts
= params
;
4660 ast_set_write_format(chan
, ts
->origwfmt
);
4664 static void *tonepair_alloc(struct ast_channel
*chan
, void *params
)
4666 struct tonepair_state
*ts
;
4667 struct tonepair_def
*td
= params
;
4669 if (!(ts
= ast_calloc(1, sizeof(*ts
))))
4671 ts
->origwfmt
= chan
->writeformat
;
4672 if (ast_set_write_format(chan
, AST_FORMAT_SLINEAR
)) {
4673 ast_log(LOG_WARNING
, "Unable to set '%s' to signed linear format (write)\n", chan
->name
);
4674 tonepair_release(NULL
, ts
);
4677 ts
->fac1
= 2.0 * cos(2.0 * M_PI
* (td
->freq1
/ 8000.0)) * 32768.0;
4679 ts
->v2_1
= sin(-4.0 * M_PI
* (td
->freq1
/ 8000.0)) * td
->vol
;
4680 ts
->v3_1
= sin(-2.0 * M_PI
* (td
->freq1
/ 8000.0)) * td
->vol
;
4682 ts
->fac2
= 2.0 * cos(2.0 * M_PI
* (td
->freq2
/ 8000.0)) * 32768.0;
4683 ts
->v2_2
= sin(-4.0 * M_PI
* (td
->freq2
/ 8000.0)) * td
->vol
;
4684 ts
->v3_2
= sin(-2.0 * M_PI
* (td
->freq2
/ 8000.0)) * td
->vol
;
4685 ts
->duration
= td
->duration
;
4688 /* Let interrupts interrupt :) */
4689 ast_set_flag(chan
, AST_FLAG_WRITE_INT
);
4693 static int tonepair_generator(struct ast_channel
*chan
, void *data
, int len
, int samples
)
4695 struct tonepair_state
*ts
= data
;
4698 /* we need to prepare a frame with 16 * timelen samples as we're
4699 * generating SLIN audio
4703 if (len
> sizeof(ts
->data
) / 2 - 1) {
4704 ast_log(LOG_WARNING
, "Can't generate that much data!\n");
4707 memset(&ts
->f
, 0, sizeof(ts
->f
));
4708 for (x
=0;x
<len
/2;x
++) {
4709 ts
->v1_1
= ts
->v2_1
;
4710 ts
->v2_1
= ts
->v3_1
;
4711 ts
->v3_1
= (ts
->fac1
* ts
->v2_1
>> 15) - ts
->v1_1
;
4713 ts
->v1_2
= ts
->v2_2
;
4714 ts
->v2_2
= ts
->v3_2
;
4715 ts
->v3_2
= (ts
->fac2
* ts
->v2_2
>> 15) - ts
->v1_2
;
4718 p
= ts
->v3_2
- 32768;
4720 p
= ((p
* 9) / 10) + 1;
4721 ts
->data
[x
] = (ts
->v3_1
* p
) >> 15;
4723 ts
->data
[x
] = ts
->v3_1
+ ts
->v3_2
;
4725 ts
->f
.frametype
= AST_FRAME_VOICE
;
4726 ts
->f
.subclass
= AST_FORMAT_SLINEAR
;
4727 ts
->f
.datalen
= len
;
4728 ts
->f
.samples
= samples
;
4729 ts
->f
.offset
= AST_FRIENDLY_OFFSET
;
4730 ts
->f
.data
.ptr
= ts
->data
;
4731 ast_write(chan
, &ts
->f
);
4733 if (ts
->duration
> 0) {
4734 if (ts
->pos
>= ts
->duration
* 8)
4740 static struct ast_generator tonepair
= {
4741 alloc
: tonepair_alloc
,
4742 release
: tonepair_release
,
4743 generate
: tonepair_generator
,
4746 int ast_tonepair_start(struct ast_channel
*chan
, int freq1
, int freq2
, int duration
, int vol
)
4748 struct tonepair_def d
= { 0, };
4752 d
.duration
= duration
;
4753 d
.vol
= (vol
< 1) ? 8192 : vol
; /* force invalid to 8192 */
4754 if (ast_activate_generator(chan
, &tonepair
, &d
))
4759 void ast_tonepair_stop(struct ast_channel
*chan
)
4761 ast_deactivate_generator(chan
);
4764 int ast_tonepair(struct ast_channel
*chan
, int freq1
, int freq2
, int duration
, int vol
)
4768 if ((res
= ast_tonepair_start(chan
, freq1
, freq2
, duration
, vol
)))
4771 /* Give us some wiggle room */
4772 while (chan
->generatordata
&& ast_waitfor(chan
, 100) >= 0) {
4773 struct ast_frame
*f
= ast_read(chan
);
4782 ast_group_t
ast_get_group(const char *s
)
4786 int start
=0, finish
=0, x
;
4787 ast_group_t group
= 0;
4789 if (ast_strlen_zero(s
))
4794 while ((piece
= strsep(&c
, ","))) {
4795 if (sscanf(piece
, "%d-%d", &start
, &finish
) == 2) {
4797 } else if (sscanf(piece
, "%d", &start
)) {
4801 ast_log(LOG_ERROR
, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s
, piece
);
4804 for (x
= start
; x
<= finish
; x
++) {
4805 if ((x
> 63) || (x
< 0)) {
4806 ast_log(LOG_WARNING
, "Ignoring invalid group %d (maximum group is 63)\n", x
);
4808 group
|= ((ast_group_t
) 1 << x
);
4814 static int (*ast_moh_start_ptr
)(struct ast_channel
*, const char *, const char *) = NULL
;
4815 static void (*ast_moh_stop_ptr
)(struct ast_channel
*) = NULL
;
4816 static void (*ast_moh_cleanup_ptr
)(struct ast_channel
*) = NULL
;
4818 void ast_install_music_functions(int (*start_ptr
)(struct ast_channel
*, const char *, const char *),
4819 void (*stop_ptr
)(struct ast_channel
*),
4820 void (*cleanup_ptr
)(struct ast_channel
*))
4822 ast_moh_start_ptr
= start_ptr
;
4823 ast_moh_stop_ptr
= stop_ptr
;
4824 ast_moh_cleanup_ptr
= cleanup_ptr
;
4827 void ast_uninstall_music_functions(void)
4829 ast_moh_start_ptr
= NULL
;
4830 ast_moh_stop_ptr
= NULL
;
4831 ast_moh_cleanup_ptr
= NULL
;
4834 /*! \brief Turn on music on hold on a given channel */
4835 int ast_moh_start(struct ast_channel
*chan
, const char *mclass
, const char *interpclass
)
4837 if (ast_moh_start_ptr
)
4838 return ast_moh_start_ptr(chan
, mclass
, interpclass
);
4840 ast_verb(3, "Music class %s requested but no musiconhold loaded.\n", mclass
? mclass
: (interpclass
? interpclass
: "default"));
4845 /*! \brief Turn off music on hold on a given channel */
4846 void ast_moh_stop(struct ast_channel
*chan
)
4848 if (ast_moh_stop_ptr
)
4849 ast_moh_stop_ptr(chan
);
4852 void ast_moh_cleanup(struct ast_channel
*chan
)
4854 if (ast_moh_cleanup_ptr
)
4855 ast_moh_cleanup_ptr(chan
);
4858 void ast_channels_init(void)
4860 ast_cli_register_multiple(cli_channel
, ARRAY_LEN(cli_channel
));
4863 /*! \brief Print call group and pickup group ---*/
4864 char *ast_print_group(char *buf
, int buflen
, ast_group_t group
)
4872 if (!group
) /* Return empty string if no group */
4875 for (i
= 0; i
<= 63; i
++) { /* Max group is 63 */
4876 if (group
& ((ast_group_t
) 1 << i
)) {
4878 strncat(buf
, ", ", buflen
- strlen(buf
) - 1);
4882 snprintf(num
, sizeof(num
), "%u", i
);
4883 strncat(buf
, num
, buflen
- strlen(buf
) - 1);
4889 void ast_set_variables(struct ast_channel
*chan
, struct ast_variable
*vars
)
4891 struct ast_variable
*cur
;
4893 for (cur
= vars
; cur
; cur
= cur
->next
)
4894 pbx_builtin_setvar_helper(chan
, cur
->name
, cur
->value
);
4897 static void *silence_generator_alloc(struct ast_channel
*chan
, void *data
)
4899 /* just store the data pointer in the channel structure */
4903 static void silence_generator_release(struct ast_channel
*chan
, void *data
)
4908 static int silence_generator_generate(struct ast_channel
*chan
, void *data
, int len
, int samples
)
4911 struct ast_frame frame
= {
4912 .frametype
= AST_FRAME_VOICE
,
4913 .subclass
= AST_FORMAT_SLINEAR
,
4916 .datalen
= sizeof(buf
),
4919 memset(buf
, 0, sizeof(buf
));
4921 if (ast_write(chan
, &frame
))
4927 static struct ast_generator silence_generator
= {
4928 .alloc
= silence_generator_alloc
,
4929 .release
= silence_generator_release
,
4930 .generate
= silence_generator_generate
,
4933 struct ast_silence_generator
{
4934 int old_write_format
;
4937 struct ast_silence_generator
*ast_channel_start_silence_generator(struct ast_channel
*chan
)
4939 struct ast_silence_generator
*state
;
4941 if (!(state
= ast_calloc(1, sizeof(*state
)))) {
4945 state
->old_write_format
= chan
->writeformat
;
4947 if (ast_set_write_format(chan
, AST_FORMAT_SLINEAR
) < 0) {
4948 ast_log(LOG_ERROR
, "Could not set write format to SLINEAR\n");
4953 ast_activate_generator(chan
, &silence_generator
, state
);
4955 ast_debug(1, "Started silence generator on '%s'\n", chan
->name
);
4960 void ast_channel_stop_silence_generator(struct ast_channel
*chan
, struct ast_silence_generator
*state
)
4965 ast_deactivate_generator(chan
);
4967 ast_debug(1, "Stopped silence generator on '%s'\n", chan
->name
);
4969 if (ast_set_write_format(chan
, state
->old_write_format
) < 0)
4970 ast_log(LOG_ERROR
, "Could not return write format to its original state\n");
4976 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4977 const char *channelreloadreason2txt(enum channelreloadreason reason
)
4980 case CHANNEL_MODULE_LOAD
:
4981 return "LOAD (Channel module load)";
4983 case CHANNEL_MODULE_RELOAD
:
4984 return "RELOAD (Channel module reload)";
4986 case CHANNEL_CLI_RELOAD
:
4987 return "CLIRELOAD (Channel module reload by CLI command)";
4990 return "MANAGERRELOAD (Channel module reload by manager)";
4994 #ifdef DEBUG_CHANNEL_LOCKS
4996 /*! \brief Unlock AST channel (and print debugging output)
4997 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4999 int __ast_channel_unlock(struct ast_channel
*chan
, const char *filename
, int lineno
, const char *func
)
5002 ast_debug(3, "::::==== Unlocking AST channel %s\n", chan
->name
);
5005 ast_debug(1, "::::==== Unlocking non-existing channel \n");
5008 #ifdef DEBUG_THREADS
5009 res
= __ast_pthread_mutex_unlock(filename
, lineno
, func
, "(channel lock)", &chan
->lock_dont_use
);
5011 res
= ast_mutex_unlock(&chan
->lock_dont_use
);
5014 if (option_debug
> 2) {
5015 #ifdef DEBUG_THREADS
5017 if ((count
= chan
->lock_dont_use
.track
.reentrancy
))
5018 ast_debug(3, ":::=== Still have %d locks (recursive)\n", count
);
5021 ast_debug(3, "::::==== Channel %s was unlocked\n", chan
->name
);
5022 if (res
== EINVAL
) {
5023 ast_debug(3, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan
->name
);
5027 /* We had no lock, so okay any way*/
5028 ast_debug(4, "::::==== Channel %s was not locked at all \n", chan
->name
);
5034 /*! \brief Lock AST channel (and print debugging output)
5035 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
5036 int __ast_channel_lock(struct ast_channel
*chan
, const char *filename
, int lineno
, const char *func
)
5040 ast_debug(4, "====:::: Locking AST channel %s\n", chan
->name
);
5042 #ifdef DEBUG_THREADS
5043 res
= __ast_pthread_mutex_lock(filename
, lineno
, func
, "(channel lock)", &chan
->lock_dont_use
);
5045 res
= ast_mutex_lock(&chan
->lock_dont_use
);
5048 if (option_debug
> 3) {
5049 #ifdef DEBUG_THREADS
5051 if ((count
= chan
->lock_dont_use
.track
.reentrancy
))
5052 ast_debug(4, ":::=== Now have %d locks (recursive)\n", count
);
5055 ast_debug(4, "::::==== Channel %s was locked\n", chan
->name
);
5056 if (res
== EDEADLK
) {
5057 /* We had no lock, so okey any way */
5058 ast_debug(4, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan
->name
);
5060 if (res
== EINVAL
) {
5061 ast_debug(4, "::::==== Channel %s lock failed. No mutex.\n", chan
->name
);
5067 /*! \brief Lock AST channel (and print debugging output)
5068 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
5069 int __ast_channel_trylock(struct ast_channel
*chan
, const char *filename
, int lineno
, const char *func
)
5073 ast_debug(3, "====:::: Trying to lock AST channel %s\n", chan
->name
);
5074 #ifdef DEBUG_THREADS
5075 res
= __ast_pthread_mutex_trylock(filename
, lineno
, func
, "(channel lock)", &chan
->lock_dont_use
);
5077 res
= ast_mutex_trylock(&chan
->lock_dont_use
);
5080 if (option_debug
> 2) {
5081 #ifdef DEBUG_THREADS
5083 if ((count
= chan
->lock_dont_use
.track
.reentrancy
))
5084 ast_debug(3, ":::=== Now have %d locks (recursive)\n", count
);
5087 ast_debug(3, "::::==== Channel %s was locked\n", chan
->name
);
5089 /* We failed to lock */
5090 ast_debug(3, "::::==== Channel %s failed to lock. Not waiting around...\n", chan
->name
);
5092 if (res
== EDEADLK
) {
5093 /* We had no lock, so okey any way*/
5094 ast_debug(3, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan
->name
);
5097 ast_debug(3, "::::==== Channel %s lock failed. No mutex.\n", chan
->name
);
5105 * Wrappers for various ast_say_*() functions that call the full version
5106 * of the same functions.
5107 * The proper place would be say.c, but that file is optional and one
5108 * must be able to build asterisk even without it (using a loadable 'say'
5109 * implementation that only supplies the 'full' version of the functions.
5112 int ast_say_number(struct ast_channel
*chan
, int num
,
5113 const char *ints
, const char *language
, const char *options
)
5115 return ast_say_number_full(chan
, num
, ints
, language
, options
, -1, -1);
5118 int ast_say_enumeration(struct ast_channel
*chan
, int num
,
5119 const char *ints
, const char *language
, const char *options
)
5121 return ast_say_enumeration_full(chan
, num
, ints
, language
, options
, -1, -1);
5124 int ast_say_digits(struct ast_channel
*chan
, int num
,
5125 const char *ints
, const char *lang
)
5127 return ast_say_digits_full(chan
, num
, ints
, lang
, -1, -1);
5130 int ast_say_digit_str(struct ast_channel
*chan
, const char *str
,
5131 const char *ints
, const char *lang
)
5133 return ast_say_digit_str_full(chan
, str
, ints
, lang
, -1, -1);
5136 int ast_say_character_str(struct ast_channel
*chan
, const char *str
,
5137 const char *ints
, const char *lang
)
5139 return ast_say_character_str_full(chan
, str
, ints
, lang
, -1, -1);
5142 int ast_say_phonetic_str(struct ast_channel
*chan
, const char *str
,
5143 const char *ints
, const char *lang
)
5145 return ast_say_phonetic_str_full(chan
, str
, ints
, lang
, -1, -1);
5148 int ast_say_digits_full(struct ast_channel
*chan
, int num
,
5149 const char *ints
, const char *lang
, int audiofd
, int ctrlfd
)
5153 snprintf(buf
, sizeof(buf
), "%d", num
);
5155 return ast_say_digit_str_full(chan
, buf
, ints
, lang
, audiofd
, ctrlfd
);