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$")
41 #include <sys/ioctl.h>
42 #include <zaptel/zaptel.h>
45 #include "asterisk/pbx.h"
46 #include "asterisk/frame.h"
47 #include "asterisk/sched.h"
48 #include "asterisk/options.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/chanspy.h"
51 #include "asterisk/musiconhold.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/say.h"
54 #include "asterisk/file.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/translate.h"
57 #include "asterisk/manager.h"
58 #include "asterisk/chanvars.h"
59 #include "asterisk/linkedlists.h"
60 #include "asterisk/indications.h"
61 #include "asterisk/monitor.h"
62 #include "asterisk/causes.h"
63 #include "asterisk/callerid.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/app.h"
67 #include "asterisk/transcap.h"
68 #include "asterisk/devicestate.h"
69 #include "asterisk/sha1.h"
70 #include "asterisk/threadstorage.h"
71 #include "asterisk/slinfactory.h"
73 struct channel_spy_trans
{
75 struct ast_trans_pvt
*path
;
78 struct ast_channel_spy_list
{
79 struct channel_spy_trans read_translator
;
80 struct channel_spy_trans write_translator
;
81 AST_LIST_HEAD_NOLOCK(, ast_channel_spy
) list
;
84 struct ast_channel_whisper_buffer
{
86 struct ast_slinfactory sf
;
87 unsigned int original_format
;
88 struct ast_trans_pvt
*path
;
91 /* uncomment if you have problems with 'monitoring' synchronized files */
93 #define MONITOR_CONSTANT_DELAY
94 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
97 /*! Prevent new channel allocation if shutting down. */
98 static int shutting_down
;
100 static int uniqueint
;
102 unsigned long global_fin
, global_fout
;
104 AST_THREADSTORAGE(state2str_threadbuf
, state2str_threadbuf_init
);
105 #define STATE2STR_BUFSIZE 32
108 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
111 const struct ast_channel_tech
*tech
;
112 AST_LIST_ENTRY(chanlist
) list
;
115 /*! the list of registered channel types */
116 static AST_LIST_HEAD_NOLOCK_STATIC(backends
, chanlist
);
118 /*! the list of channels we have. Note that the lock for this list is used for
119 both the channels list and the backends list. */
120 static AST_LIST_HEAD_STATIC(channels
, ast_channel
);
122 /*! map AST_CAUSE's to readable string representations */
123 const struct ast_cause
{
128 { AST_CAUSE_UNALLOCATED
, "UNALLOCATED", "Unallocated (unassigned) number" },
129 { AST_CAUSE_NO_ROUTE_TRANSIT_NET
, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
130 { AST_CAUSE_NO_ROUTE_DESTINATION
, "NO_ROUTE_DESTINATION", "No route to destination" },
131 { AST_CAUSE_CHANNEL_UNACCEPTABLE
, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
132 { AST_CAUSE_CALL_AWARDED_DELIVERED
, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
133 { AST_CAUSE_NORMAL_CLEARING
, "NORMAL_CLEARING", "Normal Clearing" },
134 { AST_CAUSE_USER_BUSY
, "USER_BUSY", "User busy" },
135 { AST_CAUSE_NO_USER_RESPONSE
, "NO_USER_RESPONSE", "No user responding" },
136 { AST_CAUSE_NO_ANSWER
, "NO_ANSWER", "User alerting, no answer" },
137 { AST_CAUSE_CALL_REJECTED
, "CALL_REJECTED", "Call Rejected" },
138 { AST_CAUSE_NUMBER_CHANGED
, "NUMBER_CHANGED", "Number changed" },
139 { AST_CAUSE_DESTINATION_OUT_OF_ORDER
, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
140 { AST_CAUSE_INVALID_NUMBER_FORMAT
, "INVALID_NUMBER_FORMAT", "Invalid number format" },
141 { AST_CAUSE_FACILITY_REJECTED
, "FACILITY_REJECTED", "Facility rejected" },
142 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY
, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
143 { AST_CAUSE_NORMAL_UNSPECIFIED
, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
144 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION
, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
145 { AST_CAUSE_NETWORK_OUT_OF_ORDER
, "NETWORK_OUT_OF_ORDER", "Network out of order" },
146 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE
, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
147 { AST_CAUSE_SWITCH_CONGESTION
, "SWITCH_CONGESTION", "Switching equipment congestion" },
148 { AST_CAUSE_ACCESS_INFO_DISCARDED
, "ACCESS_INFO_DISCARDED", "Access information discarded" },
149 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL
, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
150 { AST_CAUSE_PRE_EMPTED
, "PRE_EMPTED", "Pre-empted" },
151 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED
, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
152 { AST_CAUSE_OUTGOING_CALL_BARRED
, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
153 { AST_CAUSE_INCOMING_CALL_BARRED
, "INCOMING_CALL_BARRED", "Incoming call barred" },
154 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH
, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
155 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
156 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL
, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
157 { AST_CAUSE_CHAN_NOT_IMPLEMENTED
, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
158 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED
, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
159 { AST_CAUSE_INVALID_CALL_REFERENCE
, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
160 { AST_CAUSE_INCOMPATIBLE_DESTINATION
, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
161 { AST_CAUSE_INVALID_MSG_UNSPECIFIED
, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
162 { AST_CAUSE_MANDATORY_IE_MISSING
, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
163 { AST_CAUSE_MESSAGE_TYPE_NONEXIST
, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
164 { AST_CAUSE_WRONG_MESSAGE
, "WRONG_MESSAGE", "Wrong message" },
165 { AST_CAUSE_IE_NONEXIST
, "IE_NONEXIST", "Info. element nonexist or not implemented" },
166 { AST_CAUSE_INVALID_IE_CONTENTS
, "INVALID_IE_CONTENTS", "Invalid information element contents" },
167 { AST_CAUSE_WRONG_CALL_STATE
, "WRONG_CALL_STATE", "Message not compatible with call state" },
168 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE
, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
169 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR
, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
170 { AST_CAUSE_PROTOCOL_ERROR
, "PROTOCOL_ERROR", "Protocol error, unspecified" },
171 { AST_CAUSE_INTERWORKING
, "INTERWORKING", "Interworking, unspecified" },
174 struct ast_variable
*ast_channeltype_list(void)
177 struct ast_variable
*var
=NULL
, *prev
= NULL
;
178 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
180 if ((prev
->next
= ast_variable_new(cl
->tech
->type
, cl
->tech
->description
)))
183 var
= ast_variable_new(cl
->tech
->type
, cl
->tech
->description
);
190 static int show_channeltypes(int fd
, int argc
, char *argv
[])
192 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
196 ast_cli(fd
, FORMAT
, "Type", "Description", "Devicestate", "Indications", "Transfer");
197 ast_cli(fd
, FORMAT
, "----------", "-----------", "-----------", "-----------", "--------");
198 if (AST_LIST_LOCK(&channels
)) {
199 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
202 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
203 ast_cli(fd
, FORMAT
, cl
->tech
->type
, cl
->tech
->description
,
204 (cl
->tech
->devicestate
) ? "yes" : "no",
205 (cl
->tech
->indicate
) ? "yes" : "no",
206 (cl
->tech
->transfer
) ? "yes" : "no");
209 AST_LIST_UNLOCK(&channels
);
210 ast_cli(fd
, "----------\n%d channel drivers registered.\n", count_chan
);
211 return RESULT_SUCCESS
;
217 static int show_channeltype_deprecated(int fd
, int argc
, char *argv
[])
219 struct chanlist
*cl
= NULL
;
222 return RESULT_SHOWUSAGE
;
224 if (AST_LIST_LOCK(&channels
)) {
225 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
226 return RESULT_FAILURE
;
229 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
230 if (!strncasecmp(cl
->tech
->type
, argv
[2], strlen(cl
->tech
->type
))) {
237 ast_cli(fd
, "\n%s is not a registered channel driver.\n", argv
[2]);
238 AST_LIST_UNLOCK(&channels
);
239 return RESULT_FAILURE
;
243 "-- Info about channel driver: %s --\n"
244 " Device State: %s\n"
247 " Capabilities: %d\n"
251 " Image Support: %s\n"
252 " Text Support: %s\n",
254 (cl
->tech
->devicestate
) ? "yes" : "no",
255 (cl
->tech
->indicate
) ? "yes" : "no",
256 (cl
->tech
->transfer
) ? "yes" : "no",
257 (cl
->tech
->capabilities
) ? cl
->tech
->capabilities
: -1,
258 (cl
->tech
->send_digit_begin
) ? "yes" : "no",
259 (cl
->tech
->send_digit_end
) ? "yes" : "no",
260 (cl
->tech
->send_html
) ? "yes" : "no",
261 (cl
->tech
->send_image
) ? "yes" : "no",
262 (cl
->tech
->send_text
) ? "yes" : "no"
266 AST_LIST_UNLOCK(&channels
);
267 return RESULT_SUCCESS
;
270 static int show_channeltype(int fd
, int argc
, char *argv
[])
272 struct chanlist
*cl
= NULL
;
275 return RESULT_SHOWUSAGE
;
277 if (AST_LIST_LOCK(&channels
)) {
278 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
279 return RESULT_FAILURE
;
282 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
283 if (!strncasecmp(cl
->tech
->type
, argv
[3], strlen(cl
->tech
->type
))) {
290 ast_cli(fd
, "\n%s is not a registered channel driver.\n", argv
[3]);
291 AST_LIST_UNLOCK(&channels
);
292 return RESULT_FAILURE
;
296 "-- Info about channel driver: %s --\n"
297 " Device State: %s\n"
300 " Capabilities: %d\n"
304 " Image Support: %s\n"
305 " Text Support: %s\n",
307 (cl
->tech
->devicestate
) ? "yes" : "no",
308 (cl
->tech
->indicate
) ? "yes" : "no",
309 (cl
->tech
->transfer
) ? "yes" : "no",
310 (cl
->tech
->capabilities
) ? cl
->tech
->capabilities
: -1,
311 (cl
->tech
->send_digit_begin
) ? "yes" : "no",
312 (cl
->tech
->send_digit_end
) ? "yes" : "no",
313 (cl
->tech
->send_html
) ? "yes" : "no",
314 (cl
->tech
->send_image
) ? "yes" : "no",
315 (cl
->tech
->send_text
) ? "yes" : "no"
319 AST_LIST_UNLOCK(&channels
);
320 return RESULT_SUCCESS
;
323 static char *complete_channeltypes_deprecated(const char *line
, const char *word
, int pos
, int state
)
333 wordlen
= strlen(word
);
335 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
336 if (!strncasecmp(word
, cl
->tech
->type
, wordlen
) && ++which
> state
) {
337 ret
= strdup(cl
->tech
->type
);
345 static char *complete_channeltypes(const char *line
, const char *word
, int pos
, int state
)
355 wordlen
= strlen(word
);
357 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
358 if (!strncasecmp(word
, cl
->tech
->type
, wordlen
) && ++which
> state
) {
359 ret
= strdup(cl
->tech
->type
);
367 static char show_channeltypes_usage
[] =
368 "Usage: core show channeltypes\n"
369 " Lists available channel types registered in your Asterisk server.\n";
371 static char show_channeltype_usage
[] =
372 "Usage: core show channeltype <name>\n"
373 " Show details about the specified channel type, <name>.\n";
375 static struct ast_cli_entry cli_show_channeltypes_deprecated
= {
376 { "show", "channeltypes", NULL
},
377 show_channeltypes
, NULL
,
380 static struct ast_cli_entry cli_show_channeltype_deprecated
= {
381 { "show", "channeltype", NULL
},
382 show_channeltype_deprecated
, NULL
,
383 NULL
, complete_channeltypes_deprecated
};
385 static struct ast_cli_entry cli_channel
[] = {
386 { { "core", "show", "channeltypes", NULL
},
387 show_channeltypes
, "List available channel types",
388 show_channeltypes_usage
, NULL
, &cli_show_channeltypes_deprecated
},
390 { { "core", "show", "channeltype", NULL
},
391 show_channeltype
, "Give more details on that channel type",
392 show_channeltype_usage
, complete_channeltypes
, &cli_show_channeltype_deprecated
},
395 /*! \brief Checks to see if a channel is needing hang up */
396 int ast_check_hangup(struct ast_channel
*chan
)
398 if (chan
->_softhangup
) /* yes if soft hangup flag set */
400 if (!chan
->tech_pvt
) /* yes if no technology private data */
402 if (!chan
->whentohangup
) /* no if no hangup scheduled */
404 if (chan
->whentohangup
> time(NULL
)) /* no if hangup time has not come yet. */
406 chan
->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
; /* record event */
410 static int ast_check_hangup_locked(struct ast_channel
*chan
)
413 ast_channel_lock(chan
);
414 res
= ast_check_hangup(chan
);
415 ast_channel_unlock(chan
);
419 /*! \brief printf the string into a correctly sized mallocd buffer, and return the buffer */
420 char *ast_safe_string_alloc(const char *fmt
, ...)
427 len
= vsnprintf(buf
, 1, fmt
, args
);
428 b2
= ast_malloc(len
+1);
429 vsnprintf(b2
, len
+1, fmt
, args
);
434 /*! \brief Initiate system shutdown */
435 void ast_begin_shutdown(int hangup
)
437 struct ast_channel
*c
;
440 AST_LIST_LOCK(&channels
);
441 AST_LIST_TRAVERSE(&channels
, c
, chan_list
)
442 ast_softhangup(c
, AST_SOFTHANGUP_SHUTDOWN
);
443 AST_LIST_UNLOCK(&channels
);
447 /*! \brief returns number of active/allocated channels */
448 int ast_active_channels(void)
450 struct ast_channel
*c
;
452 AST_LIST_LOCK(&channels
);
453 AST_LIST_TRAVERSE(&channels
, c
, chan_list
)
455 AST_LIST_UNLOCK(&channels
);
459 /*! \brief Cancel a shutdown in progress */
460 void ast_cancel_shutdown(void)
465 /*! \brief Returns non-zero if Asterisk is being shut down */
466 int ast_shutting_down(void)
468 return shutting_down
;
471 /*! \brief Set when to hangup channel */
472 void ast_channel_setwhentohangup(struct ast_channel
*chan
, time_t offset
)
474 chan
->whentohangup
= offset
? time(NULL
) + offset
: 0;
475 ast_queue_frame(chan
, &ast_null_frame
);
479 /*! \brief Compare a offset with when to hangup channel */
480 int ast_channel_cmpwhentohangup(struct ast_channel
*chan
, time_t offset
)
484 if (chan
->whentohangup
== 0) {
485 return (offset
== 0) ? 0 : -1;
487 if (offset
== 0) /* XXX why is this special ? */
490 whentohangup
= offset
+ time (NULL
);
491 if (chan
->whentohangup
< whentohangup
)
493 else if (chan
->whentohangup
== whentohangup
)
501 /*! \brief Register a new telephony channel in Asterisk */
502 int ast_channel_register(const struct ast_channel_tech
*tech
)
504 struct chanlist
*chan
;
506 AST_LIST_LOCK(&channels
);
508 AST_LIST_TRAVERSE(&backends
, chan
, list
) {
509 if (!strcasecmp(tech
->type
, chan
->tech
->type
)) {
510 ast_log(LOG_WARNING
, "Already have a handler for type '%s'\n", tech
->type
);
511 AST_LIST_UNLOCK(&channels
);
516 if (!(chan
= ast_calloc(1, sizeof(*chan
)))) {
517 AST_LIST_UNLOCK(&channels
);
521 AST_LIST_INSERT_HEAD(&backends
, chan
, list
);
524 ast_log(LOG_DEBUG
, "Registered handler for '%s' (%s)\n", chan
->tech
->type
, chan
->tech
->description
);
526 if (option_verbose
> 1)
527 ast_verbose(VERBOSE_PREFIX_2
"Registered channel type '%s' (%s)\n", chan
->tech
->type
,
528 chan
->tech
->description
);
530 AST_LIST_UNLOCK(&channels
);
534 void ast_channel_unregister(const struct ast_channel_tech
*tech
)
536 struct chanlist
*chan
;
539 ast_log(LOG_DEBUG
, "Unregistering channel type '%s'\n", tech
->type
);
541 AST_LIST_LOCK(&channels
);
543 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends
, chan
, list
) {
544 if (chan
->tech
== tech
) {
545 AST_LIST_REMOVE_CURRENT(&backends
, list
);
547 if (option_verbose
> 1)
548 ast_verbose(VERBOSE_PREFIX_2
"Unregistered channel type '%s'\n", tech
->type
);
552 AST_LIST_TRAVERSE_SAFE_END
554 AST_LIST_UNLOCK(&channels
);
557 const struct ast_channel_tech
*ast_get_channel_tech(const char *name
)
559 struct chanlist
*chanls
;
560 const struct ast_channel_tech
*ret
= NULL
;
562 if (AST_LIST_LOCK(&channels
)) {
563 ast_log(LOG_WARNING
, "Unable to lock channel tech list\n");
567 AST_LIST_TRAVERSE(&backends
, chanls
, list
) {
568 if (!strcasecmp(name
, chanls
->tech
->type
)) {
574 AST_LIST_UNLOCK(&channels
);
579 /*! \brief Gives the string form of a given hangup cause */
580 const char *ast_cause2str(int cause
)
584 for (x
=0; x
< sizeof(causes
) / sizeof(causes
[0]); x
++) {
585 if (causes
[x
].cause
== cause
)
586 return causes
[x
].desc
;
592 /*! \brief Convert a symbolic hangup cause to number */
593 int ast_str2cause(const char *name
)
597 for (x
= 0; x
< sizeof(causes
) / sizeof(causes
[0]); x
++)
598 if (strncasecmp(causes
[x
].name
, name
, strlen(causes
[x
].name
)) == 0)
599 return causes
[x
].cause
;
604 /*! \brief Gives the string form of a given channel state */
605 char *ast_state2str(enum ast_channel_state state
)
612 case AST_STATE_RESERVED
:
614 case AST_STATE_OFFHOOK
:
616 case AST_STATE_DIALING
:
620 case AST_STATE_RINGING
:
626 case AST_STATE_DIALING_OFFHOOK
:
627 return "Dialing Offhook";
628 case AST_STATE_PRERING
:
631 if (!(buf
= ast_threadstorage_get(&state2str_threadbuf
, STATE2STR_BUFSIZE
)))
633 snprintf(buf
, STATE2STR_BUFSIZE
, "Unknown (%d)", state
);
638 /*! \brief Gives the string form of a given transfer capability */
639 char *ast_transfercapability2str(int transfercapability
)
641 switch(transfercapability
) {
642 case AST_TRANS_CAP_SPEECH
:
644 case AST_TRANS_CAP_DIGITAL
:
646 case AST_TRANS_CAP_RESTRICTED_DIGITAL
:
647 return "RESTRICTED_DIGITAL";
648 case AST_TRANS_CAP_3_1K_AUDIO
:
650 case AST_TRANS_CAP_DIGITAL_W_TONES
:
651 return "DIGITAL_W_TONES";
652 case AST_TRANS_CAP_VIDEO
:
659 /*! \brief Pick the best audio codec */
660 int ast_best_codec(int fmts
)
662 /* This just our opinion, expressed in code. We are asked to choose
663 the best codec to use, given no information */
667 /*! Okay, ulaw is used by all telephony equipment, so start with it */
669 /*! Unless of course, you're a silly European, so then prefer ALAW */
671 /*! Okay, well, signed linear is easy to translate into other stuff */
673 /*! G.726 is standard ADPCM, in RFC3551 packing order */
675 /*! G.726 is standard ADPCM, in AAL2 packing order */
676 AST_FORMAT_G726_AAL2
,
677 /*! ADPCM has great sound quality and is still pretty easy to translate */
679 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
680 translate and sounds pretty good */
682 /*! iLBC is not too bad */
684 /*! Speex is free, but computationally more expensive than GSM */
686 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
689 /*! G.729a is faster than 723 and slightly less expensive */
691 /*! Down to G.723.1 which is proprietary but at least designed for voice */
695 /* Strip out video */
696 fmts
&= AST_FORMAT_AUDIO_MASK
;
698 /* Find the first preferred codec in the format given */
699 for (x
=0; x
< (sizeof(prefs
) / sizeof(prefs
[0]) ); x
++)
702 ast_log(LOG_WARNING
, "Don't know any of 0x%x formats\n", fmts
);
706 static const struct ast_channel_tech null_tech
= {
708 .description
= "Null channel (should not see this)",
711 /*! \brief Create a new channel structure */
712 struct ast_channel
*ast_channel_alloc(int needqueue
, int state
, const char *cid_num
, const char *cid_name
, const char *name_fmt
, ...)
714 struct ast_channel
*tmp
;
717 struct varshead
*headp
;
720 /* If shutting down, don't allocate any new channels */
722 ast_log(LOG_WARNING
, "Channel allocation failed: Refusing due to active shutdown\n");
726 if (!(tmp
= ast_calloc(1, sizeof(*tmp
))))
729 if (!(tmp
->sched
= sched_context_create())) {
730 ast_log(LOG_WARNING
, "Channel allocation failed: Unable to create schedule context\n");
735 ast_string_field_init(tmp
, 128);
737 /* Don't bother initializing the last two FD here, because they
738 will *always* be set just a few lines down (AST_TIMING_FD,
740 for (x
= 0; x
< AST_MAX_FDS
- 2; x
++)
744 tmp
->timingfd
= open("/dev/zap/timer", O_RDWR
);
745 if (tmp
->timingfd
> -1) {
746 /* Check if timing interface supports new
749 if (!ioctl(tmp
->timingfd
, ZT_TIMERPONG
, &flags
))
757 if (pipe(tmp
->alertpipe
)) {
758 ast_log(LOG_WARNING
, "Channel allocation failed: Can't create alert pipe!\n");
759 ast_string_field_free_pools(tmp
);
763 flags
= fcntl(tmp
->alertpipe
[0], F_GETFL
);
764 fcntl(tmp
->alertpipe
[0], F_SETFL
, flags
| O_NONBLOCK
);
765 flags
= fcntl(tmp
->alertpipe
[1], F_GETFL
);
766 fcntl(tmp
->alertpipe
[1], F_SETFL
, flags
| O_NONBLOCK
);
768 } else /* Make sure we've got it done right if they don't */
769 tmp
->alertpipe
[0] = tmp
->alertpipe
[1] = -1;
771 /* Always watch the alertpipe */
772 tmp
->fds
[AST_ALERT_FD
] = tmp
->alertpipe
[0];
773 /* And timing pipe */
774 tmp
->fds
[AST_TIMING_FD
] = tmp
->timingfd
;
775 ast_string_field_set(tmp
, name
, "**Unknown**");
782 tmp
->fin
= global_fin
;
783 tmp
->fout
= global_fout
;
785 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME
)) {
786 ast_string_field_build(tmp
, uniqueid
, "%li.%d", (long) time(NULL
),
787 ast_atomic_fetchadd_int(&uniqueint
, 1));
789 ast_string_field_build(tmp
, uniqueid
, "%s-%li.%d", ast_config_AST_SYSTEM_NAME
,
790 (long) time(NULL
), ast_atomic_fetchadd_int(&uniqueint
, 1));
793 if (!ast_strlen_zero(name_fmt
)) {
794 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
795 * And they all use slightly different formats for their name string.
796 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
797 * This means, that the stringfields must have a routine that takes the va_lists directly, and
798 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
799 * This new function was written so this can be accomplished.
801 va_start(ap1
, name_fmt
);
802 va_start(ap2
, name_fmt
);
803 ast_string_field_build_va(tmp
, name
, name_fmt
, ap1
, ap2
);
807 /* and now, since the channel structure is built, and has its name, let's call the
808 * manager event generator with this Newchannel event. This is the proper and correct
809 * place to make this call, but you sure do have to pass a lot of data into this func
812 manager_event(EVENT_FLAG_CALL
, "Newchannel",
815 "CallerIDNum: %s\r\n"
816 "CallerIDName: %s\r\n"
818 tmp
->name
, ast_state2str(state
),
819 S_OR(cid_num
, "<unknown>"),
820 S_OR(cid_name
, "<unknown>"),
824 headp
= &tmp
->varshead
;
825 AST_LIST_HEAD_INIT_NOLOCK(headp
);
827 ast_mutex_init(&tmp
->lock
);
829 AST_LIST_HEAD_INIT_NOLOCK(&tmp
->datastores
);
831 strcpy(tmp
->context
, "default");
832 strcpy(tmp
->exten
, "s");
835 ast_string_field_set(tmp
, language
, defaultlanguage
);
836 tmp
->amaflags
= ast_default_amaflags
;
837 ast_string_field_set(tmp
, accountcode
, ast_default_accountcode
);
839 tmp
->tech
= &null_tech
;
841 AST_LIST_LOCK(&channels
);
842 AST_LIST_INSERT_HEAD(&channels
, tmp
, chan_list
);
843 AST_LIST_UNLOCK(&channels
);
848 /*! \brief Queue an outgoing media frame */
849 int ast_queue_frame(struct ast_channel
*chan
, struct ast_frame
*fin
)
852 struct ast_frame
*cur
;
856 /* Build us a copy and free the original one */
857 if (!(f
= ast_frdup(fin
))) {
858 ast_log(LOG_WARNING
, "Unable to duplicate frame\n");
861 ast_channel_lock(chan
);
863 /* See if the last frame on the queue is a hangup, if so don't queue anything */
864 if ((cur
= AST_LIST_LAST(&chan
->readq
)) && (cur
->frametype
== AST_FRAME_CONTROL
) && (cur
->subclass
== AST_CONTROL_HANGUP
)) {
866 ast_channel_unlock(chan
);
870 /* Count how many frames exist on the queue */
871 AST_LIST_TRAVERSE(&chan
->readq
, cur
, frame_list
) {
875 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
876 if (((fin
->frametype
== AST_FRAME_VOICE
) && (qlen
> 96)) || (qlen
> 128)) {
877 if (fin
->frametype
!= AST_FRAME_VOICE
) {
878 ast_log(LOG_WARNING
, "Exceptionally long queue length queuing to %s\n", chan
->name
);
882 ast_log(LOG_DEBUG
, "Dropping voice to exceptionally long queue on %s\n", chan
->name
);
884 ast_channel_unlock(chan
);
888 AST_LIST_INSERT_TAIL(&chan
->readq
, f
, frame_list
);
889 if (chan
->alertpipe
[1] > -1) {
890 if (write(chan
->alertpipe
[1], &blah
, sizeof(blah
)) != sizeof(blah
))
891 ast_log(LOG_WARNING
, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
892 chan
->name
, f
->frametype
, f
->subclass
, qlen
, strerror(errno
));
894 } else if (chan
->timingfd
> -1) {
895 ioctl(chan
->timingfd
, ZT_TIMERPING
, &blah
);
897 } else if (ast_test_flag(chan
, AST_FLAG_BLOCKING
)) {
898 pthread_kill(chan
->blocker
, SIGURG
);
900 ast_channel_unlock(chan
);
904 /*! \brief Queue a hangup frame for channel */
905 int ast_queue_hangup(struct ast_channel
*chan
)
907 struct ast_frame f
= { AST_FRAME_CONTROL
, AST_CONTROL_HANGUP
};
908 /* Yeah, let's not change a lock-critical value without locking */
909 if (!ast_channel_trylock(chan
)) {
910 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
911 ast_channel_unlock(chan
);
913 return ast_queue_frame(chan
, &f
);
916 /*! \brief Queue a control frame */
917 int ast_queue_control(struct ast_channel
*chan
, enum ast_control_frame_type control
)
919 struct ast_frame f
= { AST_FRAME_CONTROL
, };
921 f
.subclass
= control
;
923 return ast_queue_frame(chan
, &f
);
926 /*! \brief Queue a control frame with payload */
927 int ast_queue_control_data(struct ast_channel
*chan
, enum ast_control_frame_type control
,
928 const void *data
, size_t datalen
)
930 struct ast_frame f
= { AST_FRAME_CONTROL
, };
932 f
.subclass
= control
;
933 f
.data
= (void *) data
;
936 return ast_queue_frame(chan
, &f
);
939 /*! \brief Set defer DTMF flag on channel */
940 int ast_channel_defer_dtmf(struct ast_channel
*chan
)
945 pre
= ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
);
946 ast_set_flag(chan
, AST_FLAG_DEFER_DTMF
);
951 /*! \brief Unset defer DTMF flag on channel */
952 void ast_channel_undefer_dtmf(struct ast_channel
*chan
)
955 ast_clear_flag(chan
, AST_FLAG_DEFER_DTMF
);
959 * \brief Helper function to find channels.
961 * It supports these modes:
963 * prev != NULL : get channel next in list after prev
964 * name != NULL : get channel with matching name
965 * name != NULL && namelen != 0 : get channel whose name starts with prefix
966 * exten != NULL : get channel whose exten or macroexten matches
967 * context != NULL && exten != NULL : get channel whose context or macrocontext
969 * It returns with the channel's lock held. If getting the individual lock fails,
970 * unlock and retry quickly up to 10 times, then give up.
972 * \note XXX Note that this code has cost O(N) because of the need to verify
973 * that the object is still on the global list.
975 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
976 * can only be done with the lock held or someone could delete the
977 * object while we work on it. This causes some ugliness in the code.
978 * Note that removing the first ast_log() may be harmful, as it would
979 * shorten the retry period and possibly cause failures.
980 * We should definitely go for a better scheme that is deadlock-free.
982 static struct ast_channel
*channel_find_locked(const struct ast_channel
*prev
,
983 const char *name
, const int namelen
,
984 const char *context
, const char *exten
)
986 const char *msg
= prev
? "deadlock" : "initial deadlock";
988 struct ast_channel
*c
;
990 for (retries
= 0; retries
< 10; retries
++) {
992 AST_LIST_LOCK(&channels
);
993 AST_LIST_TRAVERSE(&channels
, c
, chan_list
) {
994 if (prev
) { /* look for next item */
995 if (c
!= prev
) /* not this one */
997 /* found, prepare to return c->next */
998 c
= AST_LIST_NEXT(c
, chan_list
);
1000 if (name
) { /* want match by name */
1001 if ((!namelen
&& strcasecmp(c
->name
, name
)) ||
1002 (namelen
&& strncasecmp(c
->name
, name
, namelen
)))
1003 continue; /* name match failed */
1005 if (context
&& strcasecmp(c
->context
, context
) &&
1006 strcasecmp(c
->macrocontext
, context
))
1007 continue; /* context match failed */
1008 if (strcasecmp(c
->exten
, exten
) &&
1009 strcasecmp(c
->macroexten
, exten
))
1010 continue; /* exten match failed */
1012 /* if we get here, c points to the desired record */
1015 /* exit if chan not found or mutex acquired successfully */
1016 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1017 done
= c
== NULL
|| ast_channel_trylock(c
) == 0;
1020 ast_log(LOG_DEBUG
, "Avoiding %s for channel '%p'\n", msg
, c
);
1021 AST_LIST_UNLOCK(&channels
);
1024 usleep(1); /* give other threads a chance before retrying */
1027 * c is surely not null, but we don't have the lock so cannot
1031 ast_log(LOG_DEBUG
, "Failure, could not lock '%p' after %d retries!\n",
1037 /*! \brief Browse channels in use */
1038 struct ast_channel
*ast_channel_walk_locked(const struct ast_channel
*prev
)
1040 return channel_find_locked(prev
, NULL
, 0, NULL
, NULL
);
1043 /*! \brief Get channel by name and lock it */
1044 struct ast_channel
*ast_get_channel_by_name_locked(const char *name
)
1046 return channel_find_locked(NULL
, name
, 0, NULL
, NULL
);
1049 /*! \brief Get channel by name prefix and lock it */
1050 struct ast_channel
*ast_get_channel_by_name_prefix_locked(const char *name
, const int namelen
)
1052 return channel_find_locked(NULL
, name
, namelen
, NULL
, NULL
);
1055 /*! \brief Get next channel by name prefix and lock it */
1056 struct ast_channel
*ast_walk_channel_by_name_prefix_locked(const struct ast_channel
*chan
, const char *name
,
1059 return channel_find_locked(chan
, name
, namelen
, NULL
, NULL
);
1062 /*! \brief Get channel by exten (and optionally context) and lock it */
1063 struct ast_channel
*ast_get_channel_by_exten_locked(const char *exten
, const char *context
)
1065 return channel_find_locked(NULL
, NULL
, 0, context
, exten
);
1068 /*! \brief Get next channel by exten (and optionally context) and lock it */
1069 struct ast_channel
*ast_walk_channel_by_exten_locked(const struct ast_channel
*chan
, const char *exten
,
1070 const char *context
)
1072 return channel_find_locked(chan
, NULL
, 0, context
, exten
);
1075 /*! \brief Wait, look for hangups and condition arg */
1076 int ast_safe_sleep_conditional(struct ast_channel
*chan
, int ms
, int (*cond
)(void*), void *data
)
1078 struct ast_frame
*f
;
1081 if (cond
&& ((*cond
)(data
) == 0))
1083 ms
= ast_waitfor(chan
, ms
);
1096 /*! \brief Wait, look for hangups */
1097 int ast_safe_sleep(struct ast_channel
*chan
, int ms
)
1099 return ast_safe_sleep_conditional(chan
, ms
, NULL
, NULL
);
1102 static void free_cid(struct ast_callerid
*cid
)
1105 free(cid
->cid_dnid
);
1109 free(cid
->cid_name
);
1113 free(cid
->cid_rdnis
);
1116 /*! \brief Free a channel structure */
1117 void ast_channel_free(struct ast_channel
*chan
)
1120 struct ast_var_t
*vardata
;
1121 struct ast_frame
*f
;
1122 struct varshead
*headp
;
1123 struct ast_datastore
*datastore
= NULL
;
1124 char name
[AST_CHANNEL_NAME
];
1126 headp
=&chan
->varshead
;
1128 AST_LIST_LOCK(&channels
);
1129 AST_LIST_REMOVE(&channels
, chan
, chan_list
);
1130 /* Lock and unlock the channel just to be sure nobody
1131 has it locked still */
1132 ast_channel_lock(chan
);
1133 ast_channel_unlock(chan
);
1134 if (chan
->tech_pvt
) {
1135 ast_log(LOG_WARNING
, "Channel '%s' may not have been hung up properly\n", chan
->name
);
1136 free(chan
->tech_pvt
);
1140 sched_context_destroy(chan
->sched
);
1142 ast_copy_string(name
, chan
->name
, sizeof(name
));
1144 /* Stop monitoring */
1146 chan
->monitor
->stop( chan
, 0 );
1148 /* If there is native format music-on-hold state, free it */
1149 if (chan
->music_state
)
1150 ast_moh_cleanup(chan
);
1152 /* if someone is whispering on the channel, stop them */
1154 ast_channel_whisper_stop(chan
);
1156 /* Free translators */
1157 if (chan
->readtrans
)
1158 ast_translator_free_path(chan
->readtrans
);
1159 if (chan
->writetrans
)
1160 ast_translator_free_path(chan
->writetrans
);
1162 ast_log(LOG_WARNING
, "PBX may not have been terminated properly on '%s'\n", chan
->name
);
1163 free_cid(&chan
->cid
);
1164 ast_mutex_destroy(&chan
->lock
);
1165 /* Close pipes if appropriate */
1166 if ((fd
= chan
->alertpipe
[0]) > -1)
1168 if ((fd
= chan
->alertpipe
[1]) > -1)
1170 if ((fd
= chan
->timingfd
) > -1)
1172 while ((f
= AST_LIST_REMOVE_HEAD(&chan
->readq
, frame_list
)))
1175 /* Get rid of each of the data stores on the channel */
1176 while ((datastore
= AST_LIST_REMOVE_HEAD(&chan
->datastores
, entry
)))
1177 /* Free the data store */
1178 ast_channel_datastore_free(datastore
);
1179 AST_LIST_HEAD_INIT_NOLOCK(&chan
->datastores
);
1181 /* loop over the variables list, freeing all data and deleting list items */
1182 /* no need to lock the list, as the channel is already locked */
1184 while ((vardata
= AST_LIST_REMOVE_HEAD(headp
, entries
)))
1185 ast_var_delete(vardata
);
1187 /* Destroy the jitterbuffer */
1188 ast_jb_destroy(chan
);
1190 ast_string_field_free_pools(chan
);
1192 AST_LIST_UNLOCK(&channels
);
1194 ast_device_state_changed_literal(name
);
1197 struct ast_datastore
*ast_channel_datastore_alloc(const struct ast_datastore_info
*info
, char *uid
)
1199 struct ast_datastore
*datastore
= NULL
;
1201 /* Make sure we at least have type so we can identify this */
1206 /* Allocate memory for datastore and clear it */
1207 datastore
= ast_calloc(1, sizeof(*datastore
));
1208 if (datastore
== NULL
) {
1212 datastore
->info
= info
;
1214 datastore
->uid
= ast_strdup(uid
);
1219 int ast_channel_datastore_free(struct ast_datastore
*datastore
)
1223 /* Using the destroy function (if present) destroy the data */
1224 if (datastore
->info
->destroy
!= NULL
&& datastore
->data
!= NULL
) {
1225 datastore
->info
->destroy(datastore
->data
);
1226 datastore
->data
= NULL
;
1229 /* Free allocated UID memory */
1230 if (datastore
->uid
!= NULL
) {
1231 free(datastore
->uid
);
1232 datastore
->uid
= NULL
;
1235 /* Finally free memory used by ourselves */
1241 int ast_channel_datastore_add(struct ast_channel
*chan
, struct ast_datastore
*datastore
)
1245 AST_LIST_INSERT_HEAD(&chan
->datastores
, datastore
, entry
);
1250 int ast_channel_datastore_remove(struct ast_channel
*chan
, struct ast_datastore
*datastore
)
1252 struct ast_datastore
*datastore2
= NULL
;
1255 /* Find our position and remove ourselves */
1256 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan
->datastores
, datastore2
, entry
) {
1257 if (datastore2
== datastore
) {
1258 AST_LIST_REMOVE_CURRENT(&chan
->datastores
, entry
);
1263 AST_LIST_TRAVERSE_SAFE_END
1268 struct ast_datastore
*ast_channel_datastore_find(struct ast_channel
*chan
, const struct ast_datastore_info
*info
, char *uid
)
1270 struct ast_datastore
*datastore
= NULL
;
1275 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan
->datastores
, datastore
, entry
) {
1276 if (datastore
->info
== info
) {
1277 if (uid
!= NULL
&& datastore
->uid
!= NULL
) {
1278 if (!strcasecmp(uid
, datastore
->uid
)) {
1279 /* Matched by type AND uid */
1283 /* Matched by type at least */
1288 AST_LIST_TRAVERSE_SAFE_END
1293 int ast_channel_spy_add(struct ast_channel
*chan
, struct ast_channel_spy
*spy
)
1295 /* Link the owner channel to the spy */
1298 if (!ast_test_flag(spy
, CHANSPY_FORMAT_AUDIO
)) {
1299 ast_log(LOG_WARNING
, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1300 spy
->type
, chan
->name
);
1304 if (ast_test_flag(spy
, CHANSPY_READ_VOLADJUST
) && (spy
->read_queue
.format
!= AST_FORMAT_SLINEAR
)) {
1305 ast_log(LOG_WARNING
, "Cannot provide volume adjustment on '%s' format spies\n",
1306 ast_getformatname(spy
->read_queue
.format
));
1310 if (ast_test_flag(spy
, CHANSPY_WRITE_VOLADJUST
) && (spy
->write_queue
.format
!= AST_FORMAT_SLINEAR
)) {
1311 ast_log(LOG_WARNING
, "Cannot provide volume adjustment on '%s' format spies\n",
1312 ast_getformatname(spy
->write_queue
.format
));
1316 if (ast_test_flag(spy
, CHANSPY_MIXAUDIO
) &&
1317 ((spy
->read_queue
.format
!= AST_FORMAT_SLINEAR
) ||
1318 (spy
->write_queue
.format
!= AST_FORMAT_SLINEAR
))) {
1319 ast_log(LOG_WARNING
, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1320 ast_getformatname(spy
->read_queue
.format
), ast_getformatname(spy
->write_queue
.format
));
1325 if (!(chan
->spies
= ast_calloc(1, sizeof(*chan
->spies
)))) {
1329 AST_LIST_HEAD_INIT_NOLOCK(&chan
->spies
->list
);
1330 AST_LIST_INSERT_HEAD(&chan
->spies
->list
, spy
, list
);
1332 AST_LIST_INSERT_TAIL(&chan
->spies
->list
, spy
, list
);
1335 if (ast_test_flag(spy
, CHANSPY_TRIGGER_MODE
) != CHANSPY_TRIGGER_NONE
) {
1336 ast_cond_init(&spy
->trigger
, NULL
);
1337 ast_set_flag(spy
, CHANSPY_TRIGGER_READ
);
1338 ast_clear_flag(spy
, CHANSPY_TRIGGER_WRITE
);
1342 ast_log(LOG_DEBUG
, "Spy %s added to channel %s\n",
1343 spy
->type
, chan
->name
);
1348 /* Clean up a channel's spy information */
1349 static void spy_cleanup(struct ast_channel
*chan
)
1351 if (!AST_LIST_EMPTY(&chan
->spies
->list
))
1353 if (chan
->spies
->read_translator
.path
)
1354 ast_translator_free_path(chan
->spies
->read_translator
.path
);
1355 if (chan
->spies
->write_translator
.path
)
1356 ast_translator_free_path(chan
->spies
->write_translator
.path
);
1362 /* Detach a spy from it's channel */
1363 static void spy_detach(struct ast_channel_spy
*spy
, struct ast_channel
*chan
)
1365 ast_mutex_lock(&spy
->lock
);
1367 /* We only need to poke them if they aren't already done */
1368 if (spy
->status
!= CHANSPY_DONE
) {
1369 /* Indicate to the spy to stop */
1370 spy
->status
= CHANSPY_STOP
;
1372 /* Poke the spy if needed */
1373 if (ast_test_flag(spy
, CHANSPY_TRIGGER_MODE
) != CHANSPY_TRIGGER_NONE
)
1374 ast_cond_signal(&spy
->trigger
);
1377 /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1379 ast_log(LOG_DEBUG
, "Spy %s removed from channel %s\n", spy
->type
, chan
->name
);
1381 ast_mutex_unlock(&spy
->lock
);
1386 void ast_channel_spy_stop_by_type(struct ast_channel
*chan
, const char *type
)
1388 struct ast_channel_spy
*spy
= NULL
;
1393 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan
->spies
->list
, spy
, list
) {
1394 ast_mutex_lock(&spy
->lock
);
1395 if ((spy
->type
== type
) && (spy
->status
== CHANSPY_RUNNING
)) {
1396 ast_mutex_unlock(&spy
->lock
);
1397 AST_LIST_REMOVE_CURRENT(&chan
->spies
->list
, list
);
1398 spy_detach(spy
, chan
);
1400 ast_mutex_unlock(&spy
->lock
);
1402 AST_LIST_TRAVERSE_SAFE_END
1406 void ast_channel_spy_trigger_wait(struct ast_channel_spy
*spy
)
1411 tv
= ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1412 ts
.tv_sec
= tv
.tv_sec
;
1413 ts
.tv_nsec
= tv
.tv_usec
* 1000;
1415 ast_cond_timedwait(&spy
->trigger
, &spy
->lock
, &ts
);
1418 void ast_channel_spy_remove(struct ast_channel
*chan
, struct ast_channel_spy
*spy
)
1423 AST_LIST_REMOVE(&chan
->spies
->list
, spy
, list
);
1424 spy_detach(spy
, chan
);
1428 void ast_channel_spy_free(struct ast_channel_spy
*spy
)
1430 struct ast_frame
*f
= NULL
;
1432 if (spy
->status
== CHANSPY_DONE
)
1435 /* Switch status to done in case we get called twice */
1436 spy
->status
= CHANSPY_DONE
;
1438 /* Drop any frames in the queue */
1439 while ((f
= AST_LIST_REMOVE_HEAD(&spy
->write_queue
.list
, frame_list
)))
1441 while ((f
= AST_LIST_REMOVE_HEAD(&spy
->read_queue
.list
, frame_list
)))
1444 /* Destroy the condition if in use */
1445 if (ast_test_flag(spy
, CHANSPY_TRIGGER_MODE
) != CHANSPY_TRIGGER_NONE
)
1446 ast_cond_destroy(&spy
->trigger
);
1448 /* Destroy our mutex since it is no longer in use */
1449 ast_mutex_destroy(&spy
->lock
);
1454 static void detach_spies(struct ast_channel
*chan
)
1456 struct ast_channel_spy
*spy
= NULL
;
1461 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan
->spies
->list
, spy
, list
) {
1462 AST_LIST_REMOVE_CURRENT(&chan
->spies
->list
, list
);
1463 spy_detach(spy
, chan
);
1465 AST_LIST_TRAVERSE_SAFE_END
1470 /*! \brief Softly hangup a channel, don't lock */
1471 int ast_softhangup_nolock(struct ast_channel
*chan
, int cause
)
1474 ast_log(LOG_DEBUG
, "Soft-Hanging up channel '%s'\n", chan
->name
);
1475 /* Inform channel driver that we need to be hung up, if it cares */
1476 chan
->_softhangup
|= cause
;
1477 ast_queue_frame(chan
, &ast_null_frame
);
1478 /* Interrupt any poll call or such */
1479 if (ast_test_flag(chan
, AST_FLAG_BLOCKING
))
1480 pthread_kill(chan
->blocker
, SIGURG
);
1484 /*! \brief Softly hangup a channel, lock */
1485 int ast_softhangup(struct ast_channel
*chan
, int cause
)
1488 ast_channel_lock(chan
);
1489 res
= ast_softhangup_nolock(chan
, cause
);
1490 ast_channel_unlock(chan
);
1494 enum spy_direction
{
1499 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1501 static void queue_frame_to_spies(struct ast_channel
*chan
, struct ast_frame
*f
, enum spy_direction dir
)
1503 struct ast_frame
*translated_frame
= NULL
;
1504 struct ast_channel_spy
*spy
;
1505 struct channel_spy_trans
*trans
;
1507 trans
= (dir
== SPY_READ
) ? &chan
->spies
->read_translator
: &chan
->spies
->write_translator
;
1509 AST_LIST_TRAVERSE(&chan
->spies
->list
, spy
, list
) {
1510 struct ast_channel_spy_queue
*queue
;
1511 struct ast_frame
*duped_fr
;
1513 ast_mutex_lock(&spy
->lock
);
1515 queue
= (dir
== SPY_READ
) ? &spy
->read_queue
: &spy
->write_queue
;
1517 if ((queue
->format
== AST_FORMAT_SLINEAR
) && (f
->subclass
!= AST_FORMAT_SLINEAR
)) {
1518 if (!translated_frame
) {
1519 if (trans
->path
&& (trans
->last_format
!= f
->subclass
)) {
1520 ast_translator_free_path(trans
->path
);
1525 ast_log(LOG_DEBUG
, "Building translator from %s to SLINEAR for spies on channel %s\n",
1526 ast_getformatname(f
->subclass
), chan
->name
);
1527 if ((trans
->path
= ast_translator_build_path(AST_FORMAT_SLINEAR
, f
->subclass
)) == NULL
) {
1528 ast_log(LOG_WARNING
, "Cannot build a path from %s to %s\n",
1529 ast_getformatname(f
->subclass
), ast_getformatname(AST_FORMAT_SLINEAR
));
1530 ast_mutex_unlock(&spy
->lock
);
1533 trans
->last_format
= f
->subclass
;
1536 if (!(translated_frame
= ast_translate(trans
->path
, f
, 0))) {
1537 ast_log(LOG_ERROR
, "Translation to %s failed, dropping frame for spies\n",
1538 ast_getformatname(AST_FORMAT_SLINEAR
));
1539 ast_mutex_unlock(&spy
->lock
);
1543 duped_fr
= ast_frdup(translated_frame
);
1544 } else if (f
->subclass
!= queue
->format
) {
1545 ast_log(LOG_WARNING
, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1546 spy
->type
, chan
->name
,
1547 ast_getformatname(queue
->format
), ast_getformatname(f
->subclass
));
1548 ast_mutex_unlock(&spy
->lock
);
1551 duped_fr
= ast_frdup(f
);
1553 AST_LIST_INSERT_TAIL(&queue
->list
, duped_fr
, frame_list
);
1555 queue
->samples
+= f
->samples
;
1557 if (queue
->samples
> SPY_QUEUE_SAMPLE_LIMIT
) {
1558 if (ast_test_flag(spy
, CHANSPY_TRIGGER_MODE
) != CHANSPY_TRIGGER_NONE
) {
1559 switch (ast_test_flag(spy
, CHANSPY_TRIGGER_MODE
)) {
1560 case CHANSPY_TRIGGER_READ
:
1561 if (dir
== SPY_WRITE
) {
1562 ast_set_flag(spy
, CHANSPY_TRIGGER_WRITE
);
1563 ast_clear_flag(spy
, CHANSPY_TRIGGER_READ
);
1565 ast_log(LOG_DEBUG
, "Switching spy '%s' on '%s' to write-trigger mode\n",
1566 spy
->type
, chan
->name
);
1569 case CHANSPY_TRIGGER_WRITE
:
1570 if (dir
== SPY_READ
) {
1571 ast_set_flag(spy
, CHANSPY_TRIGGER_READ
);
1572 ast_clear_flag(spy
, CHANSPY_TRIGGER_WRITE
);
1574 ast_log(LOG_DEBUG
, "Switching spy '%s' on '%s' to read-trigger mode\n",
1575 spy
->type
, chan
->name
);
1580 ast_log(LOG_DEBUG
, "Triggering queue flush for spy '%s' on '%s'\n",
1581 spy
->type
, chan
->name
);
1582 ast_set_flag(spy
, CHANSPY_TRIGGER_FLUSH
);
1583 ast_cond_signal(&spy
->trigger
);
1586 ast_log(LOG_DEBUG
, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1587 spy
->type
, chan
->name
, (dir
== SPY_READ
) ? "read" : "write");
1588 while (queue
->samples
> SPY_QUEUE_SAMPLE_LIMIT
) {
1589 struct ast_frame
*drop
= AST_LIST_REMOVE_HEAD(&queue
->list
, frame_list
);
1590 queue
->samples
-= drop
->samples
;
1595 switch (ast_test_flag(spy
, CHANSPY_TRIGGER_MODE
)) {
1596 case CHANSPY_TRIGGER_READ
:
1597 if (dir
== SPY_READ
)
1598 ast_cond_signal(&spy
->trigger
);
1600 case CHANSPY_TRIGGER_WRITE
:
1601 if (dir
== SPY_WRITE
)
1602 ast_cond_signal(&spy
->trigger
);
1607 ast_mutex_unlock(&spy
->lock
);
1610 if (translated_frame
)
1611 ast_frfree(translated_frame
);
1614 static void free_translation(struct ast_channel
*clone
)
1616 if (clone
->writetrans
)
1617 ast_translator_free_path(clone
->writetrans
);
1618 if (clone
->readtrans
)
1619 ast_translator_free_path(clone
->readtrans
);
1620 clone
->writetrans
= NULL
;
1621 clone
->readtrans
= NULL
;
1622 clone
->rawwriteformat
= clone
->nativeformats
;
1623 clone
->rawreadformat
= clone
->nativeformats
;
1626 /*! \brief Hangup a channel */
1627 int ast_hangup(struct ast_channel
*chan
)
1631 /* Don't actually hang up a channel that will masquerade as someone else, or
1632 if someone is going to masquerade as us */
1633 ast_channel_lock(chan
);
1635 detach_spies(chan
); /* get rid of spies */
1638 if (ast_do_masquerade(chan
))
1639 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
1643 ast_log(LOG_WARNING
, "%s getting hung up, but someone is trying to masq into us?!?\n", chan
->name
);
1644 ast_channel_unlock(chan
);
1647 /* If this channel is one which will be masqueraded into something,
1648 mark it as a zombie already, so we know to free it later */
1650 ast_set_flag(chan
, AST_FLAG_ZOMBIE
);
1651 ast_channel_unlock(chan
);
1654 free_translation(chan
);
1655 /* Close audio stream */
1657 ast_closestream(chan
->stream
);
1658 chan
->stream
= NULL
;
1660 /* Close video stream */
1661 if (chan
->vstream
) {
1662 ast_closestream(chan
->vstream
);
1663 chan
->vstream
= NULL
;
1666 sched_context_destroy(chan
->sched
);
1670 if (chan
->generatordata
) /* Clear any tone stuff remaining */
1671 chan
->generator
->release(chan
, chan
->generatordata
);
1672 chan
->generatordata
= NULL
;
1673 chan
->generator
= NULL
;
1674 if (chan
->cdr
) { /* End the CDR if it hasn't already */
1675 ast_cdr_end(chan
->cdr
);
1676 ast_cdr_detach(chan
->cdr
); /* Post and Free the CDR */
1679 if (ast_test_flag(chan
, AST_FLAG_BLOCKING
)) {
1680 ast_log(LOG_WARNING
, "Hard hangup called by thread %ld on %s, while fd "
1681 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1682 (long)pthread_self(), chan
->name
, (long)chan
->blocker
, chan
->blockproc
);
1685 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
)) {
1687 ast_log(LOG_DEBUG
, "Hanging up channel '%s'\n", chan
->name
);
1688 if (chan
->tech
->hangup
)
1689 res
= chan
->tech
->hangup(chan
);
1692 ast_log(LOG_DEBUG
, "Hanging up zombie '%s'\n", chan
->name
);
1695 ast_channel_unlock(chan
);
1696 manager_event(EVENT_FLAG_CALL
, "Hangup",
1700 "Cause-txt: %s\r\n",
1704 ast_cause2str(chan
->hangupcause
)
1706 ast_channel_free(chan
);
1710 int ast_answer(struct ast_channel
*chan
)
1713 ast_channel_lock(chan
);
1714 /* You can't answer an outbound call */
1715 if (ast_test_flag(chan
, AST_FLAG_OUTGOING
)) {
1716 ast_channel_unlock(chan
);
1719 /* Stop if we're a zombie or need a soft hangup */
1720 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
1721 ast_channel_unlock(chan
);
1724 switch(chan
->_state
) {
1725 case AST_STATE_RINGING
:
1726 case AST_STATE_RING
:
1727 if (chan
->tech
->answer
)
1728 res
= chan
->tech
->answer(chan
);
1729 ast_setstate(chan
, AST_STATE_UP
);
1730 ast_cdr_answer(chan
->cdr
);
1733 ast_cdr_answer(chan
->cdr
);
1738 ast_channel_unlock(chan
);
1742 void ast_deactivate_generator(struct ast_channel
*chan
)
1744 ast_channel_lock(chan
);
1745 if (chan
->generatordata
) {
1746 if (chan
->generator
&& chan
->generator
->release
)
1747 chan
->generator
->release(chan
, chan
->generatordata
);
1748 chan
->generatordata
= NULL
;
1749 chan
->generator
= NULL
;
1750 chan
->fds
[AST_GENERATOR_FD
] = -1;
1751 ast_clear_flag(chan
, AST_FLAG_WRITE_INT
);
1752 ast_settimeout(chan
, 0, NULL
, NULL
);
1754 ast_channel_unlock(chan
);
1757 static int generator_force(void *data
)
1759 /* Called if generator doesn't have data */
1762 int (*generate
)(struct ast_channel
*chan
, void *tmp
, int datalen
, int samples
);
1763 struct ast_channel
*chan
= data
;
1764 tmp
= chan
->generatordata
;
1765 chan
->generatordata
= NULL
;
1766 generate
= chan
->generator
->generate
;
1767 res
= generate(chan
, tmp
, 0, 160);
1768 chan
->generatordata
= tmp
;
1771 ast_log(LOG_DEBUG
, "Auto-deactivating generator\n");
1772 ast_deactivate_generator(chan
);
1777 int ast_activate_generator(struct ast_channel
*chan
, struct ast_generator
*gen
, void *params
)
1781 ast_channel_lock(chan
);
1783 if (chan
->generatordata
) {
1784 if (chan
->generator
&& chan
->generator
->release
)
1785 chan
->generator
->release(chan
, chan
->generatordata
);
1786 chan
->generatordata
= NULL
;
1790 if (gen
->alloc
&& !(chan
->generatordata
= gen
->alloc(chan
, params
))) {
1795 ast_settimeout(chan
, 160, generator_force
, chan
);
1796 chan
->generator
= gen
;
1799 ast_channel_unlock(chan
);
1804 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1805 int ast_waitfor_n_fd(int *fds
, int n
, int *ms
, int *exception
)
1808 ast_waitfor_nandfds(NULL
, 0, fds
, n
, exception
, &winner
, ms
);
1812 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1813 struct ast_channel
*ast_waitfor_nandfds(struct ast_channel
**c
, int n
, int *fds
, int nfds
,
1814 int *exception
, int *outfd
, int *ms
)
1816 struct timeval start
= { 0 , 0 };
1817 struct pollfd
*pfds
;
1823 long whentohangup
= 0, diff
;
1824 struct ast_channel
*winner
= NULL
;
1830 sz
= n
* AST_MAX_FDS
+ nfds
;
1831 pfds
= alloca(sizeof(*pfds
) * sz
);
1832 fdmap
= alloca(sizeof(*fdmap
) * sz
);
1839 /* Perform any pending masquerades */
1840 for (x
=0; x
< n
; x
++) {
1841 ast_channel_lock(c
[x
]);
1843 if (ast_do_masquerade(c
[x
])) {
1844 ast_log(LOG_WARNING
, "Masquerade failed\n");
1846 ast_channel_unlock(c
[x
]);
1850 if (c
[x
]->whentohangup
) {
1853 diff
= c
[x
]->whentohangup
- now
;
1855 /* Should already be hungup */
1856 c
[x
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
1857 ast_channel_unlock(c
[x
]);
1860 if (!whentohangup
|| (diff
< whentohangup
))
1861 whentohangup
= diff
;
1863 ast_channel_unlock(c
[x
]);
1865 /* Wait full interval */
1868 rms
= whentohangup
* 1000; /* timeout in milliseconds */
1869 if (*ms
>= 0 && *ms
< rms
) /* original *ms still smaller */
1873 * Build the pollfd array, putting the channels' fds first,
1874 * followed by individual fds. Order is important because
1875 * individual fd's must have priority over channel fds.
1878 for (x
=0; x
<n
; x
++) {
1879 for (y
=0; y
<AST_MAX_FDS
; y
++) {
1880 fdmap
[max
].fdno
= y
; /* fd y is linked to this pfds */
1881 fdmap
[max
].chan
= x
; /* channel x is linked to this pfds */
1882 max
+= ast_add_fd(&pfds
[max
], c
[x
]->fds
[y
]);
1884 CHECK_BLOCKING(c
[x
]);
1886 /* Add the individual fds */
1887 for (x
=0; x
<nfds
; x
++) {
1888 fdmap
[max
].chan
= -1;
1889 max
+= ast_add_fd(&pfds
[max
], fds
[x
]);
1893 start
= ast_tvnow();
1895 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1900 res
= poll(pfds
, max
, kbrms
);
1903 } while (!res
&& (rms
> 0));
1905 res
= poll(pfds
, max
, rms
);
1908 ast_clear_flag(c
[x
], AST_FLAG_BLOCKING
);
1909 if (res
< 0) { /* Simulate a timeout if we were interrupted */
1914 if (whentohangup
) { /* if we have a timeout, check who expired */
1916 for (x
=0; x
<n
; x
++) {
1917 if (c
[x
]->whentohangup
&& now
>= c
[x
]->whentohangup
) {
1918 c
[x
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
1924 if (res
== 0) { /* no fd ready, reset timeout and done */
1925 *ms
= 0; /* XXX use 0 since we may not have an exact timeout. */
1929 * Then check if any channel or fd has a pending event.
1930 * Remember to check channels first and fds last, as they
1931 * must have priority on setting 'winner'
1933 for (x
= 0; x
< max
; x
++) {
1934 res
= pfds
[x
].revents
;
1937 if (fdmap
[x
].chan
>= 0) { /* this is a channel */
1938 winner
= c
[fdmap
[x
].chan
]; /* override previous winners */
1940 ast_set_flag(winner
, AST_FLAG_EXCEPTION
);
1942 ast_clear_flag(winner
, AST_FLAG_EXCEPTION
);
1943 winner
->fdno
= fdmap
[x
].fdno
;
1944 } else { /* this is an fd */
1946 *outfd
= pfds
[x
].fd
;
1948 *exception
= (res
& POLLPRI
) ? -1 : 0;
1953 *ms
-= ast_tvdiff_ms(ast_tvnow(), start
);
1960 struct ast_channel
*ast_waitfor_n(struct ast_channel
**c
, int n
, int *ms
)
1962 return ast_waitfor_nandfds(c
, n
, NULL
, 0, NULL
, NULL
, ms
);
1965 int ast_waitfor(struct ast_channel
*c
, int ms
)
1967 int oldms
= ms
; /* -1 if no timeout */
1969 ast_waitfor_nandfds(&c
, 1, NULL
, 0, NULL
, NULL
, &ms
);
1970 if ((ms
< 0) && (oldms
< 0))
1975 /* XXX never to be called with ms = -1 */
1976 int ast_waitfordigit(struct ast_channel
*c
, int ms
)
1978 return ast_waitfordigit_full(c
, ms
, -1, -1);
1981 int ast_settimeout(struct ast_channel
*c
, int samples
, int (*func
)(void *data
), void *data
)
1985 if (c
->timingfd
> -1) {
1991 ast_log(LOG_DEBUG
, "Scheduling timer at %d sample intervals\n", samples
);
1992 res
= ioctl(c
->timingfd
, ZT_TIMERCONFIG
, &samples
);
1993 c
->timingfunc
= func
;
1994 c
->timingdata
= data
;
2000 int ast_waitfordigit_full(struct ast_channel
*c
, int ms
, int audiofd
, int cmdfd
)
2003 /* Stop if we're a zombie or need a soft hangup */
2004 if (ast_test_flag(c
, AST_FLAG_ZOMBIE
) || ast_check_hangup(c
))
2006 /* Wait for a digit, no more than ms milliseconds total. */
2008 struct ast_channel
*rchan
;
2012 rchan
= ast_waitfor_nandfds(&c
, 1, &cmdfd
, (cmdfd
> -1) ? 1 : 0, NULL
, &outfd
, &ms
);
2013 if (!rchan
&& outfd
< 0 && ms
) {
2014 if (errno
== 0 || errno
== EINTR
)
2016 ast_log(LOG_WARNING
, "Wait failed (%s)\n", strerror(errno
));
2018 } else if (outfd
> -1) {
2019 /* The FD we were watching has something waiting */
2023 struct ast_frame
*f
= ast_read(c
);
2027 switch(f
->frametype
) {
2028 case AST_FRAME_DTMF
:
2032 case AST_FRAME_CONTROL
:
2033 switch(f
->subclass
) {
2034 case AST_CONTROL_HANGUP
:
2037 case AST_CONTROL_RINGING
:
2038 case AST_CONTROL_ANSWER
:
2042 ast_log(LOG_WARNING
, "Unexpected control subclass '%d'\n", f
->subclass
);
2046 case AST_FRAME_VOICE
:
2047 /* Write audio if appropriate */
2049 write(audiofd
, f
->data
, f
->datalen
);
2057 return 0; /* Time is up */
2060 static struct ast_frame
*__ast_read(struct ast_channel
*chan
, int dropaudio
)
2062 struct ast_frame
*f
= NULL
; /* the return value */
2066 /* this function is very long so make sure there is only one return
2067 * point at the end (there is only one exception to this).
2069 ast_channel_lock(chan
);
2071 if (ast_do_masquerade(chan
))
2072 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
2074 f
= &ast_null_frame
;
2078 /* Stop if we're a zombie or need a soft hangup */
2079 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
2080 if (chan
->generator
)
2081 ast_deactivate_generator(chan
);
2084 prestate
= chan
->_state
;
2086 if (!ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
| AST_FLAG_EMULATE_DTMF
| AST_FLAG_IN_DTMF
) &&
2087 !ast_strlen_zero(chan
->dtmfq
)) {
2088 /* We have DTMF that has been deferred. Return it now */
2089 chan
->dtmff
.subclass
= chan
->dtmfq
[0];
2090 /* Drop first digit from the buffer */
2091 memmove(chan
->dtmfq
, chan
->dtmfq
+ 1, sizeof(chan
->dtmfq
) - 1);
2093 if (ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
))
2094 chan
->dtmff
.frametype
= AST_FRAME_DTMF_END
;
2096 chan
->dtmff
.frametype
= AST_FRAME_DTMF_BEGIN
;
2097 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2098 chan
->emulate_dtmf_digit
= f
->subclass
;
2099 chan
->emulate_dtmf_duration
= AST_DEFAULT_EMULATE_DTMF_DURATION
;
2100 chan
->dtmf_begin_tv
= ast_tvnow();
2105 /* Read and ignore anything on the alertpipe, but read only
2106 one sizeof(blah) per frame that we send from it */
2107 if (chan
->alertpipe
[0] > -1)
2108 read(chan
->alertpipe
[0], &blah
, sizeof(blah
));
2111 if (chan
->timingfd
> -1 && chan
->fdno
== AST_TIMING_FD
&& ast_test_flag(chan
, AST_FLAG_EXCEPTION
)) {
2114 ast_clear_flag(chan
, AST_FLAG_EXCEPTION
);
2116 /* IF we can't get event, assume it's an expired as-per the old interface */
2117 res
= ioctl(chan
->timingfd
, ZT_GETEVENT
, &blah
);
2119 blah
= ZT_EVENT_TIMER_EXPIRED
;
2121 if (blah
== ZT_EVENT_TIMER_PING
) {
2122 if (AST_LIST_EMPTY(&chan
->readq
) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan
->readq
), frame_list
)) {
2123 /* Acknowledge PONG unless we need it again */
2124 if (ioctl(chan
->timingfd
, ZT_TIMERPONG
, &blah
)) {
2125 ast_log(LOG_WARNING
, "Failed to pong timer on '%s': %s\n", chan
->name
, strerror(errno
));
2128 } else if (blah
== ZT_EVENT_TIMER_EXPIRED
) {
2129 ioctl(chan
->timingfd
, ZT_TIMERACK
, &blah
);
2130 if (chan
->timingfunc
) {
2131 /* save a copy of func/data before unlocking the channel */
2132 int (*func
)(void *) = chan
->timingfunc
;
2133 void *data
= chan
->timingdata
;
2134 ast_channel_unlock(chan
);
2138 ioctl(chan
->timingfd
, ZT_TIMERCONFIG
, &blah
);
2139 chan
->timingdata
= NULL
;
2140 ast_channel_unlock(chan
);
2142 /* cannot 'goto done' because the channel is already unlocked */
2143 return &ast_null_frame
;
2145 ast_log(LOG_NOTICE
, "No/unknown event '%d' on timer for '%s'?\n", blah
, chan
->name
);
2148 if (chan
->fds
[AST_GENERATOR_FD
] > -1 && chan
->fdno
== AST_GENERATOR_FD
) {
2149 /* if the AST_GENERATOR_FD is set, call the generator with args
2150 * set to -1 so it can do whatever it needs to.
2152 void *tmp
= chan
->generatordata
;
2153 chan
->generatordata
= NULL
; /* reset to let ast_write get through */
2154 chan
->generator
->generate(chan
, tmp
, -1, -1);
2155 chan
->generatordata
= tmp
;
2156 f
= &ast_null_frame
;
2160 /* Check for pending read queue */
2161 if (!AST_LIST_EMPTY(&chan
->readq
)) {
2162 f
= AST_LIST_REMOVE_HEAD(&chan
->readq
, frame_list
);
2163 /* Interpret hangup and return NULL */
2164 /* XXX why not the same for frames from the channel ? */
2165 if (f
->frametype
== AST_FRAME_CONTROL
&& f
->subclass
== AST_CONTROL_HANGUP
) {
2170 chan
->blocker
= pthread_self();
2171 if (ast_test_flag(chan
, AST_FLAG_EXCEPTION
)) {
2172 if (chan
->tech
->exception
)
2173 f
= chan
->tech
->exception(chan
);
2175 ast_log(LOG_WARNING
, "Exception flag set on '%s', but no exception handler\n", chan
->name
);
2176 f
= &ast_null_frame
;
2178 /* Clear the exception flag */
2179 ast_clear_flag(chan
, AST_FLAG_EXCEPTION
);
2180 } else if (chan
->tech
->read
)
2181 f
= chan
->tech
->read(chan
);
2183 ast_log(LOG_WARNING
, "No read routine on channel %s\n", chan
->name
);
2187 /* if the channel driver returned more than one frame, stuff the excess
2188 into the readq for the next ast_read call (note that we can safely assume
2189 that the readq is empty, because otherwise we would not have called into
2190 the channel driver and f would be only a single frame)
2192 if (AST_LIST_NEXT(f
, frame_list
)) {
2193 AST_LIST_HEAD_SET_NOLOCK(&chan
->readq
, AST_LIST_NEXT(f
, frame_list
));
2194 AST_LIST_NEXT(f
, frame_list
) = NULL
;
2197 switch (f
->frametype
) {
2198 case AST_FRAME_CONTROL
:
2199 if (f
->subclass
== AST_CONTROL_ANSWER
) {
2200 if (!ast_test_flag(chan
, AST_FLAG_OUTGOING
)) {
2202 ast_log(LOG_DEBUG
, "Ignoring answer on an inbound call!\n");
2204 f
= &ast_null_frame
;
2205 } else if (prestate
== AST_STATE_UP
) {
2207 ast_log(LOG_DEBUG
, "Dropping duplicate answer!\n");
2209 f
= &ast_null_frame
;
2211 /* Answer the CDR */
2212 ast_setstate(chan
, AST_STATE_UP
);
2213 ast_cdr_answer(chan
->cdr
);
2217 case AST_FRAME_DTMF_END
:
2218 ast_log(LOG_DTMF
, "DTMF end '%c' received on %s\n", f
->subclass
, chan
->name
);
2219 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2220 * However, only let emulation be forced if the other end cares about BEGIN frames */
2221 if ( ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
) ||
2222 (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
)) ) {
2223 if (strlen(chan
->dtmfq
) < sizeof(chan
->dtmfq
) - 2)
2224 chan
->dtmfq
[strlen(chan
->dtmfq
)] = f
->subclass
;
2226 ast_log(LOG_WARNING
, "Dropping deferred DTMF digits on %s\n", chan
->name
);
2228 f
= &ast_null_frame
;
2229 } else if (!ast_test_flag(chan
, AST_FLAG_IN_DTMF
| AST_FLAG_END_DTMF_ONLY
)) {
2230 f
->frametype
= AST_FRAME_DTMF_BEGIN
;
2231 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2232 chan
->emulate_dtmf_digit
= f
->subclass
;
2233 chan
->dtmf_begin_tv
= ast_tvnow();
2235 chan
->emulate_dtmf_duration
= f
->len
;
2237 chan
->emulate_dtmf_duration
= AST_DEFAULT_EMULATE_DTMF_DURATION
;
2239 ast_clear_flag(chan
, AST_FLAG_IN_DTMF
);
2241 f
->len
= ast_tvdiff_ms(chan
->dtmf_begin_tv
, ast_tvnow());
2244 case AST_FRAME_DTMF_BEGIN
:
2245 ast_log(LOG_DTMF
, "DTMF begin '%c' received on %s\n", f
->subclass
, chan
->name
);
2246 if (ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
| AST_FLAG_END_DTMF_ONLY
)) {
2248 f
= &ast_null_frame
;
2250 ast_set_flag(chan
, AST_FLAG_IN_DTMF
);
2251 chan
->dtmf_begin_tv
= ast_tvnow();
2254 case AST_FRAME_VOICE
:
2255 /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2256 * first get to zero, because we want to make sure we pass at least one
2257 * voice frame through before starting the next digit, to ensure a gap
2258 * between DTMF digits. */
2259 if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !chan
->emulate_dtmf_duration
) {
2260 ast_clear_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2261 chan
->emulate_dtmf_digit
= 0;
2264 if (dropaudio
|| ast_test_flag(chan
, AST_FLAG_IN_DTMF
)) {
2266 f
= &ast_null_frame
;
2267 } else if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
)) {
2268 if ((f
->samples
/ 8) >= chan
->emulate_dtmf_duration
) { /* XXX 8kHz */
2269 chan
->emulate_dtmf_duration
= 0;
2270 f
->frametype
= AST_FRAME_DTMF_END
;
2271 f
->subclass
= chan
->emulate_dtmf_digit
;
2273 chan
->emulate_dtmf_duration
-= f
->samples
/ 8; /* XXX 8kHz */
2275 f
= &ast_null_frame
;
2277 } else if (!(f
->subclass
& chan
->nativeformats
)) {
2278 /* This frame can't be from the current native formats -- drop it on the
2280 ast_log(LOG_NOTICE
, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2281 chan
->name
, ast_getformatname(f
->subclass
), ast_getformatname(chan
->nativeformats
));
2283 f
= &ast_null_frame
;
2286 queue_frame_to_spies(chan
, f
, SPY_READ
);
2288 if (chan
->monitor
&& chan
->monitor
->read_stream
) {
2289 /* XXX what does this do ? */
2290 #ifndef MONITOR_CONSTANT_DELAY
2291 int jump
= chan
->outsmpl
- chan
->insmpl
- 4 * f
->samples
;
2293 jump
= chan
->outsmpl
- chan
->insmpl
;
2294 if (ast_seekstream(chan
->monitor
->read_stream
, jump
, SEEK_FORCECUR
) == -1)
2295 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2296 chan
->insmpl
+= jump
+ f
->samples
;
2298 chan
->insmpl
+= f
->samples
;
2300 int jump
= chan
->outsmpl
- chan
->insmpl
;
2301 if (jump
- MONITOR_DELAY
>= 0) {
2302 if (ast_seekstream(chan
->monitor
->read_stream
, jump
- f
->samples
, SEEK_FORCECUR
) == -1)
2303 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2304 chan
->insmpl
+= jump
;
2306 chan
->insmpl
+= f
->samples
;
2308 if (chan
->monitor
->state
== AST_MONITOR_RUNNING
) {
2309 if (ast_writestream(chan
->monitor
->read_stream
, f
) < 0)
2310 ast_log(LOG_WARNING
, "Failed to write data to channel monitor read stream\n");
2314 if (chan
->readtrans
&& (f
= ast_translate(chan
->readtrans
, f
, 1)) == NULL
)
2315 f
= &ast_null_frame
;
2317 /* Run generator sitting on the line if timing device not available
2318 * and synchronous generation of outgoing frames is necessary */
2319 if (chan
->generatordata
&& !ast_internal_timing_enabled(chan
)) {
2320 void *tmp
= chan
->generatordata
;
2323 if (chan
->timingfunc
) {
2324 if (option_debug
> 1)
2325 ast_log(LOG_DEBUG
, "Generator got voice, switching to phase locked mode\n");
2326 ast_settimeout(chan
, 0, NULL
, NULL
);
2329 chan
->generatordata
= NULL
; /* reset, to let writes go through */
2330 res
= chan
->generator
->generate(chan
, tmp
, f
->datalen
, f
->samples
);
2331 chan
->generatordata
= tmp
;
2333 if (option_debug
> 1)
2334 ast_log(LOG_DEBUG
, "Auto-deactivating generator\n");
2335 ast_deactivate_generator(chan
);
2338 } else if (f
->frametype
== AST_FRAME_CNG
) {
2339 if (chan
->generator
&& !chan
->timingfunc
&& (chan
->timingfd
> -1)) {
2340 if (option_debug
> 1)
2341 ast_log(LOG_DEBUG
, "Generator got CNG, switching to timed mode\n");
2342 ast_settimeout(chan
, 160, generator_force
, chan
);
2347 /* Just pass it on! */
2351 /* Make sure we always return NULL in the future */
2352 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
2353 if (chan
->generator
)
2354 ast_deactivate_generator(chan
);
2355 /* End the CDR if appropriate */
2357 ast_cdr_end(chan
->cdr
);
2360 /* High bit prints debugging */
2361 if (chan
->fin
& DEBUGCHAN_FLAG
)
2362 ast_frame_dump(chan
->name
, f
, "<<");
2363 chan
->fin
= FRAMECOUNT_INC(chan
->fin
);
2366 ast_channel_unlock(chan
);
2370 int ast_internal_timing_enabled(struct ast_channel
*chan
)
2372 int ret
= ast_opt_internal_timing
&& chan
->timingfd
> -1;
2373 if (option_debug
> 4)
2374 ast_log(LOG_DEBUG
, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret
? "enabled": "disabled", ast_opt_internal_timing
, chan
->timingfd
);
2378 struct ast_frame
*ast_read(struct ast_channel
*chan
)
2380 return __ast_read(chan
, 0);
2383 struct ast_frame
*ast_read_noaudio(struct ast_channel
*chan
)
2385 return __ast_read(chan
, 1);
2388 int ast_indicate(struct ast_channel
*chan
, int condition
)
2390 return ast_indicate_data(chan
, condition
, NULL
, 0);
2393 int ast_indicate_data(struct ast_channel
*chan
, int condition
, const void *data
, size_t datalen
)
2397 ast_channel_lock(chan
);
2398 /* Stop if we're a zombie or need a soft hangup */
2399 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
2400 ast_channel_unlock(chan
);
2403 if (chan
->tech
->indicate
)
2404 res
= chan
->tech
->indicate(chan
, condition
, data
, datalen
);
2405 ast_channel_unlock(chan
);
2406 if (!chan
->tech
->indicate
|| res
) {
2408 * Device does not support (that) indication, lets fake
2409 * it by doing our own tone generation. (PM2002)
2412 ast_playtones_stop(chan
);
2414 const struct tone_zone_sound
*ts
= NULL
;
2415 switch (condition
) {
2416 case AST_CONTROL_RINGING
:
2417 ts
= ast_get_indication_tone(chan
->zone
, "ring");
2419 case AST_CONTROL_BUSY
:
2420 ts
= ast_get_indication_tone(chan
->zone
, "busy");
2422 case AST_CONTROL_CONGESTION
:
2423 ts
= ast_get_indication_tone(chan
->zone
, "congestion");
2426 if (ts
&& ts
->data
[0]) {
2428 ast_log(LOG_DEBUG
, "Driver for channel '%s' does not support indication %d, emulating it\n", chan
->name
, condition
);
2429 ast_playtones_start(chan
,0,ts
->data
, 1);
2431 } else if (condition
== AST_CONTROL_PROGRESS
) {
2432 /* ast_playtones_stop(chan); */
2433 } else if (condition
== AST_CONTROL_PROCEEDING
) {
2434 /* Do nothing, really */
2435 } else if (condition
== AST_CONTROL_HOLD
) {
2436 /* Do nothing.... */
2437 } else if (condition
== AST_CONTROL_UNHOLD
) {
2438 /* Do nothing.... */
2439 } else if (condition
== AST_CONTROL_VIDUPDATE
) {
2440 /* Do nothing.... */
2443 ast_log(LOG_WARNING
, "Unable to handle indication %d for '%s'\n", condition
, chan
->name
);
2451 int ast_recvchar(struct ast_channel
*chan
, int timeout
)
2454 char *buf
= ast_recvtext(chan
, timeout
);
2456 return -1; /* error or timeout */
2457 c
= *(unsigned char *)buf
;
2462 char *ast_recvtext(struct ast_channel
*chan
, int timeout
)
2468 struct ast_frame
*f
;
2469 if (ast_check_hangup(chan
))
2471 res
= ast_waitfor(chan
, timeout
);
2472 if (res
<= 0) /* timeout or error */
2474 timeout
= res
; /* update timeout */
2477 break; /* no frame */
2478 if (f
->frametype
== AST_FRAME_CONTROL
&& f
->subclass
== AST_CONTROL_HANGUP
)
2479 done
= 1; /* force a break */
2480 else if (f
->frametype
== AST_FRAME_TEXT
) { /* what we want */
2481 buf
= ast_strndup((char *) f
->data
, f
->datalen
); /* dup and break */
2489 int ast_sendtext(struct ast_channel
*chan
, const char *text
)
2492 /* Stop if we're a zombie or need a soft hangup */
2493 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
))
2495 CHECK_BLOCKING(chan
);
2496 if (chan
->tech
->send_text
)
2497 res
= chan
->tech
->send_text(chan
, text
);
2498 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2502 int ast_senddigit_begin(struct ast_channel
*chan
, char digit
)
2506 if (chan
->tech
->send_digit_begin
)
2507 res
= chan
->tech
->send_digit_begin(chan
, digit
);
2511 * Device does not support DTMF tones, lets fake
2512 * it by doing our own generation. (PM2002)
2514 static const char* dtmf_tones
[] = {
2515 "!941+1336/100,!0/100", /* 0 */
2516 "!697+1209/100,!0/100", /* 1 */
2517 "!697+1336/100,!0/100", /* 2 */
2518 "!697+1477/100,!0/100", /* 3 */
2519 "!770+1209/100,!0/100", /* 4 */
2520 "!770+1336/100,!0/100", /* 5 */
2521 "!770+1477/100,!0/100", /* 6 */
2522 "!852+1209/100,!0/100", /* 7 */
2523 "!852+1336/100,!0/100", /* 8 */
2524 "!852+1477/100,!0/100", /* 9 */
2525 "!697+1633/100,!0/100", /* A */
2526 "!770+1633/100,!0/100", /* B */
2527 "!852+1633/100,!0/100", /* C */
2528 "!941+1633/100,!0/100", /* D */
2529 "!941+1209/100,!0/100", /* * */
2530 "!941+1477/100,!0/100" }; /* # */
2531 if (digit
>= '0' && digit
<='9')
2532 ast_playtones_start(chan
, 0, dtmf_tones
[digit
-'0'], 0);
2533 else if (digit
>= 'A' && digit
<= 'D')
2534 ast_playtones_start(chan
, 0, dtmf_tones
[digit
-'A'+10], 0);
2535 else if (digit
== '*')
2536 ast_playtones_start(chan
, 0, dtmf_tones
[14], 0);
2537 else if (digit
== '#')
2538 ast_playtones_start(chan
, 0, dtmf_tones
[15], 0);
2542 ast_log(LOG_DEBUG
, "Unable to generate DTMF tone '%c' for '%s'\n", digit
, chan
->name
);
2549 int ast_senddigit_end(struct ast_channel
*chan
, char digit
, unsigned int duration
)
2553 if (chan
->tech
->send_digit_end
)
2554 res
= chan
->tech
->send_digit_end(chan
, digit
, duration
);
2556 if (res
&& chan
->generator
)
2557 ast_playtones_stop(chan
);
2562 int ast_senddigit(struct ast_channel
*chan
, char digit
)
2564 if (!ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
)) {
2565 ast_senddigit_begin(chan
, digit
);
2566 ast_safe_sleep(chan
, 100); /* XXX 100ms ... probably should be configurable */
2569 return ast_senddigit_end(chan
, digit
, 100);
2572 int ast_prod(struct ast_channel
*chan
)
2574 struct ast_frame a
= { AST_FRAME_VOICE
};
2577 /* Send an empty audio frame to get things moving */
2578 if (chan
->_state
!= AST_STATE_UP
) {
2580 ast_log(LOG_DEBUG
, "Prodding channel '%s'\n", chan
->name
);
2581 a
.subclass
= chan
->rawwriteformat
;
2582 a
.data
= nothing
+ AST_FRIENDLY_OFFSET
;
2584 if (ast_write(chan
, &a
))
2585 ast_log(LOG_WARNING
, "Prodding channel '%s' failed\n", chan
->name
);
2590 int ast_write_video(struct ast_channel
*chan
, struct ast_frame
*fr
)
2593 if (!chan
->tech
->write_video
)
2595 res
= ast_write(chan
, fr
);
2601 int ast_write(struct ast_channel
*chan
, struct ast_frame
*fr
)
2604 struct ast_frame
*f
= NULL
;
2606 /* Stop if we're a zombie or need a soft hangup */
2607 ast_channel_lock(chan
);
2608 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
))
2611 /* Handle any pending masquerades */
2612 if (chan
->masq
&& ast_do_masquerade(chan
)) {
2613 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
2617 res
= 0; /* XXX explain, why 0 ? */
2620 if (chan
->generatordata
) {
2621 if (ast_test_flag(chan
, AST_FLAG_WRITE_INT
))
2622 ast_deactivate_generator(chan
);
2624 res
= 0; /* XXX explain, why 0 ? */
2628 /* High bit prints debugging */
2629 if (chan
->fout
& DEBUGCHAN_FLAG
)
2630 ast_frame_dump(chan
->name
, fr
, ">>");
2631 CHECK_BLOCKING(chan
);
2632 switch(fr
->frametype
) {
2633 case AST_FRAME_CONTROL
:
2634 res
= (chan
->tech
->indicate
== NULL
) ? 0 :
2635 chan
->tech
->indicate(chan
, fr
->subclass
, fr
->data
, fr
->datalen
);
2637 case AST_FRAME_DTMF_BEGIN
:
2638 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2639 ast_channel_unlock(chan
);
2640 res
= ast_senddigit_begin(chan
, fr
->subclass
);
2641 ast_channel_lock(chan
);
2642 CHECK_BLOCKING(chan
);
2644 case AST_FRAME_DTMF_END
:
2645 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2646 ast_channel_unlock(chan
);
2647 res
= ast_senddigit_end(chan
, fr
->subclass
, fr
->len
);
2648 ast_channel_lock(chan
);
2649 CHECK_BLOCKING(chan
);
2651 case AST_FRAME_TEXT
:
2652 res
= (chan
->tech
->send_text
== NULL
) ? 0 :
2653 chan
->tech
->send_text(chan
, (char *) fr
->data
);
2655 case AST_FRAME_HTML
:
2656 res
= (chan
->tech
->send_html
== NULL
) ? 0 :
2657 chan
->tech
->send_html(chan
, fr
->subclass
, (char *) fr
->data
, fr
->datalen
);
2659 case AST_FRAME_VIDEO
:
2660 /* XXX Handle translation of video codecs one day XXX */
2661 res
= (chan
->tech
->write_video
== NULL
) ? 0 :
2662 chan
->tech
->write_video(chan
, fr
);
2664 case AST_FRAME_MODEM
:
2665 res
= (chan
->tech
->write
== NULL
) ? 0 :
2666 chan
->tech
->write(chan
, fr
);
2668 case AST_FRAME_VOICE
:
2669 if (chan
->tech
->write
== NULL
)
2670 break; /*! \todo XXX should return 0 maybe ? */
2672 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2673 if (ast_test_flag(chan
, AST_FLAG_WHISPER
)) {
2674 if (fr
->subclass
== AST_FORMAT_SLINEAR
)
2677 ast_mutex_lock(&chan
->whisper
->lock
);
2678 if (chan
->writeformat
!= AST_FORMAT_SLINEAR
) {
2679 /* Rebuild the translation path and set our write format back to signed linear */
2680 chan
->whisper
->original_format
= chan
->writeformat
;
2681 ast_set_write_format(chan
, AST_FORMAT_SLINEAR
);
2682 if (chan
->whisper
->path
)
2683 ast_translator_free_path(chan
->whisper
->path
);
2684 chan
->whisper
->path
= ast_translator_build_path(AST_FORMAT_SLINEAR
, chan
->whisper
->original_format
);
2686 /* Translate frame using the above translation path */
2687 f
= (chan
->whisper
->path
) ? ast_translate(chan
->whisper
->path
, fr
, 0) : fr
;
2688 ast_mutex_unlock(&chan
->whisper
->lock
);
2691 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2692 if (fr
->subclass
== chan
->rawwriteformat
)
2695 f
= (chan
->writetrans
) ? ast_translate(chan
->writetrans
, fr
, 0) : fr
;
2698 /* If we have no frame of audio, then we have to bail out */
2704 /* If spies are on the channel then queue the frame out to them */
2706 queue_frame_to_spies(chan
, f
, SPY_WRITE
);
2708 /* If Monitor is running on this channel, then we have to write frames out there too */
2709 if (chan
->monitor
&& chan
->monitor
->write_stream
) {
2710 /* XXX must explain this code */
2711 #ifndef MONITOR_CONSTANT_DELAY
2712 int jump
= chan
->insmpl
- chan
->outsmpl
- 4 * f
->samples
;
2714 jump
= chan
->insmpl
- chan
->outsmpl
;
2715 if (ast_seekstream(chan
->monitor
->write_stream
, jump
, SEEK_FORCECUR
) == -1)
2716 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2717 chan
->outsmpl
+= jump
+ f
->samples
;
2719 chan
->outsmpl
+= f
->samples
;
2721 int jump
= chan
->insmpl
- chan
->outsmpl
;
2722 if (jump
- MONITOR_DELAY
>= 0) {
2723 if (ast_seekstream(chan
->monitor
->write_stream
, jump
- f
->samples
, SEEK_FORCECUR
) == -1)
2724 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2725 chan
->outsmpl
+= jump
;
2727 chan
->outsmpl
+= f
->samples
;
2729 if (chan
->monitor
->state
== AST_MONITOR_RUNNING
) {
2730 if (ast_writestream(chan
->monitor
->write_stream
, f
) < 0)
2731 ast_log(LOG_WARNING
, "Failed to write data to channel monitor write stream\n");
2735 /* Finally the good part! Write this out to the channel */
2736 if (ast_test_flag(chan
, AST_FLAG_WHISPER
)) {
2737 /* frame is assumed to be in SLINEAR, since that is
2738 required for whisper mode */
2739 ast_frame_adjust_volume(f
, -2);
2740 if (ast_slinfactory_available(&chan
->whisper
->sf
) >= f
->samples
) {
2741 short buf
[f
->samples
];
2742 struct ast_frame whisper
= {
2743 .frametype
= AST_FRAME_VOICE
,
2744 .subclass
= AST_FORMAT_SLINEAR
,
2746 .datalen
= sizeof(buf
),
2747 .samples
= f
->samples
,
2750 ast_mutex_lock(&chan
->whisper
->lock
);
2751 if (ast_slinfactory_read(&chan
->whisper
->sf
, buf
, f
->samples
))
2752 ast_frame_slinear_sum(f
, &whisper
);
2753 ast_mutex_unlock(&chan
->whisper
->lock
);
2755 /* and now put it through the regular translator */
2756 f
= (chan
->writetrans
) ? ast_translate(chan
->writetrans
, f
, 0) : f
;
2759 res
= chan
->tech
->write(chan
, f
);
2763 case AST_FRAME_NULL
:
2769 /* At this point, fr is the incoming frame and f is NULL. Channels do
2770 * not expect to get NULL as a frame pointer and will segfault. Hence,
2771 * we output the original frame passed in. */
2772 res
= chan
->tech
->write(chan
, fr
);
2778 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2779 /* Consider a write failure to force a soft hangup */
2781 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
2783 chan
->fout
= FRAMECOUNT_INC(chan
->fout
);
2786 ast_channel_unlock(chan
);
2790 static int set_format(struct ast_channel
*chan
, int fmt
, int *rawformat
, int *format
,
2791 struct ast_trans_pvt
**trans
, const int direction
)
2796 /* Make sure we only consider audio */
2797 fmt
&= AST_FORMAT_AUDIO_MASK
;
2799 native
= chan
->nativeformats
;
2800 /* Find a translation path from the native format to one of the desired formats */
2803 res
= ast_translator_best_choice(&fmt
, &native
);
2806 res
= ast_translator_best_choice(&native
, &fmt
);
2809 ast_log(LOG_WARNING
, "Unable to find a codec translation path from %s to %s\n",
2810 ast_getformatname(native
), ast_getformatname(fmt
));
2814 /* Now we have a good choice for both. */
2815 ast_channel_lock(chan
);
2817 if ((*rawformat
== native
) && (*format
== fmt
) && ((*rawformat
== *format
) || (*trans
))) {
2818 /* the channel is already in these formats, so nothing to do */
2819 ast_channel_unlock(chan
);
2823 *rawformat
= native
;
2824 /* User perspective is fmt */
2826 /* Free any read translation we have right now */
2828 ast_translator_free_path(*trans
);
2829 /* Build a translation path from the raw format to the desired format */
2832 *trans
= ast_translator_build_path(*format
, *rawformat
);
2835 *trans
= ast_translator_build_path(*rawformat
, *format
);
2836 ast_channel_unlock(chan
);
2838 ast_log(LOG_DEBUG
, "Set channel %s to %s format %s\n", chan
->name
,
2839 direction
? "write" : "read", ast_getformatname(fmt
));
2843 int ast_set_read_format(struct ast_channel
*chan
, int fmt
)
2845 return set_format(chan
, fmt
, &chan
->rawreadformat
, &chan
->readformat
,
2846 &chan
->readtrans
, 0);
2849 int ast_set_write_format(struct ast_channel
*chan
, int fmt
)
2851 return set_format(chan
, fmt
, &chan
->rawwriteformat
, &chan
->writeformat
,
2852 &chan
->writetrans
, 1);
2855 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
)
2859 struct ast_channel
*chan
;
2865 outstate
= &dummy_outstate
; /* make outstate always a valid pointer */
2867 chan
= ast_request(type
, format
, data
, &cause
);
2869 ast_log(LOG_NOTICE
, "Unable to request channel %s/%s\n", type
, (char *)data
);
2870 /* compute error and return */
2871 if (cause
== AST_CAUSE_BUSY
)
2872 *outstate
= AST_CONTROL_BUSY
;
2873 else if (cause
== AST_CAUSE_CONGESTION
)
2874 *outstate
= AST_CONTROL_CONGESTION
;
2880 ast_set_variables(chan
, oh
->vars
);
2881 /* XXX why is this necessary, for the parent_channel perhaps ? */
2882 if (!ast_strlen_zero(oh
->cid_num
) && !ast_strlen_zero(oh
->cid_name
))
2883 ast_set_callerid(chan
, oh
->cid_num
, oh
->cid_name
, oh
->cid_num
);
2884 if (oh
->parent_channel
)
2885 ast_channel_inherit_variables(oh
->parent_channel
, chan
);
2887 ast_cdr_setaccount(chan
, oh
->account
);
2889 ast_set_callerid(chan
, cid_num
, cid_name
, cid_num
);
2891 if (ast_call(chan
, data
, 0)) { /* ast_call failed... */
2892 ast_log(LOG_NOTICE
, "Unable to call channel %s/%s\n", type
, (char *)data
);
2894 res
= 1; /* mark success in case chan->_state is already AST_STATE_UP */
2895 while (timeout
&& chan
->_state
!= AST_STATE_UP
) {
2896 struct ast_frame
*f
;
2897 res
= ast_waitfor(chan
, timeout
);
2898 if (res
<= 0) /* error, timeout, or done */
2904 *outstate
= AST_CONTROL_HANGUP
;
2908 if (f
->frametype
== AST_FRAME_CONTROL
) {
2909 switch (f
->subclass
) {
2910 case AST_CONTROL_RINGING
: /* record but keep going */
2911 *outstate
= f
->subclass
;
2914 case AST_CONTROL_BUSY
:
2915 case AST_CONTROL_CONGESTION
:
2916 case AST_CONTROL_ANSWER
:
2917 *outstate
= f
->subclass
;
2918 timeout
= 0; /* trick to force exit from the while() */
2922 case AST_CONTROL_PROGRESS
:
2923 case AST_CONTROL_PROCEEDING
:
2924 case AST_CONTROL_HOLD
:
2925 case AST_CONTROL_UNHOLD
:
2926 case AST_CONTROL_VIDUPDATE
:
2927 case -1: /* Ignore -- just stopping indications */
2931 ast_log(LOG_NOTICE
, "Don't know what to do with control frame %d\n", f
->subclass
);
2940 if (!ast_strlen_zero(oh
->context
))
2941 ast_copy_string(chan
->context
, oh
->context
, sizeof(chan
->context
));
2942 if (!ast_strlen_zero(oh
->exten
))
2943 ast_copy_string(chan
->exten
, oh
->exten
, sizeof(chan
->exten
));
2945 chan
->priority
= oh
->priority
;
2947 if (chan
->_state
== AST_STATE_UP
)
2948 *outstate
= AST_CONTROL_ANSWER
;
2951 if (!chan
->cdr
&& (chan
->cdr
= ast_cdr_alloc()))
2952 ast_cdr_init(chan
->cdr
, chan
);
2955 snprintf(tmp
, sizeof(tmp
), "%s/%s", type
, (char *)data
);
2956 ast_cdr_setapp(chan
->cdr
,"Dial",tmp
);
2957 ast_cdr_update(chan
);
2958 ast_cdr_start(chan
->cdr
);
2959 ast_cdr_end(chan
->cdr
);
2960 /* If the cause wasn't handled properly */
2961 if (ast_cdr_disposition(chan
->cdr
,chan
->hangupcause
))
2962 ast_cdr_failed(chan
->cdr
);
2970 struct ast_channel
*ast_request_and_dial(const char *type
, int format
, void *data
, int timeout
, int *outstate
, const char *cidnum
, const char *cidname
)
2972 return __ast_request_and_dial(type
, format
, data
, timeout
, outstate
, cidnum
, cidname
, NULL
);
2975 struct ast_channel
*ast_request(const char *type
, int format
, void *data
, int *cause
)
2977 struct chanlist
*chan
;
2978 struct ast_channel
*c
;
2983 int videoformat
= format
& AST_FORMAT_VIDEO_MASK
;
2987 *cause
= AST_CAUSE_NOTDEFINED
;
2989 if (AST_LIST_LOCK(&channels
)) {
2990 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
2994 AST_LIST_TRAVERSE(&backends
, chan
, list
) {
2995 if (strcasecmp(type
, chan
->tech
->type
))
2998 capabilities
= chan
->tech
->capabilities
;
2999 fmt
= format
& AST_FORMAT_AUDIO_MASK
;
3000 res
= ast_translator_best_choice(&fmt
, &capabilities
);
3002 ast_log(LOG_WARNING
, "No translator path exists for channel type %s (native %d) to %d\n", type
, chan
->tech
->capabilities
, format
);
3003 AST_LIST_UNLOCK(&channels
);
3006 AST_LIST_UNLOCK(&channels
);
3007 if (!chan
->tech
->requester
)
3010 if (!(c
= chan
->tech
->requester(type
, capabilities
| videoformat
, data
, cause
)))
3013 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3017 ast_log(LOG_WARNING
, "No channel type registered for '%s'\n", type
);
3018 *cause
= AST_CAUSE_NOSUCHDRIVER
;
3019 AST_LIST_UNLOCK(&channels
);
3024 int ast_call(struct ast_channel
*chan
, char *addr
, int timeout
)
3026 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3027 If the remote end does not answer within the timeout, then do NOT hang up, but
3030 /* Stop if we're a zombie or need a soft hangup */
3031 ast_channel_lock(chan
);
3032 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
) && !ast_check_hangup(chan
)) {
3033 if (chan
->tech
->call
)
3034 res
= chan
->tech
->call(chan
, addr
, timeout
);
3035 ast_set_flag(chan
, AST_FLAG_OUTGOING
);
3037 ast_channel_unlock(chan
);
3042 \brief Transfer a call to dest, if the channel supports transfer
3046 \arg the manager interface
3048 int ast_transfer(struct ast_channel
*chan
, char *dest
)
3052 /* Stop if we're a zombie or need a soft hangup */
3053 ast_channel_lock(chan
);
3054 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
) && !ast_check_hangup(chan
)) {
3055 if (chan
->tech
->transfer
) {
3056 res
= chan
->tech
->transfer(chan
, dest
);
3062 ast_channel_unlock(chan
);
3066 int ast_readstring(struct ast_channel
*c
, char *s
, int len
, int timeout
, int ftimeout
, char *enders
)
3068 return ast_readstring_full(c
, s
, len
, timeout
, ftimeout
, enders
, -1, -1);
3071 int ast_readstring_full(struct ast_channel
*c
, char *s
, int len
, int timeout
, int ftimeout
, char *enders
, int audiofd
, int ctrlfd
)
3073 int pos
= 0; /* index in the buffer where we accumulate digits */
3076 /* Stop if we're a zombie or need a soft hangup */
3077 if (ast_test_flag(c
, AST_FLAG_ZOMBIE
) || ast_check_hangup(c
))
3084 d
= ast_waitstream_full(c
, AST_DIGIT_ANY
, audiofd
, ctrlfd
);
3088 d
= ast_waitfordigit_full(c
, to
, audiofd
, ctrlfd
);
3090 d
= ast_waitfordigit_full(c
, to
, audiofd
, ctrlfd
);
3102 if (!strchr(enders
, d
))
3104 if (strchr(enders
, d
) || (pos
>= len
)) {
3114 int ast_channel_supports_html(struct ast_channel
*chan
)
3116 return (chan
->tech
->send_html
) ? 1 : 0;
3119 int ast_channel_sendhtml(struct ast_channel
*chan
, int subclass
, const char *data
, int datalen
)
3121 if (chan
->tech
->send_html
)
3122 return chan
->tech
->send_html(chan
, subclass
, data
, datalen
);
3126 int ast_channel_sendurl(struct ast_channel
*chan
, const char *url
)
3128 return ast_channel_sendhtml(chan
, AST_HTML_URL
, url
, strlen(url
) + 1);
3131 int ast_channel_make_compatible(struct ast_channel
*chan
, struct ast_channel
*peer
)
3136 /* Set up translation from the chan to the peer */
3137 src
= chan
->nativeformats
;
3138 dst
= peer
->nativeformats
;
3139 if (ast_translator_best_choice(&dst
, &src
) < 0) {
3140 ast_log(LOG_WARNING
, "No path to translate from %s(%d) to %s(%d)\n", chan
->name
, src
, peer
->name
, dst
);
3144 /* if the best path is not 'pass through', then
3145 transcoding is needed; if desired, force transcode path
3146 to use SLINEAR between channels, but only if there is
3147 no direct conversion available */
3148 if ((src
!= dst
) && ast_opt_transcode_via_slin
&&
3149 (ast_translate_path_steps(dst
, src
) != 1))
3150 dst
= AST_FORMAT_SLINEAR
;
3151 if (ast_set_read_format(chan
, dst
) < 0) {
3152 ast_log(LOG_WARNING
, "Unable to set read format on channel %s to %d\n", chan
->name
, dst
);
3155 if (ast_set_write_format(peer
, dst
) < 0) {
3156 ast_log(LOG_WARNING
, "Unable to set write format on channel %s to %d\n", peer
->name
, dst
);
3160 /* Set up translation from the peer to the chan */
3161 src
= peer
->nativeformats
;
3162 dst
= chan
->nativeformats
;
3163 if (ast_translator_best_choice(&dst
, &src
) < 0) {
3164 ast_log(LOG_WARNING
, "No path to translate from %s(%d) to %s(%d)\n", peer
->name
, src
, chan
->name
, dst
);
3168 /* if the best path is not 'pass through', then
3169 transcoding is needed; if desired, force transcode path
3170 to use SLINEAR between channels, but only if there is
3171 no direct conversion available */
3172 if ((src
!= dst
) && ast_opt_transcode_via_slin
&&
3173 (ast_translate_path_steps(dst
, src
) != 1))
3174 dst
= AST_FORMAT_SLINEAR
;
3175 if (ast_set_read_format(peer
, dst
) < 0) {
3176 ast_log(LOG_WARNING
, "Unable to set read format on channel %s to %d\n", peer
->name
, dst
);
3179 if (ast_set_write_format(chan
, dst
) < 0) {
3180 ast_log(LOG_WARNING
, "Unable to set write format on channel %s to %d\n", chan
->name
, dst
);
3186 int ast_channel_masquerade(struct ast_channel
*original
, struct ast_channel
*clone
)
3189 struct ast_channel
*final_orig
= original
, *final_clone
= clone
;
3191 ast_channel_lock(original
);
3192 while (ast_channel_trylock(clone
)) {
3193 ast_channel_unlock(original
);
3195 ast_channel_lock(original
);
3198 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3199 and if so, we don't really want to masquerade it, but its proxy */
3200 if (original
->_bridge
&& (original
->_bridge
!= ast_bridged_channel(original
)))
3201 final_orig
= original
->_bridge
;
3203 if (clone
->_bridge
&& (clone
->_bridge
!= ast_bridged_channel(clone
)))
3204 final_clone
= clone
->_bridge
;
3206 if ((final_orig
!= original
) || (final_clone
!= clone
)) {
3207 ast_channel_lock(final_orig
);
3208 while (ast_channel_trylock(final_clone
)) {
3209 ast_channel_unlock(final_orig
);
3211 ast_channel_lock(final_orig
);
3213 ast_channel_unlock(clone
);
3214 ast_channel_unlock(original
);
3215 original
= final_orig
;
3216 clone
= final_clone
;
3219 if (original
== clone
) {
3220 ast_log(LOG_WARNING
, "Can't masquerade channel '%s' into itself!\n", original
->name
);
3221 ast_channel_unlock(clone
);
3222 ast_channel_unlock(original
);
3227 ast_log(LOG_DEBUG
, "Planning to masquerade channel %s into the structure of %s\n",
3228 clone
->name
, original
->name
);
3229 if (original
->masq
) {
3230 ast_log(LOG_WARNING
, "%s is already going to masquerade as %s\n",
3231 original
->masq
->name
, original
->name
);
3232 } else if (clone
->masqr
) {
3233 ast_log(LOG_WARNING
, "%s is already going to masquerade as %s\n",
3234 clone
->name
, clone
->masqr
->name
);
3236 original
->masq
= clone
;
3237 clone
->masqr
= original
;
3238 ast_queue_frame(original
, &ast_null_frame
);
3239 ast_queue_frame(clone
, &ast_null_frame
);
3241 ast_log(LOG_DEBUG
, "Done planning to masquerade channel %s into the structure of %s\n", clone
->name
, original
->name
);
3245 ast_channel_unlock(clone
);
3246 ast_channel_unlock(original
);
3251 void ast_change_name(struct ast_channel
*chan
, char *newname
)
3253 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan
->name
, newname
, chan
->uniqueid
);
3254 ast_string_field_set(chan
, name
, newname
);
3257 void ast_channel_inherit_variables(const struct ast_channel
*parent
, struct ast_channel
*child
)
3259 struct ast_var_t
*current
, *newvar
;
3260 const char *varname
;
3262 AST_LIST_TRAVERSE(&parent
->varshead
, current
, entries
) {
3265 varname
= ast_var_full_name(current
);
3269 if (varname
[0] == '_') {
3271 if (varname
[1] == '_')
3277 newvar
= ast_var_assign(&varname
[1], ast_var_value(current
));
3279 AST_LIST_INSERT_TAIL(&child
->varshead
, newvar
, entries
);
3281 ast_log(LOG_DEBUG
, "Copying soft-transferable variable %s.\n", ast_var_name(newvar
));
3285 newvar
= ast_var_assign(ast_var_full_name(current
), ast_var_value(current
));
3287 AST_LIST_INSERT_TAIL(&child
->varshead
, newvar
, entries
);
3289 ast_log(LOG_DEBUG
, "Copying hard-transferable variable %s.\n", ast_var_name(newvar
));
3294 ast_log(LOG_DEBUG
, "Not copying variable %s.\n", ast_var_name(current
));
3301 \brief Clone channel variables from 'clone' channel into 'original' channel
3303 All variables except those related to app_groupcount are cloned.
3304 Variables are actually _removed_ from 'clone' channel, presumably
3305 because it will subsequently be destroyed.
3307 \note Assumes locks will be in place on both channels when called.
3309 static void clone_variables(struct ast_channel
*original
, struct ast_channel
*clone
)
3311 struct ast_var_t
*varptr
;
3313 /* we need to remove all app_groupcount related variables from the original
3314 channel before merging in the clone's variables; any groups assigned to the
3315 original channel should be released, only those assigned to the clone
3319 AST_LIST_TRAVERSE_SAFE_BEGIN(&original
->varshead
, varptr
, entries
) {
3320 if (!strncmp(ast_var_name(varptr
), GROUP_CATEGORY_PREFIX
, strlen(GROUP_CATEGORY_PREFIX
))) {
3321 AST_LIST_REMOVE_CURRENT(&original
->varshead
, entries
);
3322 ast_var_delete(varptr
);
3325 AST_LIST_TRAVERSE_SAFE_END
;
3327 /* Append variables from clone channel into original channel */
3328 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3329 if (AST_LIST_FIRST(&clone
->varshead
))
3330 AST_LIST_APPEND_LIST(&original
->varshead
, &clone
->varshead
, entries
);
3334 \brief Masquerade a channel
3336 \note Assumes channel will be locked when called
3338 int ast_do_masquerade(struct ast_channel
*original
)
3343 struct ast_frame
*cur
;
3344 const struct ast_channel_tech
*t
;
3346 struct ast_callerid tmpcid
;
3347 struct ast_channel
*clone
= original
->masq
;
3348 struct ast_channel_spy_list
*spy_list
= NULL
;
3349 struct ast_channel_spy
*spy
= NULL
;
3350 int rformat
= original
->readformat
;
3351 int wformat
= original
->writeformat
;
3357 if (option_debug
> 3)
3358 ast_log(LOG_DEBUG
, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3359 clone
->name
, clone
->_state
, original
->name
, original
->_state
);
3361 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3362 the clone channel into the original channel. Start by killing off the original
3363 channel's backend. I'm not sure we're going to keep this function, because
3364 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3366 /* We need the clone's lock, too */
3367 ast_channel_lock(clone
);
3369 if (option_debug
> 1)
3370 ast_log(LOG_DEBUG
, "Got clone lock for masquerade on '%s' at %p\n", clone
->name
, &clone
->lock
);
3372 /* Having remembered the original read/write formats, we turn off any translation on either
3374 free_translation(clone
);
3375 free_translation(original
);
3378 /* Unlink the masquerade */
3379 original
->masq
= NULL
;
3380 clone
->masqr
= NULL
;
3382 /* Save the original name */
3383 ast_copy_string(orig
, original
->name
, sizeof(orig
));
3384 /* Save the new name */
3385 ast_copy_string(newn
, clone
->name
, sizeof(newn
));
3386 /* Create the masq name */
3387 snprintf(masqn
, sizeof(masqn
), "%s<MASQ>", newn
);
3389 /* Copy the name from the clone channel */
3390 ast_string_field_set(original
, name
, newn
);
3392 /* Mangle the name of the clone channel */
3393 ast_string_field_set(clone
, name
, masqn
);
3395 /* Notify any managers of the change, first the masq then the other */
3396 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn
, masqn
, clone
->uniqueid
);
3397 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig
, newn
, original
->uniqueid
);
3399 /* Swap the technologies */
3401 original
->tech
= clone
->tech
;
3404 t_pvt
= original
->tech_pvt
;
3405 original
->tech_pvt
= clone
->tech_pvt
;
3406 clone
->tech_pvt
= t_pvt
;
3408 /* Swap the readq's */
3409 cur
= AST_LIST_FIRST(&original
->readq
);
3410 AST_LIST_HEAD_SET_NOLOCK(&original
->readq
, AST_LIST_FIRST(&clone
->readq
));
3411 AST_LIST_HEAD_SET_NOLOCK(&clone
->readq
, cur
);
3413 /* Swap the alertpipes */
3414 for (i
= 0; i
< 2; i
++) {
3415 x
= original
->alertpipe
[i
];
3416 original
->alertpipe
[i
] = clone
->alertpipe
[i
];
3417 clone
->alertpipe
[i
] = x
;
3420 /* Swap the raw formats */
3421 x
= original
->rawreadformat
;
3422 original
->rawreadformat
= clone
->rawreadformat
;
3423 clone
->rawreadformat
= x
;
3424 x
= original
->rawwriteformat
;
3425 original
->rawwriteformat
= clone
->rawwriteformat
;
3426 clone
->rawwriteformat
= x
;
3428 /* Swap the spies */
3429 spy_list
= original
->spies
;
3430 original
->spies
= clone
->spies
;
3431 clone
->spies
= spy_list
;
3433 /* Update channel on respective spy lists if present */
3434 if (original
->spies
) {
3435 AST_LIST_TRAVERSE(&original
->spies
->list
, spy
, list
) {
3436 ast_mutex_lock(&spy
->lock
);
3437 spy
->chan
= original
;
3438 ast_mutex_unlock(&spy
->lock
);
3442 AST_LIST_TRAVERSE(&clone
->spies
->list
, spy
, list
) {
3443 ast_mutex_lock(&spy
->lock
);
3445 ast_mutex_unlock(&spy
->lock
);
3449 /* Save any pending frames on both sides. Start by counting
3450 * how many we're going to need... */
3452 if (original
->alertpipe
[1] > -1) {
3453 AST_LIST_TRAVERSE(&clone
->readq
, cur
, frame_list
)
3457 /* If we had any, prepend them to the ones already in the queue, and
3458 * load up the alertpipe */
3459 if (AST_LIST_FIRST(&clone
->readq
)) {
3460 AST_LIST_INSERT_TAIL(&clone
->readq
, AST_LIST_FIRST(&original
->readq
), frame_list
);
3461 AST_LIST_HEAD_SET_NOLOCK(&original
->readq
, AST_LIST_FIRST(&clone
->readq
));
3462 AST_LIST_HEAD_SET_NOLOCK(&clone
->readq
, NULL
);
3463 for (i
= 0; i
< x
; i
++)
3464 write(original
->alertpipe
[1], &x
, sizeof(x
));
3467 clone
->_softhangup
= AST_SOFTHANGUP_DEV
;
3470 /* And of course, so does our current state. Note we need not
3471 call ast_setstate since the event manager doesn't really consider
3472 these separate. We do this early so that the clone has the proper
3473 state of the original channel. */
3474 origstate
= original
->_state
;
3475 original
->_state
= clone
->_state
;
3476 clone
->_state
= origstate
;
3478 if (clone
->tech
->fixup
){
3479 res
= clone
->tech
->fixup(original
, clone
);
3481 ast_log(LOG_WARNING
, "Fixup failed on channel %s, strange things may happen.\n", clone
->name
);
3484 /* Start by disconnecting the original's physical side */
3485 if (clone
->tech
->hangup
)
3486 res
= clone
->tech
->hangup(clone
);
3488 ast_log(LOG_WARNING
, "Hangup failed! Strange things may happen!\n");
3489 ast_channel_unlock(clone
);
3493 snprintf(zombn
, sizeof(zombn
), "%s<ZOMBIE>", orig
);
3494 /* Mangle the name of the clone channel */
3495 ast_string_field_set(clone
, name
, zombn
);
3496 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn
, zombn
, clone
->uniqueid
);
3498 /* Update the type. */
3499 t_pvt
= original
->monitor
;
3500 original
->monitor
= clone
->monitor
;
3501 clone
->monitor
= t_pvt
;
3503 /* Keep the same language. */
3504 ast_string_field_set(original
, language
, clone
->language
);
3505 /* Copy the FD's other than the generator fd */
3506 for (x
= 0; x
< AST_MAX_FDS
; x
++) {
3507 if (x
!= AST_GENERATOR_FD
)
3508 original
->fds
[x
] = clone
->fds
[x
];
3511 /* move any whisperer over */
3512 ast_channel_whisper_stop(original
);
3513 if (ast_test_flag(clone
, AST_FLAG_WHISPER
)) {
3514 original
->whisper
= clone
->whisper
;
3515 ast_set_flag(original
, AST_FLAG_WHISPER
);
3516 clone
->whisper
= NULL
;
3517 ast_clear_flag(clone
, AST_FLAG_WHISPER
);
3520 /* Move data stores over */
3521 if (AST_LIST_FIRST(&clone
->datastores
))
3522 AST_LIST_INSERT_TAIL(&original
->datastores
, AST_LIST_FIRST(&clone
->datastores
), entry
);
3523 AST_LIST_HEAD_INIT_NOLOCK(&clone
->datastores
);
3525 clone_variables(original
, clone
);
3526 AST_LIST_HEAD_INIT_NOLOCK(&clone
->varshead
);
3527 /* Presense of ADSI capable CPE follows clone */
3528 original
->adsicpe
= clone
->adsicpe
;
3529 /* Bridge remains the same */
3530 /* CDR fields remain the same */
3531 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3532 /* Application and data remain the same */
3533 /* Clone exception becomes real one, as with fdno */
3534 ast_copy_flags(original
, clone
, AST_FLAG_EXCEPTION
);
3535 original
->fdno
= clone
->fdno
;
3536 /* Schedule context remains the same */
3537 /* Stream stuff stays the same */
3538 /* Keep the original state. The fixup code will need to work with it most likely */
3540 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3542 tmpcid
= original
->cid
;
3543 original
->cid
= clone
->cid
;
3544 clone
->cid
= tmpcid
;
3546 /* Restore original timing file descriptor */
3547 original
->fds
[AST_TIMING_FD
] = original
->timingfd
;
3549 /* Our native formats are different now */
3550 original
->nativeformats
= clone
->nativeformats
;
3552 /* Context, extension, priority, app data, jump table, remain the same */
3553 /* pvt switches. pbx stays the same, as does next */
3555 /* Set the write format */
3556 ast_set_write_format(original
, wformat
);
3558 /* Set the read format */
3559 ast_set_read_format(original
, rformat
);
3561 /* Copy the music class */
3562 ast_string_field_set(original
, musicclass
, clone
->musicclass
);
3565 ast_log(LOG_DEBUG
, "Putting channel %s in %d/%d formats\n", original
->name
, wformat
, rformat
);
3567 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3568 can fix up everything as best as possible */
3569 if (original
->tech
->fixup
) {
3570 res
= original
->tech
->fixup(clone
, original
);
3572 ast_log(LOG_WARNING
, "Channel for type '%s' could not fixup channel %s\n",
3573 original
->tech
->type
, original
->name
);
3574 ast_channel_unlock(clone
);
3578 ast_log(LOG_WARNING
, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3579 original
->tech
->type
, original
->name
);
3581 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3582 a zombie so nothing tries to touch it. If it's already been marked as a
3583 zombie, then free it now (since it already is considered invalid). */
3584 if (ast_test_flag(clone
, AST_FLAG_ZOMBIE
)) {
3586 ast_log(LOG_DEBUG
, "Destroying channel clone '%s'\n", clone
->name
);
3587 ast_channel_unlock(clone
);
3588 manager_event(EVENT_FLAG_CALL
, "Hangup",
3592 "Cause-txt: %s\r\n",
3596 ast_cause2str(clone
->hangupcause
)
3598 ast_channel_free(clone
);
3601 ast_log(LOG_DEBUG
, "Released clone lock on '%s'\n", clone
->name
);
3602 ast_set_flag(clone
, AST_FLAG_ZOMBIE
);
3603 ast_queue_frame(clone
, &ast_null_frame
);
3604 ast_channel_unlock(clone
);
3607 /* Signal any blocker */
3608 if (ast_test_flag(original
, AST_FLAG_BLOCKING
))
3609 pthread_kill(original
->blocker
, SIGURG
);
3611 ast_log(LOG_DEBUG
, "Done Masquerading %s (%d)\n", original
->name
, original
->_state
);
3615 void ast_set_callerid(struct ast_channel
*chan
, const char *callerid
, const char *calleridname
, const char *ani
)
3618 if (chan
->cid
.cid_num
)
3619 free(chan
->cid
.cid_num
);
3620 chan
->cid
.cid_num
= ast_strdup(callerid
);
3623 if (chan
->cid
.cid_name
)
3624 free(chan
->cid
.cid_name
);
3625 chan
->cid
.cid_name
= ast_strdup(calleridname
);
3628 if (chan
->cid
.cid_ani
)
3629 free(chan
->cid
.cid_ani
);
3630 chan
->cid
.cid_ani
= ast_strdup(ani
);
3633 ast_cdr_setcid(chan
->cdr
, chan
);
3634 manager_event(EVENT_FLAG_CALL
, "Newcallerid",
3637 "CallerIDName: %s\r\n"
3639 "CID-CallingPres: %d (%s)\r\n",
3641 S_OR(chan
->cid
.cid_num
, "<Unknown>"),
3642 S_OR(chan
->cid
.cid_name
, "<Unknown>"),
3645 ast_describe_caller_presentation(chan
->cid
.cid_pres
)
3649 int ast_setstate(struct ast_channel
*chan
, enum ast_channel_state state
)
3651 int oldstate
= chan
->_state
;
3653 if (oldstate
== state
)
3656 chan
->_state
= state
;
3657 ast_device_state_changed_literal(chan
->name
);
3658 /* setstate used to conditionally report Newchannel; this is no more */
3659 manager_event(EVENT_FLAG_CALL
,
3664 "CallerIDName: %s\r\n"
3666 chan
->name
, ast_state2str(chan
->_state
),
3667 S_OR(chan
->cid
.cid_num
, "<unknown>"),
3668 S_OR(chan
->cid
.cid_name
, "<unknown>"),
3674 /*! \brief Find bridged channel */
3675 struct ast_channel
*ast_bridged_channel(struct ast_channel
*chan
)
3677 struct ast_channel
*bridged
;
3678 bridged
= chan
->_bridge
;
3679 if (bridged
&& bridged
->tech
->bridged_channel
)
3680 bridged
= bridged
->tech
->bridged_channel(chan
, bridged
);
3684 static void bridge_playfile(struct ast_channel
*chan
, struct ast_channel
*peer
, const char *sound
, int remain
)
3686 int min
= 0, sec
= 0, check
;
3688 check
= ast_autoservice_start(peer
);
3693 if (remain
/ 60 > 1) {
3701 if (!strcmp(sound
,"timeleft")) { /* Queue support */
3702 ast_stream_and_wait(chan
, "vm-youhave", chan
->language
, "");
3704 ast_say_number(chan
, min
, AST_DIGIT_ANY
, chan
->language
, NULL
);
3705 ast_stream_and_wait(chan
, "queue-minutes", chan
->language
, "");
3708 ast_say_number(chan
, sec
, AST_DIGIT_ANY
, chan
->language
, NULL
);
3709 ast_stream_and_wait(chan
, "queue-seconds", chan
->language
, "");
3712 ast_stream_and_wait(chan
, sound
, chan
->language
, "");
3715 ast_autoservice_stop(peer
);
3718 static enum ast_bridge_result
ast_generic_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
,
3719 struct ast_bridge_config
*config
, struct ast_frame
**fo
,
3720 struct ast_channel
**rc
, struct timeval bridge_end
)
3722 /* Copy voice back and forth between the two channels. */
3723 struct ast_channel
*cs
[3];
3724 struct ast_frame
*f
;
3725 enum ast_bridge_result res
= AST_BRIDGE_COMPLETE
;
3726 int o0nativeformats
;
3727 int o1nativeformats
;
3731 /* Indicates whether a frame was queued into a jitterbuffer */
3732 int frame_put_in_jb
= 0;
3738 pvt0
= c0
->tech_pvt
;
3739 pvt1
= c1
->tech_pvt
;
3740 o0nativeformats
= c0
->nativeformats
;
3741 o1nativeformats
= c1
->nativeformats
;
3742 watch_c0_dtmf
= config
->flags
& AST_BRIDGE_DTMF_CHANNEL_0
;
3743 watch_c1_dtmf
= config
->flags
& AST_BRIDGE_DTMF_CHANNEL_1
;
3745 /* Check the need of a jitterbuffer for each channel */
3746 jb_in_use
= ast_jb_do_usecheck(c0
, c1
);
3749 struct ast_channel
*who
, *other
;
3751 if ((c0
->tech_pvt
!= pvt0
) || (c1
->tech_pvt
!= pvt1
) ||
3752 (o0nativeformats
!= c0
->nativeformats
) ||
3753 (o1nativeformats
!= c1
->nativeformats
)) {
3754 /* Check for Masquerade, codec changes, etc */
3755 res
= AST_BRIDGE_RETRY
;
3758 if (bridge_end
.tv_sec
) {
3759 to
= ast_tvdiff_ms(bridge_end
, ast_tvnow());
3761 if (config
->timelimit
)
3762 res
= AST_BRIDGE_RETRY
;
3764 res
= AST_BRIDGE_COMPLETE
;
3769 /* Calculate the appropriate max sleep interval - in general, this is the time,
3770 left to the closest jb delivery moment */
3772 to
= ast_jb_get_when_to_wakeup(c0
, c1
, to
);
3773 who
= ast_waitfor_n(cs
, 2, &to
);
3775 /* No frame received within the specified timeout - check if we have to deliver now */
3777 ast_jb_get_and_deliver(c0
, c1
);
3778 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
) {
3779 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
3780 c0
->_softhangup
= 0;
3781 if (c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
3782 c1
->_softhangup
= 0;
3793 ast_log(LOG_DEBUG
, "Didn't get a frame from channel: %s\n",who
->name
);
3797 other
= (who
== c0
) ? c1
: c0
; /* the 'other' channel */
3798 /* Try add the frame info the who's bridged channel jitterbuff */
3800 frame_put_in_jb
= !ast_jb_put(other
, f
);
3802 if ((f
->frametype
== AST_FRAME_CONTROL
) && !(config
->flags
& AST_BRIDGE_IGNORE_SIGS
)) {
3803 int bridge_exit
= 0;
3805 switch (f
->subclass
) {
3806 case AST_CONTROL_HOLD
:
3807 case AST_CONTROL_UNHOLD
:
3808 case AST_CONTROL_VIDUPDATE
:
3809 ast_indicate_data(other
, f
->subclass
, f
->data
, f
->datalen
);
3816 ast_log(LOG_DEBUG
, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f
->subclass
, who
->name
);
3822 if ((f
->frametype
== AST_FRAME_VOICE
) ||
3823 (f
->frametype
== AST_FRAME_DTMF_BEGIN
) ||
3824 (f
->frametype
== AST_FRAME_DTMF
) ||
3825 (f
->frametype
== AST_FRAME_VIDEO
) ||
3826 (f
->frametype
== AST_FRAME_IMAGE
) ||
3827 (f
->frametype
== AST_FRAME_HTML
) ||
3828 (f
->frametype
== AST_FRAME_MODEM
) ||
3829 (f
->frametype
== AST_FRAME_TEXT
)) {
3830 /* monitored dtmf causes exit from bridge */
3831 int monitored_source
= (who
== c0
) ? watch_c0_dtmf
: watch_c1_dtmf
;
3833 if (monitored_source
&&
3834 (f
->frametype
== AST_FRAME_DTMF_END
||
3835 f
->frametype
== AST_FRAME_DTMF_BEGIN
)) {
3839 ast_log(LOG_DEBUG
, "Got DTMF %s on channel (%s)\n",
3840 f
->frametype
== AST_FRAME_DTMF_END
? "end" : "begin",
3844 /* Write immediately frames, not passed through jb */
3845 if (!frame_put_in_jb
)
3846 ast_write(other
, f
);
3848 /* Check if we have to deliver now */
3850 ast_jb_get_and_deliver(c0
, c1
);
3852 /* XXX do we want to pass on also frames not matched above ? */
3855 /* Swap who gets priority */
3863 /*! \brief Bridge two channels together */
3864 enum ast_bridge_result
ast_channel_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
,
3865 struct ast_bridge_config
*config
, struct ast_frame
**fo
, struct ast_channel
**rc
)
3867 struct ast_channel
*who
= NULL
;
3868 enum ast_bridge_result res
= AST_BRIDGE_COMPLETE
;
3871 int o0nativeformats
;
3872 int o1nativeformats
;
3873 long time_left_ms
=0;
3874 struct timeval nexteventts
= { 0, };
3875 char caller_warning
= 0;
3876 char callee_warning
= 0;
3879 ast_log(LOG_WARNING
, "%s is already in a bridge with %s\n",
3880 c0
->name
, c0
->_bridge
->name
);
3884 ast_log(LOG_WARNING
, "%s is already in a bridge with %s\n",
3885 c1
->name
, c1
->_bridge
->name
);
3889 /* Stop if we're a zombie or need a soft hangup */
3890 if (ast_test_flag(c0
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c0
) ||
3891 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c1
))
3895 firstpass
= config
->firstpass
;
3896 config
->firstpass
= 0;
3898 if (ast_tvzero(config
->start_time
))
3899 config
->start_time
= ast_tvnow();
3900 time_left_ms
= config
->timelimit
;
3902 caller_warning
= ast_test_flag(&config
->features_caller
, AST_FEATURE_PLAY_WARNING
);
3903 callee_warning
= ast_test_flag(&config
->features_callee
, AST_FEATURE_PLAY_WARNING
);
3905 if (config
->start_sound
&& firstpass
) {
3907 bridge_playfile(c0
, c1
, config
->start_sound
, time_left_ms
/ 1000);
3909 bridge_playfile(c1
, c0
, config
->start_sound
, time_left_ms
/ 1000);
3912 /* Keep track of bridge */
3916 /* \todo XXX here should check that cid_num is not NULL */
3917 manager_event(EVENT_FLAG_CALL
, "Link",
3923 "CallerID2: %s\r\n",
3924 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
3926 o0nativeformats
= c0
->nativeformats
;
3927 o1nativeformats
= c1
->nativeformats
;
3929 if (config
->feature_timer
) {
3930 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->feature_timer
, 1000));
3931 } else if (config
->timelimit
) {
3932 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->timelimit
, 1000));
3933 if (caller_warning
|| callee_warning
)
3934 nexteventts
= ast_tvsub(nexteventts
, ast_samp2tv(config
->play_warning
, 1000));
3937 if (!c0
->tech
->send_digit_begin
)
3938 ast_set_flag(c1
, AST_FLAG_END_DTMF_ONLY
);
3939 if (!c1
->tech
->send_digit_begin
)
3940 ast_set_flag(c0
, AST_FLAG_END_DTMF_ONLY
);
3942 for (/* ever */;;) {
3943 struct timeval now
= { 0, };
3948 if (!ast_tvzero(nexteventts
)) {
3950 to
= ast_tvdiff_ms(nexteventts
, now
);
3952 if (!config
->timelimit
) {
3953 res
= AST_BRIDGE_COMPLETE
;
3960 if (config
->timelimit
) {
3961 time_left_ms
= config
->timelimit
- ast_tvdiff_ms(now
, config
->start_time
);
3962 if (time_left_ms
< to
)
3965 if (time_left_ms
<= 0) {
3966 if (caller_warning
&& config
->end_sound
)
3967 bridge_playfile(c0
, c1
, config
->end_sound
, 0);
3968 if (callee_warning
&& config
->end_sound
)
3969 bridge_playfile(c1
, c0
, config
->end_sound
, 0);
3978 if (time_left_ms
>= 5000 && config
->warning_sound
&& config
->play_warning
) {
3979 int t
= (time_left_ms
+ 500) / 1000; /* round to nearest second */
3981 bridge_playfile(c0
, c1
, config
->warning_sound
, t
);
3983 bridge_playfile(c1
, c0
, config
->warning_sound
, t
);
3985 if (config
->warning_freq
&& (time_left_ms
> (config
->warning_freq
+ 5000)))
3986 nexteventts
= ast_tvadd(nexteventts
, ast_samp2tv(config
->warning_freq
, 1000));
3988 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->timelimit
, 1000));
3992 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
) {
3993 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
3994 c0
->_softhangup
= 0;
3995 if (c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
3996 c1
->_softhangup
= 0;
4000 ast_log(LOG_DEBUG
, "Unbridge signal received. Ending native bridge.\n");
4004 /* Stop if we're a zombie or need a soft hangup */
4005 if (ast_test_flag(c0
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c0
) ||
4006 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c1
)) {
4012 ast_log(LOG_DEBUG
, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
4014 ast_test_flag(c0
, AST_FLAG_ZOMBIE
) ? "Yes" : "No",
4015 ast_check_hangup(c0
) ? "Yes" : "No",
4016 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) ? "Yes" : "No",
4017 ast_check_hangup(c1
) ? "Yes" : "No");
4021 if (c0
->tech
->bridge
&&
4022 (config
->timelimit
== 0) &&
4023 (c0
->tech
->bridge
== c1
->tech
->bridge
) &&
4024 !nativefailed
&& !c0
->monitor
&& !c1
->monitor
&&
4025 !c0
->spies
&& !c1
->spies
&& !ast_test_flag(&(config
->features_callee
),AST_FEATURE_REDIRECT
) &&
4026 !ast_test_flag(&(config
->features_caller
),AST_FEATURE_REDIRECT
) ) {
4027 /* Looks like they share a bridge method and nothing else is in the way */
4028 ast_set_flag(c0
, AST_FLAG_NBRIDGE
);
4029 ast_set_flag(c1
, AST_FLAG_NBRIDGE
);
4030 if ((res
= c0
->tech
->bridge(c0
, c1
, config
->flags
, fo
, rc
, to
)) == AST_BRIDGE_COMPLETE
) {
4031 /* \todo XXX here should check that cid_num is not NULL */
4032 manager_event(EVENT_FLAG_CALL
, "Unlink",
4038 "CallerID2: %s\r\n",
4039 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4041 ast_log(LOG_DEBUG
, "Returning from native bridge, channels: %s, %s\n", c0
->name
, c1
->name
);
4043 ast_clear_flag(c0
, AST_FLAG_NBRIDGE
);
4044 ast_clear_flag(c1
, AST_FLAG_NBRIDGE
);
4046 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4054 ast_clear_flag(c0
, AST_FLAG_NBRIDGE
);
4055 ast_clear_flag(c1
, AST_FLAG_NBRIDGE
);
4058 case AST_BRIDGE_RETRY
:
4061 if (option_verbose
> 2)
4062 ast_verbose(VERBOSE_PREFIX_3
"Native bridging %s and %s ended\n",
4063 c0
->name
, c1
->name
);
4065 case AST_BRIDGE_FAILED_NOWARN
:
4071 if (((c0
->writeformat
!= c1
->readformat
) || (c0
->readformat
!= c1
->writeformat
) ||
4072 (c0
->nativeformats
!= o0nativeformats
) || (c1
->nativeformats
!= o1nativeformats
)) &&
4073 !(c0
->generator
|| c1
->generator
)) {
4074 if (ast_channel_make_compatible(c0
, c1
)) {
4075 ast_log(LOG_WARNING
, "Can't make %s and %s compatible\n", c0
->name
, c1
->name
);
4076 /* \todo XXX here should check that cid_num is not NULL */
4077 manager_event(EVENT_FLAG_CALL
, "Unlink",
4083 "CallerID2: %s\r\n",
4084 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4085 return AST_BRIDGE_FAILED
;
4087 o0nativeformats
= c0
->nativeformats
;
4088 o1nativeformats
= c1
->nativeformats
;
4090 res
= ast_generic_bridge(c0
, c1
, config
, fo
, rc
, nexteventts
);
4091 if (res
!= AST_BRIDGE_RETRY
)
4095 ast_clear_flag(c0
, AST_FLAG_END_DTMF_ONLY
);
4096 ast_clear_flag(c1
, AST_FLAG_END_DTMF_ONLY
);
4101 /* \todo XXX here should check that cid_num is not NULL */
4102 manager_event(EVENT_FLAG_CALL
, "Unlink",
4108 "CallerID2: %s\r\n",
4109 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4111 ast_log(LOG_DEBUG
, "Bridge stops bridging channels %s and %s\n", c0
->name
, c1
->name
);
4116 /*! \brief Sets an option on a channel */
4117 int ast_channel_setoption(struct ast_channel
*chan
, int option
, void *data
, int datalen
, int block
)
4121 if (chan
->tech
->setoption
) {
4122 res
= chan
->tech
->setoption(chan
, option
, data
, datalen
);
4130 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4131 intermediate packets. XXX */
4132 ast_log(LOG_ERROR
, "XXX Blocking not implemented yet XXX\n");
4138 struct tonepair_def
{
4145 struct tonepair_state
{
4159 unsigned char offset
[AST_FRIENDLY_OFFSET
];
4163 static void tonepair_release(struct ast_channel
*chan
, void *params
)
4165 struct tonepair_state
*ts
= params
;
4168 ast_set_write_format(chan
, ts
->origwfmt
);
4172 static void *tonepair_alloc(struct ast_channel
*chan
, void *params
)
4174 struct tonepair_state
*ts
;
4175 struct tonepair_def
*td
= params
;
4177 if (!(ts
= ast_calloc(1, sizeof(*ts
))))
4179 ts
->origwfmt
= chan
->writeformat
;
4180 if (ast_set_write_format(chan
, AST_FORMAT_SLINEAR
)) {
4181 ast_log(LOG_WARNING
, "Unable to set '%s' to signed linear format (write)\n", chan
->name
);
4182 tonepair_release(NULL
, ts
);
4185 ts
->fac1
= 2.0 * cos(2.0 * M_PI
* (td
->freq1
/ 8000.0)) * 32768.0;
4187 ts
->v2_1
= sin(-4.0 * M_PI
* (td
->freq1
/ 8000.0)) * td
->vol
;
4188 ts
->v3_1
= sin(-2.0 * M_PI
* (td
->freq1
/ 8000.0)) * td
->vol
;
4190 ts
->fac2
= 2.0 * cos(2.0 * M_PI
* (td
->freq2
/ 8000.0)) * 32768.0;
4191 ts
->v2_2
= sin(-4.0 * M_PI
* (td
->freq2
/ 8000.0)) * td
->vol
;
4192 ts
->v3_2
= sin(-2.0 * M_PI
* (td
->freq2
/ 8000.0)) * td
->vol
;
4193 ts
->duration
= td
->duration
;
4196 /* Let interrupts interrupt :) */
4197 ast_set_flag(chan
, AST_FLAG_WRITE_INT
);
4201 static int tonepair_generator(struct ast_channel
*chan
, void *data
, int len
, int samples
)
4203 struct tonepair_state
*ts
= data
;
4206 /* we need to prepare a frame with 16 * timelen samples as we're
4207 * generating SLIN audio
4211 if (len
> sizeof(ts
->data
) / 2 - 1) {
4212 ast_log(LOG_WARNING
, "Can't generate that much data!\n");
4215 memset(&ts
->f
, 0, sizeof(ts
->f
));
4216 for (x
=0;x
<len
/2;x
++) {
4217 ts
->v1_1
= ts
->v2_1
;
4218 ts
->v2_1
= ts
->v3_1
;
4219 ts
->v3_1
= (ts
->fac1
* ts
->v2_1
>> 15) - ts
->v1_1
;
4221 ts
->v1_2
= ts
->v2_2
;
4222 ts
->v2_2
= ts
->v3_2
;
4223 ts
->v3_2
= (ts
->fac2
* ts
->v2_2
>> 15) - ts
->v1_2
;
4226 p
= ts
->v3_2
- 32768;
4228 p
= ((p
* 9) / 10) + 1;
4229 ts
->data
[x
] = (ts
->v3_1
* p
) >> 15;
4231 ts
->data
[x
] = ts
->v3_1
+ ts
->v3_2
;
4233 ts
->f
.frametype
= AST_FRAME_VOICE
;
4234 ts
->f
.subclass
= AST_FORMAT_SLINEAR
;
4235 ts
->f
.datalen
= len
;
4236 ts
->f
.samples
= samples
;
4237 ts
->f
.offset
= AST_FRIENDLY_OFFSET
;
4238 ts
->f
.data
= ts
->data
;
4239 ast_write(chan
, &ts
->f
);
4241 if (ts
->duration
> 0) {
4242 if (ts
->pos
>= ts
->duration
* 8)
4248 static struct ast_generator tonepair
= {
4249 alloc
: tonepair_alloc
,
4250 release
: tonepair_release
,
4251 generate
: tonepair_generator
,
4254 int ast_tonepair_start(struct ast_channel
*chan
, int freq1
, int freq2
, int duration
, int vol
)
4256 struct tonepair_def d
= { 0, };
4260 d
.duration
= duration
;
4261 d
.vol
= (vol
< 1) ? 8192 : vol
; /* force invalid to 8192 */
4262 if (ast_activate_generator(chan
, &tonepair
, &d
))
4267 void ast_tonepair_stop(struct ast_channel
*chan
)
4269 ast_deactivate_generator(chan
);
4272 int ast_tonepair(struct ast_channel
*chan
, int freq1
, int freq2
, int duration
, int vol
)
4276 if ((res
= ast_tonepair_start(chan
, freq1
, freq2
, duration
, vol
)))
4279 /* Give us some wiggle room */
4280 while (chan
->generatordata
&& ast_waitfor(chan
, 100) >= 0) {
4281 struct ast_frame
*f
= ast_read(chan
);
4290 ast_group_t
ast_get_group(const char *s
)
4294 int start
=0, finish
=0, x
;
4295 ast_group_t group
= 0;
4299 while ((piece
= strsep(&c
, ","))) {
4300 if (sscanf(piece
, "%d-%d", &start
, &finish
) == 2) {
4302 } else if (sscanf(piece
, "%d", &start
)) {
4306 ast_log(LOG_ERROR
, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s
, piece
);
4309 for (x
= start
; x
<= finish
; x
++) {
4310 if ((x
> 63) || (x
< 0)) {
4311 ast_log(LOG_WARNING
, "Ignoring invalid group %d (maximum group is 63)\n", x
);
4313 group
|= ((ast_group_t
) 1 << x
);
4319 static int (*ast_moh_start_ptr
)(struct ast_channel
*, const char *, const char *) = NULL
;
4320 static void (*ast_moh_stop_ptr
)(struct ast_channel
*) = NULL
;
4321 static void (*ast_moh_cleanup_ptr
)(struct ast_channel
*) = NULL
;
4323 void ast_install_music_functions(int (*start_ptr
)(struct ast_channel
*, const char *, const char *),
4324 void (*stop_ptr
)(struct ast_channel
*),
4325 void (*cleanup_ptr
)(struct ast_channel
*))
4327 ast_moh_start_ptr
= start_ptr
;
4328 ast_moh_stop_ptr
= stop_ptr
;
4329 ast_moh_cleanup_ptr
= cleanup_ptr
;
4332 void ast_uninstall_music_functions(void)
4334 ast_moh_start_ptr
= NULL
;
4335 ast_moh_stop_ptr
= NULL
;
4336 ast_moh_cleanup_ptr
= NULL
;
4339 /*! \brief Turn on music on hold on a given channel */
4340 int ast_moh_start(struct ast_channel
*chan
, const char *mclass
, const char *interpclass
)
4342 if (ast_moh_start_ptr
)
4343 return ast_moh_start_ptr(chan
, mclass
, interpclass
);
4345 if (option_verbose
> 2) {
4346 ast_verbose(VERBOSE_PREFIX_3
"Music class %s requested but no musiconhold loaded.\n",
4347 mclass
? mclass
: (interpclass
? interpclass
: "default"));
4353 /*! \brief Turn off music on hold on a given channel */
4354 void ast_moh_stop(struct ast_channel
*chan
)
4356 if (ast_moh_stop_ptr
)
4357 ast_moh_stop_ptr(chan
);
4360 void ast_moh_cleanup(struct ast_channel
*chan
)
4362 if (ast_moh_cleanup_ptr
)
4363 ast_moh_cleanup_ptr(chan
);
4366 void ast_channels_init(void)
4368 ast_cli_register_multiple(cli_channel
, sizeof(cli_channel
) / sizeof(struct ast_cli_entry
));
4371 /*! \brief Print call group and pickup group ---*/
4372 char *ast_print_group(char *buf
, int buflen
, ast_group_t group
)
4380 if (!group
) /* Return empty string if no group */
4383 for (i
= 0; i
<= 63; i
++) { /* Max group is 63 */
4384 if (group
& ((ast_group_t
) 1 << i
)) {
4386 strncat(buf
, ", ", buflen
);
4390 snprintf(num
, sizeof(num
), "%u", i
);
4391 strncat(buf
, num
, buflen
);
4397 void ast_set_variables(struct ast_channel
*chan
, struct ast_variable
*vars
)
4399 struct ast_variable
*cur
;
4401 for (cur
= vars
; cur
; cur
= cur
->next
)
4402 pbx_builtin_setvar_helper(chan
, cur
->name
, cur
->value
);
4405 static void copy_data_from_queue(struct ast_channel_spy_queue
*queue
, short *buf
, unsigned int samples
)
4407 struct ast_frame
*f
;
4412 if (!(f
= AST_LIST_FIRST(&queue
->list
))) {
4413 ast_log(LOG_ERROR
, "Ran out of frames before buffer filled!\n");
4417 tocopy
= (f
->samples
> samples
) ? samples
: f
->samples
;
4418 bytestocopy
= ast_codec_get_len(queue
->format
, tocopy
);
4419 memcpy(buf
, f
->data
, bytestocopy
);
4422 f
->samples
-= tocopy
;
4423 f
->data
+= bytestocopy
;
4424 f
->datalen
-= bytestocopy
;
4425 f
->offset
+= bytestocopy
;
4426 queue
->samples
-= tocopy
;
4429 ast_frfree(AST_LIST_REMOVE_HEAD(&queue
->list
, frame_list
));
4433 struct ast_frame
*ast_channel_spy_read_frame(struct ast_channel_spy
*spy
, unsigned int samples
)
4435 struct ast_frame
*result
;
4436 /* buffers are allocated to hold SLINEAR, which is the largest format */
4437 short read_buf
[samples
];
4438 short write_buf
[samples
];
4439 struct ast_frame
*read_frame
;
4440 struct ast_frame
*write_frame
;
4442 struct ast_frame stack_read_frame
= { .frametype
= AST_FRAME_VOICE
,
4443 .subclass
= spy
->read_queue
.format
,
4446 .datalen
= ast_codec_get_len(spy
->read_queue
.format
, samples
),
4448 struct ast_frame stack_write_frame
= { .frametype
= AST_FRAME_VOICE
,
4449 .subclass
= spy
->write_queue
.format
,
4452 .datalen
= ast_codec_get_len(spy
->write_queue
.format
, samples
),
4455 /* if a flush has been requested, dump everything in whichever queue is larger */
4456 if (ast_test_flag(spy
, CHANSPY_TRIGGER_FLUSH
)) {
4457 if (spy
->read_queue
.samples
> spy
->write_queue
.samples
) {
4458 if (ast_test_flag(spy
, CHANSPY_READ_VOLADJUST
)) {
4459 AST_LIST_TRAVERSE(&spy
->read_queue
.list
, result
, frame_list
)
4460 ast_frame_adjust_volume(result
, spy
->read_vol_adjustment
);
4462 result
= AST_LIST_FIRST(&spy
->read_queue
.list
);
4463 AST_LIST_HEAD_SET_NOLOCK(&spy
->read_queue
.list
, NULL
);
4464 spy
->read_queue
.samples
= 0;
4466 if (ast_test_flag(spy
, CHANSPY_WRITE_VOLADJUST
)) {
4467 AST_LIST_TRAVERSE(&spy
->write_queue
.list
, result
, frame_list
)
4468 ast_frame_adjust_volume(result
, spy
->write_vol_adjustment
);
4470 result
= AST_LIST_FIRST(&spy
->write_queue
.list
);
4471 AST_LIST_HEAD_SET_NOLOCK(&spy
->write_queue
.list
, NULL
);
4472 spy
->write_queue
.samples
= 0;
4474 ast_clear_flag(spy
, CHANSPY_TRIGGER_FLUSH
);
4478 if ((spy
->read_queue
.samples
< samples
) || (spy
->write_queue
.samples
< samples
))
4481 /* short-circuit if both head frames have exactly what we want */
4482 if ((AST_LIST_FIRST(&spy
->read_queue
.list
)->samples
== samples
) &&
4483 (AST_LIST_FIRST(&spy
->write_queue
.list
)->samples
== samples
)) {
4484 read_frame
= AST_LIST_REMOVE_HEAD(&spy
->read_queue
.list
, frame_list
);
4485 write_frame
= AST_LIST_REMOVE_HEAD(&spy
->write_queue
.list
, frame_list
);
4487 spy
->read_queue
.samples
-= samples
;
4488 spy
->write_queue
.samples
-= samples
;
4492 copy_data_from_queue(&spy
->read_queue
, read_buf
, samples
);
4493 copy_data_from_queue(&spy
->write_queue
, write_buf
, samples
);
4495 read_frame
= &stack_read_frame
;
4496 write_frame
= &stack_write_frame
;
4500 if (ast_test_flag(spy
, CHANSPY_READ_VOLADJUST
))
4501 ast_frame_adjust_volume(read_frame
, spy
->read_vol_adjustment
);
4503 if (ast_test_flag(spy
, CHANSPY_WRITE_VOLADJUST
))
4504 ast_frame_adjust_volume(write_frame
, spy
->write_vol_adjustment
);
4506 if (ast_test_flag(spy
, CHANSPY_MIXAUDIO
)) {
4507 ast_frame_slinear_sum(read_frame
, write_frame
);
4510 result
= ast_frdup(read_frame
);
4512 result
= read_frame
;
4513 ast_frfree(write_frame
);
4517 result
= ast_frdup(read_frame
);
4518 AST_LIST_NEXT(result
, frame_list
) = ast_frdup(write_frame
);
4520 result
= read_frame
;
4521 AST_LIST_NEXT(result
, frame_list
) = write_frame
;
4528 static void *silence_generator_alloc(struct ast_channel
*chan
, void *data
)
4530 /* just store the data pointer in the channel structure */
4534 static void silence_generator_release(struct ast_channel
*chan
, void *data
)
4539 static int silence_generator_generate(struct ast_channel
*chan
, void *data
, int len
, int samples
)
4542 struct ast_frame frame
= {
4543 .frametype
= AST_FRAME_VOICE
,
4544 .subclass
= AST_FORMAT_SLINEAR
,
4547 .datalen
= sizeof(buf
),
4549 memset(buf
, 0, sizeof(buf
));
4550 if (ast_write(chan
, &frame
))
4555 static struct ast_generator silence_generator
= {
4556 .alloc
= silence_generator_alloc
,
4557 .release
= silence_generator_release
,
4558 .generate
= silence_generator_generate
,
4561 struct ast_silence_generator
{
4562 int old_write_format
;
4565 struct ast_silence_generator
*ast_channel_start_silence_generator(struct ast_channel
*chan
)
4567 struct ast_silence_generator
*state
;
4569 if (!(state
= ast_calloc(1, sizeof(*state
)))) {
4573 state
->old_write_format
= chan
->writeformat
;
4575 if (ast_set_write_format(chan
, AST_FORMAT_SLINEAR
) < 0) {
4576 ast_log(LOG_ERROR
, "Could not set write format to SLINEAR\n");
4581 ast_activate_generator(chan
, &silence_generator
, state
);
4584 ast_log(LOG_DEBUG
, "Started silence generator on '%s'\n", chan
->name
);
4589 void ast_channel_stop_silence_generator(struct ast_channel
*chan
, struct ast_silence_generator
*state
)
4594 ast_deactivate_generator(chan
);
4597 ast_log(LOG_DEBUG
, "Stopped silence generator on '%s'\n", chan
->name
);
4599 if (ast_set_write_format(chan
, state
->old_write_format
) < 0)
4600 ast_log(LOG_ERROR
, "Could not return write format to its original state\n");
4606 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4607 const char *channelreloadreason2txt(enum channelreloadreason reason
)
4610 case CHANNEL_MODULE_LOAD
:
4611 return "LOAD (Channel module load)";
4613 case CHANNEL_MODULE_RELOAD
:
4614 return "RELOAD (Channel module reload)";
4616 case CHANNEL_CLI_RELOAD
:
4617 return "CLIRELOAD (Channel module reload by CLI command)";
4620 return "MANAGERRELOAD (Channel module reload by manager)";
4624 #ifdef DEBUG_CHANNEL_LOCKS
4626 /*! \brief Unlock AST channel (and print debugging output)
4627 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4629 int ast_channel_unlock(struct ast_channel
*chan
)
4632 if (option_debug
> 2)
4633 ast_log(LOG_DEBUG
, "::::==== Unlocking AST channel %s\n", chan
->name
);
4637 ast_log(LOG_DEBUG
, "::::==== Unlocking non-existing channel \n");
4641 res
= ast_mutex_unlock(&chan
->lock
);
4643 if (option_debug
> 2) {
4644 #ifdef DEBUG_THREADS
4646 if ((count
= chan
->lock
.reentrancy
))
4647 ast_log(LOG_DEBUG
, ":::=== Still have %d locks (recursive)\n", count
);
4651 ast_log(LOG_DEBUG
, "::::==== Channel %s was unlocked\n", chan
->name
);
4652 if (res
== EINVAL
) {
4654 ast_log(LOG_DEBUG
, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan
->name
);
4658 /* We had no lock, so okay any way*/
4659 if (option_debug
> 3)
4660 ast_log(LOG_DEBUG
, "::::==== Channel %s was not locked at all \n", chan
->name
);
4666 /*! \brief Lock AST channel (and print debugging output)
4667 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4668 int ast_channel_lock(struct ast_channel
*chan
)
4672 if (option_debug
> 3)
4673 ast_log(LOG_DEBUG
, "====:::: Locking AST channel %s\n", chan
->name
);
4675 res
= ast_mutex_lock(&chan
->lock
);
4677 if (option_debug
> 3) {
4678 #ifdef DEBUG_THREADS
4680 if ((count
= chan
->lock
.reentrancy
))
4681 ast_log(LOG_DEBUG
, ":::=== Now have %d locks (recursive)\n", count
);
4684 ast_log(LOG_DEBUG
, "::::==== Channel %s was locked\n", chan
->name
);
4685 if (res
== EDEADLK
) {
4686 /* We had no lock, so okey any way */
4687 if (option_debug
> 3)
4688 ast_log(LOG_DEBUG
, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan
->name
);
4690 if (res
== EINVAL
) {
4691 if (option_debug
> 3)
4692 ast_log(LOG_DEBUG
, "::::==== Channel %s lock failed. No mutex.\n", chan
->name
);
4698 /*! \brief Lock AST channel (and print debugging output)
4699 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4700 int ast_channel_trylock(struct ast_channel
*chan
)
4704 if (option_debug
> 2)
4705 ast_log(LOG_DEBUG
, "====:::: Trying to lock AST channel %s\n", chan
->name
);
4707 res
= ast_mutex_trylock(&chan
->lock
);
4709 if (option_debug
> 2) {
4710 #ifdef DEBUG_THREADS
4712 if ((count
= chan
->lock
.reentrancy
))
4713 ast_log(LOG_DEBUG
, ":::=== Now have %d locks (recursive)\n", count
);
4716 ast_log(LOG_DEBUG
, "::::==== Channel %s was locked\n", chan
->name
);
4718 /* We failed to lock */
4719 if (option_debug
> 2)
4720 ast_log(LOG_DEBUG
, "::::==== Channel %s failed to lock. Not waiting around...\n", chan
->name
);
4722 if (res
== EDEADLK
) {
4723 /* We had no lock, so okey any way*/
4724 if (option_debug
> 2)
4725 ast_log(LOG_DEBUG
, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan
->name
);
4727 if (res
== EINVAL
&& option_debug
> 2)
4728 ast_log(LOG_DEBUG
, "::::==== Channel %s lock failed. No mutex.\n", chan
->name
);
4736 * Wrappers for various ast_say_*() functions that call the full version
4737 * of the same functions.
4738 * The proper place would be say.c, but that file is optional and one
4739 * must be able to build asterisk even without it (using a loadable 'say'
4740 * implementation that only supplies the 'full' version of the functions.
4743 int ast_say_number(struct ast_channel
*chan
, int num
,
4744 const char *ints
, const char *language
, const char *options
)
4746 return ast_say_number_full(chan
, num
, ints
, language
, options
, -1, -1);
4749 int ast_say_enumeration(struct ast_channel
*chan
, int num
,
4750 const char *ints
, const char *language
, const char *options
)
4752 return ast_say_enumeration_full(chan
, num
, ints
, language
, options
, -1, -1);
4755 int ast_say_digits(struct ast_channel
*chan
, int num
,
4756 const char *ints
, const char *lang
)
4758 return ast_say_digits_full(chan
, num
, ints
, lang
, -1, -1);
4761 int ast_say_digit_str(struct ast_channel
*chan
, const char *str
,
4762 const char *ints
, const char *lang
)
4764 return ast_say_digit_str_full(chan
, str
, ints
, lang
, -1, -1);
4767 int ast_say_character_str(struct ast_channel
*chan
, const char *str
,
4768 const char *ints
, const char *lang
)
4770 return ast_say_character_str_full(chan
, str
, ints
, lang
, -1, -1);
4773 int ast_say_phonetic_str(struct ast_channel
*chan
, const char *str
,
4774 const char *ints
, const char *lang
)
4776 return ast_say_phonetic_str_full(chan
, str
, ints
, lang
, -1, -1);
4779 int ast_say_digits_full(struct ast_channel
*chan
, int num
,
4780 const char *ints
, const char *lang
, int audiofd
, int ctrlfd
)
4784 snprintf(buf
, sizeof(buf
), "%d", num
);
4785 return ast_say_digit_str_full(chan
, buf
, ints
, lang
, audiofd
, ctrlfd
);
4788 int ast_channel_whisper_start(struct ast_channel
*chan
)
4793 if (!(chan
->whisper
= ast_calloc(1, sizeof(*chan
->whisper
))))
4796 ast_mutex_init(&chan
->whisper
->lock
);
4797 ast_slinfactory_init(&chan
->whisper
->sf
);
4798 ast_set_flag(chan
, AST_FLAG_WHISPER
);
4803 int ast_channel_whisper_feed(struct ast_channel
*chan
, struct ast_frame
*f
)
4808 ast_mutex_lock(&chan
->whisper
->lock
);
4809 ast_slinfactory_feed(&chan
->whisper
->sf
, f
);
4810 ast_mutex_unlock(&chan
->whisper
->lock
);
4815 void ast_channel_whisper_stop(struct ast_channel
*chan
)
4820 ast_clear_flag(chan
, AST_FLAG_WHISPER
);
4821 if (chan
->whisper
->path
)
4822 ast_translator_free_path(chan
->whisper
->path
);
4823 if (chan
->whisper
->original_format
&& chan
->writeformat
== AST_FORMAT_SLINEAR
)
4824 ast_set_write_format(chan
, chan
->whisper
->original_format
);
4825 ast_slinfactory_destroy(&chan
->whisper
->sf
);
4826 ast_mutex_destroy(&chan
->whisper
->lock
);
4827 free(chan
->whisper
);
4828 chan
->whisper
= NULL
;